"use client";

/**
 * BriefSchemaSection — inline JSON-LD generator for Content Briefs.
 * ──────────────────────────────────────────────────────────────────
 * Rendered below the main brief output on both the SEO
 * (/content-brief) and LLMO (/llmo-content-brief) pages. Lets the
 * user generate appropriate structured-data markup scaffolded from
 * the brief's title / description / keyword, then copy it straight
 * into their CMS or page <head>.
 *
 * Intentionally NOT persisted — this is a copy-paste workflow. The
 * existing /api/schema/save route handles persistence if the user
 * wants to catalogue the schema on the Schema Generator page later.
 *
 * Differentiation between SEO and LLMO is passed through `briefType`
 * into /api/schema/generate-for-brief, which routes to different
 * system prompts server-side — the two pages share this component
 * but get meaningfully different output.
 */

import { useState } from "react";
import { Sparkles, Loader2, Copy, FileCode, AlertCircle, Check } from "lucide-react";

interface BriefSchemaResponse {
  schemaType: string;
  jsonLd: Record<string, unknown>;
  reasoning: string;
  typeReasoning: string;
}

interface Props {
  brandId: string;
  briefType: "seo" | "llmo";
  /** Recommended page title from the brief. */
  title?: string;
  /** Meta description from the brief. */
  description?: string;
  /** Target search keyword from the brief's keyword research. */
  keyword?: string;
  /** Secondary keywords — rolled into schema.keywords. */
  secondaryKeywords?: string[];
  /** Brief mode (SEO only — "standard" vs "humanized"). */
  mode?: "standard" | "humanized";
  /** Free-form text for the AI's type inference — falls back to
   *  title + keyword server-side. Pass the brief intro / H1 when
   *  available for higher-accuracy auto-detection (FAQPage /
   *  HowTo / Service / LocalBusiness / MedicalWebPage / etc.). */
  contentSignal?: string;
}

export default function BriefSchemaSection(props: Props) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<BriefSchemaResponse | null>(null);
  const [toast, setToast] = useState<string | null>(null);

  function flash(msg: string) {
    setToast(msg);
    setTimeout(() => setToast(null), 1800);
  }

  async function generate() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/schema/generate-for-brief", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brandId: props.brandId,
          briefType: props.briefType,
          title: props.title,
          description: props.description,
          keyword: props.keyword,
          secondaryKeywords: props.secondaryKeywords,
          mode: props.mode,
          contentSignal: props.contentSignal,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || `Request failed (HTTP ${res.status})`);
      } else {
        setResult(data as BriefSchemaResponse);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Network error");
    } finally {
      setLoading(false);
    }
  }

  /** Clipboard writer with execCommand fallback. Same pattern as
   *  the Schema Generator page so users get identical behaviour on
   *  older browsers / insecure contexts. */
  async function copyToClipboard(text: string, successMsg: string) {
    try {
      if (typeof navigator !== "undefined" && navigator.clipboard) {
        await navigator.clipboard.writeText(text);
      } else {
        const ta = document.createElement("textarea");
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      }
      flash(successMsg);
    } catch {
      flash("Copy failed");
    }
  }

  const jsonString = result ? JSON.stringify(result.jsonLd, null, 2) : "";
  const scriptTag = result ? `<script type="application/ld+json">\n${jsonString}\n</script>` : "";

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between gap-3 flex-wrap">
        <div>
          <h2 className="text-sm font-bold text-slate-800 flex items-center gap-2">
            <FileCode className="w-4 h-4 text-violet-600" />
            Schema Markup
            <span className="text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded border bg-violet-50 text-violet-700 border-violet-200">
              {props.briefType === "llmo" ? "LLMO" : "SEO"}
            </span>
          </h2>
          <p className="text-[11px] text-slate-400 mt-0.5">
            Generate JSON-LD to paste into the{" "}
            <code className="text-[10px] bg-slate-100 px-1 rounded">&lt;head&gt;</code>
            {" "}of your page. Auto-detects schema type from the brief.
          </p>
        </div>
        <button
          onClick={generate}
          disabled={loading}
          className="inline-flex items-center gap-2 px-4 py-2 text-xs font-semibold rounded-lg bg-slate-900 text-white hover:bg-slate-800 disabled:opacity-50"
        >
          {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
          {loading ? "Generating…" : result ? "Regenerate" : "Generate Schema"}
        </button>
      </div>

      {error && (
        <div className="px-5 py-3 bg-red-50 border-b border-red-100 text-xs text-red-700 flex items-start gap-2">
          <AlertCircle className="w-3.5 h-3.5 mt-0.5 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {/* Empty state — no result yet + not loading + no error. A
          plain "click Generate" hint avoids the section reading as
          broken when the brief first renders. */}
      {!result && !loading && !error && (
        <div className="px-5 py-8 text-center text-xs text-slate-400">
          Click <span className="font-semibold text-slate-600">Generate Schema</span> to scaffold{" "}
          {props.briefType === "llmo" ? "LLMO citation-friendly" : "SEO rich-results"} JSON-LD for this brief.
        </div>
      )}

      {/* Result panel */}
      {result && (
        <div className="p-5 space-y-4">
          {/* Type badge + reasoning. Short, inline — users should
              see WHY this @type before they copy. */}
          <div className="flex items-start gap-3 flex-wrap">
            <span className="inline-flex items-center gap-1.5 text-xs font-bold px-2.5 py-1 rounded-md bg-slate-900 text-slate-100">
              @type: {result.schemaType}
            </span>
            <p className="text-[11px] text-slate-500 flex-1 min-w-[200px] italic leading-relaxed">
              {result.typeReasoning}
            </p>
          </div>

          {/* JSON-LD code block. Pre/code with overflow-x-auto so
              long keyword lists don't force the whole page to
              horizontal-scroll. Monospace size small so 40-line
              schemas stay within a reasonable viewport window. */}
          <div className="relative group">
            <pre className="text-[11px] leading-relaxed bg-slate-50 border border-slate-200 rounded-lg p-3 overflow-x-auto max-h-[400px] overflow-y-auto font-mono">
              {jsonString}
            </pre>
          </div>

          {/* Field-filling reasoning — separate from the @type
              reasoning above. This explains WHY the AI picked the
              specific fields it populated (keywords array, author
              org, datePublished today, etc.). */}
          {result.reasoning && (
            <p className="text-[11px] text-slate-500 leading-relaxed">
              <span className="font-semibold text-slate-600">Why these fields:</span> {result.reasoning}
            </p>
          )}

          {/* Action buttons */}
          <div className="flex items-center gap-2 flex-wrap pt-1">
            <button
              onClick={() => copyToClipboard(jsonString, "JSON-LD copied")}
              className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700"
            >
              <Copy className="w-3 h-3" /> Copy JSON-LD
            </button>
            <button
              onClick={() => copyToClipboard(scriptTag, "Script tag copied")}
              className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700"
            >
              <FileCode className="w-3 h-3" /> Copy &lt;script&gt; tag
            </button>
            <p className="text-[10px] text-slate-400 ml-auto">
              Paste into your page&apos;s <code className="bg-slate-100 px-1 rounded">&lt;head&gt;</code>.
              {" "}Not deployed via Site Tag.
            </p>
          </div>
        </div>
      )}

      {toast && (
        <div className="fixed bottom-4 right-4 z-50 px-4 py-2 rounded-lg bg-slate-900 text-white text-xs font-semibold shadow-lg flex items-center gap-2">
          <Check className="w-3 h-3" /> {toast}
        </div>
      )}
    </div>
  );
}
