"use client";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { ArrowDown, ArrowLeft, ArrowUp, Copy, ExternalLink, Plus, Rocket, Save, Trash2 } from "lucide-react";
import { Badge, Button, Card, Checkbox, Field, Input, Select, Spinner, Tabs, Textarea, Toggle, api, cx, useAction, useUI } from "@/components/ui";
import { ago, useApi, useIndustry } from "@/components/hooks";

const FIELD_TYPES = ["text", "email", "phone", "number", "select", "textarea", "checkbox", "hidden"];
const MAP_TARGETS = [["", "Auto"], ["name", "Full name"], ["first_name", "First name"], ["last_name", "Last name"], ["email", "Email"], ["phone", "Phone"], ["city", "City"]];
const BLOCK_TYPES = ["hero", "features", "text", "image", "form", "cta", "testimonial", "faq", "gallery"];

export default function FormEditor() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const f = useApi<{ data: any }>(`/forms/${id}`);
  const forms = useApi<{ data: any[] }>("/forms");
  const cf = useApi<{ data: any[] }>("/custom-fields");
  const ws = useApi<{ data: any }>("/workspace");
  const [d, setD] = useState<any>(null);
  const [tab, setTab] = useState("build");
  const [dirty, setDirty] = useState(false);
  const { busy, run } = useAction();
  const { push, confirm } = useUI();
  useEffect(() => { if (f.data) { setD(structuredClone(f.data.data)); setDirty(false); } }, [f.data]);
  if (!d) return <div className="flex justify-center py-20"><Spinner /></div>;
  const s = d.schema;
  const set = (patch: any) => { setD({ ...d, ...patch }); setDirty(true); };
  const setS = (patch: any) => set({ schema: { ...s, ...patch } });
  const slug = ws.data?.data.slug;
  const hosted = typeof window !== "undefined" ? `${location.origin}/${d.type === "page" ? "p" : "f"}/${slug}/${d.slug}` : "";
  const save = (status?: string) => run(async () => {
    await api(`/forms/${id}`, { method: "PATCH", body: { name: d.name, slug: d.slug, schema: s, variants: d.variants, pixels: d.pixels, domain: d.domain || null, ...(status ? { status } : {}) } });
    f.reload();
  }, status === "published" ? "Published" : "Saved");

  return (
    <>
      <div className="mb-4 flex flex-wrap items-center gap-2">
        <Link href="/forms" className="grid h-8 w-8 place-items-center rounded-[7px] hover:bg-ink/[.06]" aria-label="Back"><ArrowLeft className="h-4 w-4" /></Link>
        <input className="min-w-[200px] flex-1 bg-transparent font-display text-[20px] font-bold outline-none" value={d.name} onChange={(e) => set({ name: e.target.value })} />
        <Badge tone={d.status === "published" ? "green" : "gray"} dot>{d.status}{d.publishedVersion ? ` · v${d.publishedVersion}` : ""}</Badge>
        {d.status === "published" && <a href={hosted} target="_blank" rel="noreferrer"><Button icon={<ExternalLink className="h-3.5 w-3.5" />}>Open</Button></a>}
        <Button icon={<Save className="h-3.5 w-3.5" />} loading={busy} disabled={!dirty} onClick={() => save()}>Save</Button>
        <Button variant="primary" icon={<Rocket className="h-3.5 w-3.5" />} loading={busy} onClick={() => save("published")}>Publish</Button>
        <Button variant="ghost" aria-label="Delete" onClick={async () => { if (await confirm({ title: "Delete this form?", body: "Submissions stay on contact timelines.", danger: true, confirmLabel: "Delete" })) { await api(`/forms/${id}`, { method: "DELETE" }); router.push("/forms"); } }}><Trash2 className="h-4 w-4" /></Button>
      </div>
      <div className="mb-3"><Tabs value={tab} onChange={setTab} tabs={[{ value: "build", label: "Build" }, ...(d.type === "page" ? [{ value: "ab", label: "A/B test" }] : []), { value: "settings", label: "Tracking & domain" }, { value: "share", label: "Share & embed" }, { value: "results", label: "Results", count: f.data?.data.recent.length }]} /></div>

      {tab === "build" && (d.type === "form" ? <FormBuilder s={s} setS={setS} customFields={cf.data?.data ?? []} /> : <PageBuilder s={s} setS={setS} forms={(forms.data?.data ?? []).filter((x) => x.type === "form")} />)}
      {tab === "ab" && <ABEditor d={d} set={set} />}
      {tab === "settings" && (
        <div className="grid gap-4 lg:grid-cols-2">
          <Card title="Pixels & tags" subtitle="Fire on page view and on submit">
            <div className="space-y-3">
              <Field label="Meta Pixel ID"><Input value={d.pixels?.metaPixelId ?? ""} onChange={(e) => set({ pixels: { ...d.pixels, metaPixelId: e.target.value } })} /></Field>
              <Field label="GA4 Measurement ID"><Input value={d.pixels?.ga4Id ?? ""} onChange={(e) => set({ pixels: { ...d.pixels, ga4Id: e.target.value } })} placeholder="G-XXXXXXX" /></Field>
              <Field label="GTM container ID"><Input value={d.pixels?.gtmId ?? ""} onChange={(e) => set({ pixels: { ...d.pixels, gtmId: e.target.value } })} placeholder="GTM-XXXX" /></Field>
            </div>
          </Card>
          <Card title="URL & domain">
            <div className="space-y-3">
              <Field label="Slug"><Input value={d.slug} onChange={(e) => set({ slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-") })} /></Field>
              {d.type === "page" && <>
                <Field label="Custom domain" hint="Point a CNAME to your app domain (cname.vercel-dns.com on Vercel) and add the domain in Vercel → Domains — SSL is automatic."><Input value={d.domain ?? ""} onChange={(e) => set({ domain: e.target.value })} placeholder="offers.acedevelopers.com" /></Field>
                <Field label="SEO title"><Input value={s.seo?.title ?? ""} onChange={(e) => setS({ seo: { ...s.seo, title: e.target.value } })} /></Field>
                <Field label="SEO description"><Textarea value={s.seo?.description ?? ""} onChange={(e) => setS({ seo: { ...s.seo, description: e.target.value } })} /></Field>
              </>}
              {d.type === "form" && <Toggle checked={!!s.captcha} onChange={(v) => setS({ captcha: v })} label="Require CAPTCHA (Cloudflare Turnstile)" />}
              <p className="text-[11.5px] text-ink-3">Always on: honeypot field, minimum fill time, per-IP rate limiting and phone validation.</p>
            </div>
          </Card>
        </div>
      )}
      {tab === "share" && (
        <div className="space-y-4">
          {d.status !== "published" && <p className="rounded-[9px] bg-warn/10 px-3 py-2 text-[12.5px] text-warn">Publish first — unpublished forms reject submissions.</p>}
          <Snippet title="Hosted URL" code={hosted + "?utm_source=facebook&utm_campaign=launch"} />
          {d.type === "form" && <>
            <Snippet title="Embed (iframe)" code={`<iframe src="${hosted}?embed=1" style="width:100%;max-width:520px;height:640px;border:0" loading="lazy"></iframe>\n<script src="${typeof window !== "undefined" ? location.origin : ""}/t.js" data-ws="${slug}" async></script>`} />
            <Snippet title="REST (server-to-server)" code={`curl -X POST ${typeof window !== "undefined" ? location.origin : ""}/api/v1/forms/${id}/submissions \\\n  -H "Content-Type: application/json" \\\n  -d '{"name":"Rahim","phone":"01712345678","utm_source":"google","gclid":"..."}'`} />
          </>}
          <Snippet title="Website tracking snippet (page views, UTMs, fbclid/gclid, identity stitching)" code={`<script src="${typeof window !== "undefined" ? location.origin : ""}/t.js" data-ws="${slug}" async></script>`} />
        </div>
      )}
      {tab === "results" && (
        <div className="grid gap-4 lg:grid-cols-[320px_1fr]">
          <Card title="Conversion by variant">
            {f.data?.data.ab.map((r: any) => (
              <div key={r.key} className="mb-3">
                <div className="flex justify-between text-[13px]"><b>{r.key === "default" ? "Form" : `Variant ${r.key}`}</b><span>{r.rate.toFixed(1)}%</span></div>
                <div className="mt-1 h-2 overflow-hidden rounded-full bg-ink/[.07]"><div className="h-full rounded-full bg-brand" style={{ width: `${Math.min(100, r.rate * 5)}%` }} /></div>
                <div className="mt-0.5 text-[11px] text-ink-3">{r.submits} / {r.views} views{r.lift != null && ` · ${r.lift >= 0 ? "+" : ""}${r.lift.toFixed(0)}% vs control · ${r.confidence}% confidence`}</div>
              </div>
            ))}
          </Card>
          <Card title="Recent submissions" bodyClass="p-0">
            <table className="table-mac">
              <thead><tr><th>When</th><th>Data</th><th>Source</th><th>Variant</th><th /></tr></thead>
              <tbody>{f.data?.data.recent.map((r: any) => (
                <tr key={r.id}><td className="text-ink-3">{ago(r.createdAt)}</td><td className="max-w-[380px] truncate">{Object.entries(r.data).map(([k, v]) => `${k}: ${v}`).join(" · ")}</td><td className="text-ink-3">{[r.meta.utm_source, r.meta.utm_campaign].filter(Boolean).join(" / ") || (r.meta.gclid ? "gclid" : r.meta.fbclid ? "fbclid" : "direct")}</td><td>{r.variant ?? "—"}</td><td>{r.contactId && <Link href={`/contacts/${r.contactId}`} className="text-brand">Contact →</Link>}</td></tr>
              ))}</tbody>
            </table>
            {!f.data?.data.recent.length && <p className="py-8 text-center text-[13px] text-ink-3">No submissions yet</p>}
          </Card>
        </div>
      )}
    </>
  );
}

function Snippet({ title, code }: { title: string; code: string }) {
  const { push } = useUI();
  return (
    <Card title={title} actions={<Button size="sm" icon={<Copy className="h-3 w-3" />} onClick={() => { navigator.clipboard.writeText(code); push("ok", "Copied"); }}>Copy</Button>}>
      <pre className="overflow-x-auto whitespace-pre-wrap break-all rounded-[8px] bg-sunken p-3 font-mono text-[11.5px]">{code}</pre>
    </Card>
  );
}

function FormBuilder({ s, setS, customFields }: { s: any; setS: (p: any) => void; customFields: any[] }) {
  const ind = useIndustry();
  const fields: any[] = s.fields;
  const setField = (i: number, p: any) => setS({ fields: fields.map((f, j) => (j === i ? { ...f, ...p } : f)) });
  const move = (i: number, dir: number) => { const a = [...fields]; const [x] = a.splice(i, 1); a.splice(i + dir, 0, x); setS({ fields: a }); };
  return (
    <div className="grid gap-4 lg:grid-cols-[1fr_380px]">
      <div className="space-y-4">
        <Card title="Form">
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Title"><Input value={s.title} onChange={(e) => setS({ title: e.target.value })} /></Field>
            <Field label={`${ind.projectLabel} (for routing & deals)`}><Input value={s.project ?? ""} onChange={(e) => setS({ project: e.target.value })} /></Field>
            <Field label="Description" className="sm:col-span-2"><Textarea className="min-h-[50px]" value={s.description ?? ""} onChange={(e) => setS({ description: e.target.value })} /></Field>
            <Field label="Submit button"><Input value={s.submitLabel} onChange={(e) => setS({ submitLabel: e.target.value })} /></Field>
            <Field label="Success message"><Input value={s.successMessage} onChange={(e) => setS({ successMessage: e.target.value })} /></Field>
          </div>
          <div className="mt-3"><Toggle checked={s.createDeal !== false} onChange={(v) => setS({ createDeal: v })} label="Create a deal in the default pipeline" /></div>
        </Card>
        <Card title="Fields" actions={<Button size="sm" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setS({ fields: [...fields, { key: `field_${fields.length + 1}`, label: "New field", type: "text" }] })}>Add field</Button>}>
          <div className="space-y-2">
            {fields.map((f, i) => (
              <div key={i} className="grid grid-cols-12 items-end gap-2 rounded-[9px] bg-sunken p-2">
                <Field label="Label" className="col-span-12 sm:col-span-3"><Input value={f.label} onChange={(e) => setField(i, { label: e.target.value })} /></Field>
                <Field label="Key" className="col-span-6 sm:col-span-2"><Input value={f.key} onChange={(e) => setField(i, { key: e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, "_") })} /></Field>
                <Field label="Type" className="col-span-6 sm:col-span-2"><Select value={f.type} onChange={(e) => setField(i, { type: e.target.value })}>{FIELD_TYPES.map((t) => <option key={t}>{t}</option>)}</Select></Field>
                <Field label="Maps to" className="col-span-8 sm:col-span-3"><Select value={f.mapTo ?? ""} onChange={(e) => setField(i, { mapTo: e.target.value || undefined })}>{MAP_TARGETS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}{customFields.map((c) => <option key={c.key} value={`custom.${c.key}`}>Custom: {c.label}</option>)}</Select></Field>
                <div className="col-span-4 flex items-center justify-end gap-1 pb-1 sm:col-span-2">
                  <Checkbox checked={!!f.required} onChange={(v) => setField(i, { required: v })} label="Req." />
                  <button aria-label="Up" disabled={i === 0} onClick={() => move(i, -1)} className="text-ink-3 disabled:opacity-30"><ArrowUp className="h-3.5 w-3.5" /></button>
                  <button aria-label="Down" disabled={i === fields.length - 1} onClick={() => move(i, 1)} className="text-ink-3 disabled:opacity-30"><ArrowDown className="h-3.5 w-3.5" /></button>
                  <button aria-label="Remove" onClick={() => setS({ fields: fields.filter((_, j) => j !== i) })} className="text-ink-3 hover:text-bad"><Trash2 className="h-3.5 w-3.5" /></button>
                </div>
                {f.type === "select" && <Field label="Options (comma separated)" className="col-span-12"><Input value={(f.options ?? []).join(", ")} onChange={(e) => setField(i, { options: e.target.value.split(",").map((x) => x.trim()).filter(Boolean) })} /></Field>}
              </div>
            ))}
          </div>
          <p className="mt-2 text-[11.5px] text-ink-3">UTM parameters, fbclid, gclid, landing URL and the visitor ID are captured automatically as hidden fields.</p>
        </Card>
        <Card title="Consent checkboxes" actions={<Button size="sm" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setS({ consent: [...(s.consent ?? []), { channel: "email", label: "Email me updates" }] })}>Add</Button>}>
          {(s.consent ?? []).map((c: any, i: number) => (
            <div key={i} className="mb-2 flex gap-2"><Select className="w-[140px]" value={c.channel} onChange={(e) => setS({ consent: s.consent.map((x: any, j: number) => (j === i ? { ...x, channel: e.target.value } : x)) })}><option value="whatsapp">WhatsApp</option><option value="sms">SMS</option><option value="email">Email</option></Select><Input className="flex-1" value={c.label} onChange={(e) => setS({ consent: s.consent.map((x: any, j: number) => (j === i ? { ...x, label: e.target.value } : x)) })} /><button aria-label="Remove" onClick={() => setS({ consent: s.consent.filter((_: any, j: number) => j !== i) })} className="text-ink-3 hover:text-bad"><Trash2 className="h-4 w-4" /></button></div>
          ))}
        </Card>
      </div>
      <Card title="Preview" className="h-fit lg:sticky lg:top-4">
        <div className="space-y-3">
          <div><h3 className="text-[18px] font-bold">{s.title}</h3>{s.description && <p className="text-[12.5px] text-ink-3">{s.description}</p>}</div>
          {fields.filter((f) => f.type !== "hidden").map((f, i) => (
            <Field key={i} label={<>{f.label}{f.required && <span className="text-brand"> *</span>}</>}>
              {f.type === "select" ? <Select><option>Choose…</option>{(f.options ?? []).map((o: string) => <option key={o}>{o}</option>)}</Select> : f.type === "textarea" ? <Textarea /> : f.type === "checkbox" ? <Checkbox checked={false} onChange={() => {}} label={f.label} /> : <Input type={f.type === "phone" ? "tel" : f.type} placeholder={f.type === "phone" ? "01XXXXXXXXX" : ""} />}
            </Field>
          ))}
          {(s.consent ?? []).map((c: any, i: number) => <Checkbox key={i} checked={false} onChange={() => {}} label={<span className="text-[12px]">{c.label}</span>} />)}
          <Button variant="primary" size="lg" className="w-full">{s.submitLabel}</Button>
        </div>
      </Card>
    </div>
  );
}

function BlockProps({ b, onChange }: { b: any; onChange: (p: any) => void }) {
  const p = b.props;
  const set = (k: string, v: any) => onChange({ ...p, [k]: v });
  const items = (k: string, keys: string[]) => (
    <div className="space-y-1.5">{(p[k] ?? []).map((it: any, i: number) => (
      <div key={i} className="flex gap-1.5">{keys.map((kk) => <Input key={kk} placeholder={kk} value={it[kk] ?? ""} onChange={(e) => set(k, p[k].map((x: any, j: number) => (j === i ? { ...x, [kk]: e.target.value } : x)))} />)}<button aria-label="Remove" onClick={() => set(k, p[k].filter((_: any, j: number) => j !== i))} className="text-ink-3 hover:text-bad"><Trash2 className="h-3.5 w-3.5" /></button></div>
    ))}<Button size="sm" variant="ghost" icon={<Plus className="h-3 w-3" />} onClick={() => set(k, [...(p[k] ?? []), Object.fromEntries(keys.map((x) => [x, ""]))])}>Add</Button></div>
  );
  switch (b.type) {
    case "hero": return <div className="grid gap-2 sm:grid-cols-2"><Input placeholder="Eyebrow" value={p.eyebrow ?? ""} onChange={(e) => set("eyebrow", e.target.value)} /><Input placeholder="CTA label" value={p.cta ?? ""} onChange={(e) => set("cta", e.target.value)} /><Input className="sm:col-span-2" placeholder="Headline" value={p.title ?? ""} onChange={(e) => set("title", e.target.value)} /><Textarea className="min-h-[50px] sm:col-span-2" placeholder="Subtitle" value={p.subtitle ?? ""} onChange={(e) => set("subtitle", e.target.value)} /><Input className="sm:col-span-2" placeholder="Background image URL" value={p.image ?? ""} onChange={(e) => set("image", e.target.value)} /></div>;
    case "features": return <div className="space-y-2"><Input placeholder="Section title" value={p.title ?? ""} onChange={(e) => set("title", e.target.value)} />{items("items", ["title", "text"])}</div>;
    case "faq": return <div className="space-y-2"><Input placeholder="Section title" value={p.title ?? ""} onChange={(e) => set("title", e.target.value)} />{items("items", ["q", "a"])}</div>;
    case "gallery": return items("images", ["url"]);
    case "testimonial": return <div className="space-y-2"><Textarea placeholder="Quote" value={p.quote ?? ""} onChange={(e) => set("quote", e.target.value)} /><Input placeholder="Name, role" value={p.author ?? ""} onChange={(e) => set("author", e.target.value)} /></div>;
    case "image": return <div className="space-y-2"><Input placeholder="Image URL" value={p.url ?? ""} onChange={(e) => set("url", e.target.value)} /><Input placeholder="Caption" value={p.caption ?? ""} onChange={(e) => set("caption", e.target.value)} /></div>;
    case "cta": return <div className="grid gap-2 sm:grid-cols-2"><Input placeholder="Headline" value={p.title ?? ""} onChange={(e) => set("title", e.target.value)} /><Input placeholder="Button label" value={p.label ?? ""} onChange={(e) => set("label", e.target.value)} /><Input className="sm:col-span-2" placeholder="Button link (#form, tel:, https://wa.me/…)" value={p.href ?? ""} onChange={(e) => set("href", e.target.value)} /></div>;
    case "form": return <Input placeholder="Form heading" value={p.title ?? ""} onChange={(e) => set("title", e.target.value)} />;
    default: return <Textarea placeholder="Text (supports line breaks)" value={p.text ?? ""} onChange={(e) => set("text", e.target.value)} />;
  }
}

function BlocksEditor({ blocks, onChange }: { blocks: any[]; onChange: (b: any[]) => void }) {
  const [add, setAdd] = useState("features");
  const move = (i: number, dir: number) => { const a = [...blocks]; const [x] = a.splice(i, 1); a.splice(i + dir, 0, x); onChange(a); };
  return (
    <div className="space-y-3">
      {blocks.map((b, i) => (
        <div key={b.id} className="rounded-[10px] border border-line p-3">
          <div className="mb-2 flex items-center gap-2"><Badge tone="violet">{b.type}</Badge><span className="ml-auto flex gap-1">
            <button aria-label="Up" disabled={i === 0} onClick={() => move(i, -1)} className="text-ink-3 disabled:opacity-30"><ArrowUp className="h-3.5 w-3.5" /></button>
            <button aria-label="Down" disabled={i === blocks.length - 1} onClick={() => move(i, 1)} className="text-ink-3 disabled:opacity-30"><ArrowDown className="h-3.5 w-3.5" /></button>
            <button aria-label="Remove" onClick={() => onChange(blocks.filter((_, j) => j !== i))} className="text-ink-3 hover:text-bad"><Trash2 className="h-3.5 w-3.5" /></button></span></div>
          <BlockProps b={b} onChange={(props) => onChange(blocks.map((x, j) => (j === i ? { ...x, props } : x)))} />
        </div>
      ))}
      <div className="flex gap-2"><Select className="w-[180px]" value={add} onChange={(e) => setAdd(e.target.value)}>{BLOCK_TYPES.map((t) => <option key={t}>{t}</option>)}</Select><Button icon={<Plus className="h-3.5 w-3.5" />} onClick={() => onChange([...blocks, { id: `b${Date.now().toString(36)}`, type: add, props: add === "features" || add === "faq" ? { items: [] } : {} }])}>Add block</Button></div>
    </div>
  );
}

function PageBuilder({ s, setS, forms }: { s: any; setS: (p: any) => void; forms: any[] }) {
  return (
    <div className="grid gap-4 lg:grid-cols-[1fr_320px]">
      <Card title="Blocks" subtitle="Build the page without code — templates, sections and a lead form"><BlocksEditor blocks={s.blocks} onChange={(blocks) => setS({ blocks })} /></Card>
      <Card title="Page" className="h-fit">
        <div className="space-y-3">
          <Field label="Page title"><Input value={s.title} onChange={(e) => setS({ title: e.target.value })} /></Field>
          <Field label="Lead form used by form blocks"><Select value={s.formId ?? ""} onChange={(e) => setS({ formId: e.target.value || undefined })}><option value="">Choose a form…</option>{forms.map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}</Select></Field>
          <Field label="Accent colour"><div className="flex gap-2"><input type="color" className="h-8 w-10 rounded" value={s.theme?.accent ?? "#2563EB"} onChange={(e) => setS({ theme: { ...s.theme, accent: e.target.value } })} /><Input value={s.theme?.accent ?? "#2563EB"} onChange={(e) => setS({ theme: { ...s.theme, accent: e.target.value } })} /></div></Field>
          <Toggle checked={!!s.theme?.dark} onChange={(v) => setS({ theme: { ...s.theme, dark: v } })} label="Dark theme" />
        </div>
      </Card>
    </div>
  );
}

function ABEditor({ d, set }: { d: any; set: (p: any) => void }) {
  const variants: any[] = d.variants ?? [];
  const enabled = variants.length >= 2;
  const [active, setActive] = useState(variants[1]?.key ?? "B");
  const v = variants.find((x) => x.key === active);
  return (
    <div className="space-y-4">
      <Card title="A/B test" subtitle="Split traffic between versions of the page; variant A is the page as built. Visitors stick to their variant.">
        {!enabled ? <Button variant="primary" onClick={() => set({ variants: [{ key: "A", weight: 50, blocks: [] }, { key: "B", weight: 50, blocks: structuredClone(d.schema.blocks) }] })}>Start an A/B test</Button> : (
          <div className="space-y-3">
            {variants.map((x, i) => (
              <div key={x.key} className="flex items-center gap-3"><b className="w-20">Variant {x.key}</b><input type="range" min="0" max="100" step="5" className="flex-1 accent-[rgb(var(--brand))]" value={x.weight} onChange={(e) => set({ variants: variants.map((y, j) => (j === i ? { ...y, weight: Number(e.target.value) } : y)) })} /><span className="w-12 text-right text-[12.5px]">{x.weight}%</span>{x.key !== "A" && <button aria-label="Remove" onClick={() => set({ variants: variants.filter((_, j) => j !== i) })} className="text-ink-3 hover:text-bad"><Trash2 className="h-4 w-4" /></button>}</div>
            ))}
            <div className="flex gap-2">
              <Button size="sm" onClick={() => { const k = String.fromCharCode(65 + variants.length); set({ variants: [...variants, { key: k, weight: 0, blocks: structuredClone(d.schema.blocks) }] }); setActive(k); }}>Add variant</Button>
              <Button size="sm" variant="ghost" onClick={() => set({ variants: [] })}>Stop test</Button>
            </div>
          </div>
        )}
      </Card>
      {enabled && (
        <Card title={<span className="flex items-center gap-2">Edit variant {variants.filter((x) => x.key !== "A").map((x) => <button key={x.key} onClick={() => setActive(x.key)} className={cx("rounded-full px-2 py-0.5 text-[12px]", active === x.key ? "bg-brand text-white" : "bg-ink/[.06]")}>{x.key}</button>)}</span>} subtitle="Blocks for this variant replace the page’s blocks">
          {v && <BlocksEditor blocks={v.blocks.length ? v.blocks : structuredClone(d.schema.blocks)} onChange={(blocks) => set({ variants: variants.map((y) => (y.key === active ? { ...y, blocks } : y)) })} />}
        </Card>
      )}
    </div>
  );
}

