"use client";

/**
 * Code preview panel — shows the generated HTML or JSX for the current
 * page. No syntax highlighter dependency; a plain dark pre/code block
 * with tabular font keeps the bundle small. Toggle between HTML and
 * React; copy to clipboard with a transient "Copied!" toast.
 */

import { useMemo, useState } from "react";
import { Copy, Check, Code2, FileCode } from "lucide-react";
import type { Section, Branding } from "@/lib/page-studio/section-registry";
import { exportPageToHtml, type ExportablePage } from "@/lib/page-studio/html-exporter";
import { exportPageToReact } from "@/lib/page-studio/react-exporter";

interface Props {
  title: string;
  metaTitle: string;
  metaDescription: string;
  sections: Section[];
  branding: Branding;
}

type Format = "html" | "react";

export default function CodePreview({ title, metaTitle, metaDescription, sections, branding }: Props) {
  const [format, setFormat] = useState<Format>("html");
  const [copied, setCopied] = useState(false);

  const code = useMemo(() => {
    const page: ExportablePage = { title, metaTitle, metaDescription, sections, branding };
    return format === "html" ? exportPageToHtml(page) : exportPageToReact(page);
  }, [format, title, metaTitle, metaDescription, sections, branding]);

  async function copy() {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {/* clipboard may be blocked */ }
  }

  return (
    <div className="flex flex-col h-full bg-slate-900">
      <div className="flex items-center justify-between border-b border-slate-800 px-4 py-2.5 bg-slate-950">
        <div className="flex bg-slate-800 rounded-lg p-0.5">
          {(["html", "react"] as const).map((f) => {
            const Icon = f === "html" ? Code2 : FileCode;
            return (
              <button
                key={f}
                onClick={() => setFormat(f)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold uppercase tracking-wide transition-colors ${
                  format === f ? "bg-slate-700 text-white" : "text-slate-400 hover:text-slate-200"
                }`}
              >
                <Icon className="w-3.5 h-3.5" /> {f}
              </button>
            );
          })}
        </div>
        <button
          onClick={copy}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-semibold"
        >
          {copied ? <Check className="w-3.5 h-3.5 text-green-400" /> : <Copy className="w-3.5 h-3.5" />}
          {copied ? "Copied!" : "Copy Code"}
        </button>
      </div>
      <div className="flex-1 overflow-auto">
        <pre className="m-0 p-5 text-[12px] leading-relaxed text-slate-200 font-mono whitespace-pre">
          <code>{code}</code>
        </pre>
      </div>
    </div>
  );
}
