"use client";

/**
 * Inline Schema Section
 * ─────────────────────
 * Accordion-style schema section used by both the SEO Content Brief
 * and the LLMO Content Brief. Each schema renders as a collapsed tile
 * (name + short badge) that expands to show its description, a "why
 * it helps" hint, and the JSON-LD payload in an editable code block.
 *
 * The JSON-LD payloads come from brief-schema-generator.ts — this
 * component is purely presentational. Both callers pass the same
 * SchemaItem[] shape; the component does not distinguish SEO vs LLMO
 * schemas because the presentation is identical.
 *
 * Users copy schemas individually or all-at-once; the "Copy All"
 * button produces a single <script type="application/ld+json"> block
 * per schema, separated by blank lines, ready to paste into a page.
 */

import { useMemo, useState } from "react";
import { ChevronDown, Copy, Check, Code2, Info } from "lucide-react";
import type { SchemaItem } from "@/lib/services/brief-schema-generator";

interface Props {
  /** Schemas produced by generateSEOSchemas() or generateLLMOSchemas(). */
  schemas: SchemaItem[];
  /** Title shown at the top of the section. Defaults to "Schema Markup". */
  title?: string;
  /** Short explanatory subtitle. Falls back to a generic description. */
  subtitle?: string;
  /** Optional badge shown next to the title (e.g. "SEO" or "LLMO"). */
  badge?: string;
  /** Tailwind color class for the badge background. Defaults to slate. */
  badgeColorClass?: string;
}

// ─── Per-schema row ─────────────────────────────────────────────────────────

function SchemaRow({ schema, index }: { schema: SchemaItem; index: number }) {
  const [expanded, setExpanded] = useState(index === 0); // first row open by default
  const [copied, setCopied] = useState(false);

  // Pretty-printed JSON — memoised so we don't re-stringify on every render.
  const jsonString = useMemo(() => JSON.stringify(schema.json, null, 2), [schema.json]);

  // Derive a badge-friendly @type label for the collapsed tile so users can
  // identify schemas at a glance without opening them.
  const typeLabel = useMemo(() => {
    const t = schema.json["@type"];
    return typeof t === "string" ? t : "Schema";
  }, [schema.json]);

  function handleCopy() {
    navigator.clipboard.writeText(jsonString).then(
      () => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1500);
      },
      () => {
        // clipboard denied — no-op; the user can still select the text.
      },
    );
  }

  return (
    <div className="border border-slate-200 rounded-lg bg-white overflow-hidden">
      {/* Header — always visible, click to toggle */}
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="w-full flex items-center justify-between px-4 py-3 hover:bg-slate-50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <Code2 className="w-4 h-4 text-slate-400 shrink-0" />
          <div className="text-left">
            <div className="font-semibold text-sm text-slate-800">{schema.name}</div>
            <div className="text-[11px] text-slate-500 line-clamp-1">{schema.description}</div>
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-slate-100 text-slate-600">
            {typeLabel}
          </span>
          <ChevronDown
            className={`w-4 h-4 text-slate-400 transition-transform ${expanded ? "rotate-180" : ""}`}
          />
        </div>
      </button>

      {/* Expanded body */}
      {expanded && (
        <div className="border-t border-slate-200 px-4 py-3 space-y-3">
          {/* Description */}
          <p className="text-sm text-slate-600">{schema.description}</p>

          {/* Why it helps */}
          <div className="flex gap-2 p-3 rounded-md bg-blue-50 border border-blue-100">
            <Info className="w-4 h-4 text-blue-600 shrink-0 mt-0.5" />
            <p className="text-xs text-blue-900 leading-relaxed">
              <span className="font-semibold">Why it helps: </span>
              {schema.whyItHelps}
            </p>
          </div>

          {/* JSON payload */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-semibold text-slate-700">JSON-LD</span>
              <button
                type="button"
                onClick={handleCopy}
                className="text-[11px] px-2.5 py-1 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium flex items-center gap-1"
              >
                {copied ? (
                  <>
                    <Check className="w-3 h-3 text-green-600" /> Copied
                  </>
                ) : (
                  <>
                    <Copy className="w-3 h-3" /> Copy
                  </>
                )}
              </button>
            </div>
            <pre className="w-full max-h-72 overflow-auto font-mono text-[11px] leading-relaxed bg-[#0F172A] text-[#4ADE80] p-3 rounded-lg border border-slate-700 whitespace-pre">
              {jsonString}
            </pre>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Section wrapper ────────────────────────────────────────────────────────

export default function InlineSchemaSection({
  schemas,
  title = "Schema Markup",
  subtitle,
  badge,
  badgeColorClass = "bg-slate-100 text-slate-700",
}: Props) {
  const [copiedAll, setCopiedAll] = useState(false);

  const defaultSubtitle =
    "JSON-LD schemas tailored to this content brief. Copy each one below and paste it into your page inside a <script type=\"application/ld+json\"> tag.";

  // "Copy All" produces a single string with each schema wrapped in its own
  // <script type="application/ld+json"> block, separated by blank lines.
  // Users typically paste this straight into a page template.
  function handleCopyAll() {
    if (!schemas.length) return;
    const blob = schemas
      .map((s) => `<script type="application/ld+json">\n${JSON.stringify(s.json, null, 2)}\n</script>`)
      .join("\n\n");
    navigator.clipboard.writeText(blob).then(
      () => {
        setCopiedAll(true);
        setTimeout(() => setCopiedAll(false), 2000);
      },
      () => {},
    );
  }

  if (!schemas.length) {
    return (
      <div className="bg-slate-50 border border-slate-200 rounded-lg p-6 text-center">
        <Code2 className="w-8 h-8 text-slate-400 mx-auto mb-2" />
        <p className="text-sm text-slate-600">
          No schemas match this content type yet. Fill in topic, keyword, and FAQ questions to generate schemas.
        </p>
      </div>
    );
  }

  return (
    <section className="space-y-4">
      {/* Section header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-lg font-bold text-slate-900">{title}</h3>
            {badge && (
              <span className={`text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wide ${badgeColorClass}`}>
                {badge}
              </span>
            )}
            <span className="text-[10px] font-semibold px-2 py-0.5 rounded bg-slate-100 text-slate-600">
              {schemas.length} {schemas.length === 1 ? "schema" : "schemas"}
            </span>
          </div>
          <p className="text-xs text-slate-500 max-w-2xl">{subtitle ?? defaultSubtitle}</p>
        </div>
        <button
          type="button"
          onClick={handleCopyAll}
          className="shrink-0 text-xs px-3 py-1.5 rounded-md bg-blue-600 hover:bg-blue-700 text-white font-semibold flex items-center gap-1.5"
        >
          {copiedAll ? (
            <>
              <Check className="w-3.5 h-3.5" /> Copied all
            </>
          ) : (
            <>
              <Copy className="w-3.5 h-3.5" /> Copy all schemas
            </>
          )}
        </button>
      </div>

      {/* Schema rows */}
      <div className="space-y-2">
        {schemas.map((schema, i) => (
          <SchemaRow key={`${schema.name}-${i}`} schema={schema} index={i} />
        ))}
      </div>

      {/* Paste instructions */}
      <div className="flex gap-2 p-3 rounded-md bg-amber-50 border border-amber-200">
        <Info className="w-4 h-4 text-amber-700 shrink-0 mt-0.5" />
        <div className="text-xs text-amber-900 leading-relaxed">
          <span className="font-semibold">How to deploy: </span>
          Copy each schema and paste it inside a{" "}
          <code className="font-mono text-[11px] px-1 py-0.5 rounded bg-amber-100">
            &lt;script type=&quot;application/ld+json&quot;&gt;...&lt;/script&gt;
          </code>{" "}
          tag in your page&apos;s HTML head. Replace any{" "}
          <code className="font-mono text-[11px] px-1 py-0.5 rounded bg-amber-100">[placeholder]</code>{" "}
          text with your real content before publishing, and validate with Google&apos;s Rich Results Test.
        </div>
      </div>
    </section>
  );
}
