/* ============================================================================
   FOUNDRY CONTROL — PROJECTS + INSPECT
   Adds the first-class "what am I controlling?" layer to Foundry Control:
     · Project selector / switcher (sites & apps under Divonci World Foundry)
     · Inspect Project — a DevTools-style element picker over a controlled
       preview (desktop) and a screenshot-annotation flow (mobile)
     · Both produce a structured change-request draft scoped to the project.
   Safety: the inspect tool can ONLY create / update a change request. No
   production mutation happens here — production still requires approval.
   Shares atoms (Icon, Led, Panel, PHead) with the rest of the OS.
   ========================================================================== */
const { useState: useStateP, useRef: useRefP } = React;

/* ---- the sites & apps under Foundry control --------------------------- */
const FOUNDRY_PROJECTS = [
  { id: "divonci", name: "divonci.world", domain: "divonci.world", ac: "#A855F7",
    repo: "diovinci/divonci-world", pages: "divonci-world", worker: "dw-api.divonci.workers.dev",
    supabase: "dw-prod", prod: "clear", prodVer: "v0.1.7", preview: { url: "cr2041.foundry.pages.dev", t: "09:16" }, risk: "med" },
  { id: "council", name: "Cloud Council Presidency", domain: "council.divonci.world", ac: "#D4B062",
    repo: "diovinci/cloud-council", pages: "cloud-council", worker: "council-api.divonci.workers.dev",
    supabase: "council-prod", prod: "caution", prodVer: "v0.4.2", preview: { url: "ccp-staging.pages.dev", t: "Jun 12" }, risk: "high" },
  { id: "viiera", name: "Viiera", domain: "viiera.app", ac: "#D946EF",
    repo: "diovinci/viiera-studio", pages: "viiera-studio", worker: "viiera-api.divonci.workers.dev",
    supabase: "viiera-prod", prod: "clear", prodVer: "v2.0.0", preview: { url: "viiera-next.pages.dev", t: "08:40" }, risk: "low" },
  { id: "lasso", name: "Lasso", domain: "lasso.dev", ac: "#4D9FFF",
    repo: "diovinci/lasso", pages: "lasso-web", worker: "lasso-api.divonci.workers.dev",
    supabase: "lasso-prod", prod: "standby", prodVer: "—", preview: null, risk: "low" },
  { id: "plugg", name: "Plugg Life", domain: "plugg.life", ac: "#2FE0A1",
    repo: "diovinci/plugg-life", pages: "plugg-life", worker: "plugg-api.divonci.workers.dev",
    supabase: "plugg-prod", prod: "crisis", prodVer: "v1.3.1", preview: { url: "plugg-fix.pages.dev", t: "07:55" }, risk: "high" },
];
const fproj = (id) => FOUNDRY_PROJECTS.find(p => p.id === id) || FOUNDRY_PROJECTS[0];

/* extra change requests so switching projects shows scoped data ---------- */
const EXTRA_SEED = [
  { id: "CR-3110", title: "Council seat ratification banner", project: "council", target: "Cloud Council Presidency",
    area: "Presidency · home hero", type: "Copy", priority: "High", env: "production", status: "Awaiting Approval",
    step: 3, channel: "web", cmd: null, author: "Viiera", created: "08:48", agent: "Claws",
    desc: "Swap the hero headline to the ratified sixth-seat language.", accept: "Headline matches approved doctrine · no layout shift.",
    diff: { files: 1, add: 4, del: 4 }, files: ["src/Home.jsx"], preview: "ccp-staging.pages.dev",
    logs: [["ok", "build", "green"], ["ok", "verify", "passed"]] },
  { id: "CR-3220", title: "Studio export preset crash", project: "viiera", target: "Viiera",
    area: "Studio · export panel", type: "Bug fix", priority: "Urgent", env: "preview", status: "Validating",
    step: 2, channel: "telegram", cmd: "/cr 3220", author: "Diego", created: "08:31", agent: "VV",
    desc: "Export preset dropdown throws when no take is selected.", accept: "No crash · empty state shown.",
    diff: { files: 1, add: 11, del: 3 }, files: ["src/ExportPanel.jsx"], preview: null,
    logs: [["ok", "build", "green"], ["run", "verify", "reproducing…"]] },
  { id: "CR-3401", title: "Plugg checkout webhook origin", project: "plugg", target: "Plugg Life",
    area: "Checkout · webhook", type: "Backend", priority: "Urgent", env: "preview", status: "Validation Failed",
    step: 2, channel: "discord", cmd: "/cr 3401", author: "BroDex", created: "07:58", agent: "BroDex",
    desc: "Verify Stripe webhook signature before mutating orders.", accept: "Invalid signatures rejected · orders untouched.",
    diff: { files: 1, add: 14, del: 2 }, files: ["functions/webhook.ts"], preview: null,
    logs: [["ok", "build", "green"], ["err", "verify", "signature check missing on 1 path"]] },
  { id: "CR-3402", title: "Plugg storefront skeleton", project: "plugg", target: "Plugg Life",
    area: "Storefront · grid", type: "UI", priority: "Med", env: "preview", status: "Patch Ready",
    step: 1, channel: "web", cmd: null, author: "Nova", created: "07:40", agent: "VV",
    desc: "Add loading skeletons to the product grid.", accept: "Skeletons show while fetching · no CLS.",
    diff: { files: 2, add: 33, del: 1 }, files: ["src/Grid.jsx", "src/skeleton.css"], preview: null, logs: [["ok", "patch", "branch created"]] },
];

/* count open (non-terminal) CRs for a project --------------------------- */
function projOpenCRs(reqs, pid) {
  return reqs.filter(r => r.project === pid && !["Published", "Rejected", "Rolled Back"].includes(r.status)).length;
}
function projAwaiting(reqs, pid) {
  return reqs.filter(r => r.project === pid && ["Awaiting Approval", "Preview Live", "Patch Ready"].includes(r.status)).length;
}

/* =================================================== PROJECT SELECTOR ==== */
function ProjectSelector({ reqs, onPick }) {
  const [q, setQ] = useStateP("");
  const list = FOUNDRY_PROJECTS.filter(p => !q || (p.name + p.domain).toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="fp-selector">
      <div className="fp-sel-head">
        <div>
          <div className="fp-sel-eyebrow">Foundry Control</div>
          <div className="fp-sel-title">Choose what you're controlling</div>
          <div className="fp-sel-sub">Every request, deploy and inspect action is scoped to one project. Pick a site or app to open its control room.</div>
        </div>
        <div className="cmd fp-sel-search">
          <Icon name="search" style={{ width: 14, height: 14 }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Filter projects…" />
        </div>
      </div>
      <div className="fp-grid">
        {list.map(p => {
          const open = projOpenCRs(reqs, p.id), awaiting = projAwaiting(reqs, p.id);
          const rc = { low: "clear", med: "caution", high: "crisis" }[p.risk];
          return (
            <button key={p.id} className="fp-card focusable" style={{ "--ac": p.ac }} onClick={() => onPick(p.id)}>
              <div className="fp-card-top">
                <span className="fp-card-glyph"><Icon name="globe" className="glyph" style={{ width: 16, height: 16 }} /></span>
                <div className="fp-card-id"><b>{p.name}</b><span>{p.domain}</span></div>
                <span className="fp-prod" style={{ color: DW.STATE_META[p.prod].c }}><Led state={p.prod} size={7} />{p.prodVer}</span>
              </div>
              <div className="fp-int">
                {[["branch", p.repo], ["rocket", "pages · " + p.pages], ["bolt", p.worker], ["nexus", "supabase · " + p.supabase]].map(([ic, v]) => (
                  <div key={v} className="fp-int-row"><Icon name={ic} className="glyph" style={{ width: 12, height: 12 }} /><span>{v}</span></div>
                ))}
              </div>
              <div className="fp-card-foot">
                <span className="fp-stat"><b style={{ color: open ? "var(--state-active)" : "var(--ink-3)" }}>{open}</b> open</span>
                <span className="fp-stat"><b style={{ color: awaiting ? "var(--gold-bright)" : "var(--ink-3)" }}>{awaiting}</b> to review</span>
                <span className="fp-risk" style={{ color: DW.STATE_META[rc].c, borderColor: "color-mix(in srgb," + DW.STATE_META[rc].c + " 38%,transparent)" }}>{p.risk} risk</span>
                <span className="fp-open">Open <Icon name="chevron" className="glyph" style={{ width: 13, height: 13 }} /></span>
              </div>
              {p.preview && <div className="fp-prev"><Icon name="globe" className="glyph" style={{ width: 11, height: 11 }} />latest preview · {p.preview.url} · {p.preview.t}</div>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ============================================== PROJECT SWITCHER (bar) === */
function ProjectSwitcher({ project, reqs, onPick, onAll }) {
  const [open, setOpen] = useStateP(false);
  const p = project;
  return (
    <div className="fp-switch">
      <button className="fp-switch-btn focusable" style={{ "--ac": p.ac }} onClick={() => setOpen(o => !o)}>
        <span className="fp-switch-glyph"><Icon name="globe" className="glyph" style={{ width: 13, height: 13 }} /></span>
        <span className="fp-switch-name"><b>{p.name}</b><em>{p.domain}</em></span>
        <span className="fp-prod sm" style={{ color: DW.STATE_META[p.prod].c }}><Led state={p.prod} size={6} /></span>
        <Icon name="chevron" className="glyph" style={{ width: 13, height: 13, transform: open ? "rotate(270deg)" : "rotate(90deg)", transition: "transform .15s" }} />
      </button>
      {open && (
        <>
          <div className="fp-switch-bd" onClick={() => setOpen(false)} />
          <div className="fp-switch-menu">
            <div className="fp-switch-menulabel">Switch project</div>
            {FOUNDRY_PROJECTS.map(x => (
              <button key={x.id} className={"fp-switch-item" + (x.id === p.id ? " on" : "")} style={{ "--ac": x.ac }} onClick={() => { onPick(x.id); setOpen(false); }}>
                <span className="fp-switch-glyph"><Icon name="globe" className="glyph" style={{ width: 12, height: 12 }} /></span>
                <span className="fp-switch-name"><b>{x.name}</b><em>{x.domain}</em></span>
                <span className="fp-switch-count">{projOpenCRs(reqs, x.id)}</span>
                <Led state={x.prod} size={6} />
              </button>
            ))}
            <button className="fp-switch-all" onClick={() => { onAll(); setOpen(false); }}><Icon name="ops" className="glyph" style={{ width: 12, height: 12 }} /> All projects</button>
          </div>
        </>
      )}
    </div>
  );
}

/* =============================== CONTROLLED PREVIEW (the inspected page) == */
/* A representative rendered surface for the project. Each element carries the
   metadata the picker captures: selector, element type, file hint. */
function SitePreview({ project, inspect, onHover, onPick }) {
  const p = project;
  function meta(el) {
    if (!el) return null;
    const r = el.getBoundingClientRect();
    const wrap = el.closest(".fp-site");
    const wr = wrap.getBoundingClientRect();
    const parent = el.parentElement.closest("[data-sel]");
    return {
      sel: el.getAttribute("data-sel"), type: el.getAttribute("data-type") || el.tagName.toLowerCase(),
      name: el.getAttribute("data-name") || (el.textContent || "").trim().slice(0, 48),
      text: (el.textContent || "").trim().slice(0, 120), file: el.getAttribute("data-file"),
      context: parent ? parent.getAttribute("data-sel") : "document",
      box: { x: Math.round(r.left - wr.left), y: Math.round(r.top - wr.top), w: Math.round(r.width), h: Math.round(r.height) },
      rect: { left: r.left - wr.left, top: r.top - wr.top, width: r.width, height: r.height },
    };
  }
  const onMove = (e) => { if (!inspect) return; const el = e.target.closest("[data-sel]"); onHover(el ? meta(el) : null); };
  const onClick = (e) => { if (!inspect) return; e.preventDefault(); e.stopPropagation(); const el = e.target.closest("[data-sel]"); if (el) onPick(meta(el)); };
  return (
    <div className={"fp-site" + (inspect ? " inspecting" : "")} onMouseMove={onMove} onMouseLeave={() => inspect && onHover(null)} onClick={onClick}>
      <header data-sel="header.site-nav" data-type="nav" data-file="src/components/Nav.jsx" data-name="Primary navigation" className="fps-nav">
        <span data-sel=".brand" data-type="logo" data-file="src/components/Nav.jsx" data-name="Brand logo" className="fps-brand">{p.name}</span>
        <span className="fps-navlinks">
          <a data-sel="nav a.link-product" data-type="link" data-file="src/components/Nav.jsx" data-name="Product link">Product</a>
          <a data-sel="nav a.link-pricing" data-type="link" data-file="src/components/Nav.jsx" data-name="Pricing link">Pricing</a>
          <a data-sel="nav a.link-docs" data-type="link" data-file="src/components/Nav.jsx" data-name="Docs link">Docs</a>
        </span>
        <button data-sel="nav button.cta" data-type="button" data-file="src/components/Nav.jsx" data-name="Get started button" className="fps-navcta">Get started</button>
      </header>
      <section data-sel="section.hero" data-type="section" data-file="src/sections/Hero.jsx" data-name="Hero section" className="fps-hero">
        <h1 data-sel=".hero h1" data-type="heading" data-file="src/sections/Hero.jsx" data-name="Hero headline" className="fps-h1">Control every change to {p.domain}</h1>
        <p data-sel=".hero p.sub" data-type="text" data-file="src/sections/Hero.jsx" data-name="Hero subcopy" className="fps-sub">Request, validate and publish safely — nothing reaches production without approval.</p>
        <div className="fps-herocta">
          <button data-sel=".hero button.primary" data-type="button" data-file="src/sections/Hero.jsx" data-name="Primary CTA" className="fps-btn primary">Open console</button>
          <button data-sel=".hero button.ghost" data-type="button" data-file="src/sections/Hero.jsx" data-name="Secondary CTA" className="fps-btn">Watch demo</button>
        </div>
      </section>
      <section data-sel="section.features" data-type="section" data-file="src/sections/Features.jsx" data-name="Features grid" className="fps-feat">
        {[["Requests", "branch"], ["Validation", "ops"], ["Deploys", "rocket"]].map(([t, ic], i) => (
          <div key={t} data-sel={".features .card-" + (i + 1)} data-type="card" data-file="src/sections/Features.jsx" data-name={t + " feature card"} className="fps-card">
            <span className="fps-card-ic"><Icon name={ic} className="glyph" style={{ width: 15, height: 15 }} /></span>
            <b data-sel={".card-" + (i + 1) + " .title"} data-type="heading" data-file="src/sections/Features.jsx" data-name={t + " title"}>{t}</b>
            <span data-sel={".card-" + (i + 1) + " .desc"} data-type="text" data-file="src/sections/Features.jsx" data-name={t + " description"}>Operational control over {t.toLowerCase()} with a full audit trail.</span>
          </div>
        ))}
      </section>
      <footer data-sel="footer.site" data-type="footer" data-file="src/components/Footer.jsx" data-name="Site footer" className="fps-foot">© {p.name} · {p.domain}</footer>
    </div>
  );
}

/* ============================================ INSPECT PROJECT (desktop) == */
function InspectProject({ project, onCreateCR }) {
  const [inspect, setInspect] = useStateP(true);
  const [hover, setHover] = useStateP(null);
  const [picked, setPicked] = useStateP(null);
  const p = project;
  const url = "https://" + (p.preview ? p.preview.url : p.domain);
  const overlay = inspect ? (picked || hover) : null;
  return (
    <div className="fp-inspect">
      <div className="fp-browser">
        <div className="fp-bchrome">
          <span className="fp-dots"><i /><i /><i /></span>
          <div className="fp-urlbar"><Icon name="lock" className="glyph" style={{ width: 11, height: 11 }} />{url}</div>
          <button className={"fp-inspect-toggle focusable" + (inspect ? " on" : "")} onClick={() => { setInspect(v => !v); setHover(null); }} title="Toggle element picker">
            <Icon name="eye" className="glyph" style={{ width: 14, height: 14 }} />Inspect
          </button>
        </div>
        <div className="fp-viewport">
          <div className="fp-stagewrap">
            <SitePreview project={p} inspect={inspect} onHover={setHover} onPick={(m) => { setPicked(m); }} />
            {overlay && (
              <div className="fp-overlay" style={{ left: overlay.rect.left, top: overlay.rect.top, width: overlay.rect.width, height: overlay.rect.height }}>
                <span className="fp-overlay-tag">{overlay.sel} <em>{overlay.box.w}×{overlay.box.h}</em></span>
              </div>
            )}
          </div>
        </div>
      </div>
      <ElementInspector picked={picked} project={p} url={url} onClear={() => setPicked(null)} onCreateCR={onCreateCR} />
    </div>
  );
}

/* ------------------------------------------- selected-element inspector -- */
function ElementInspector({ picked, project, url, onClear, onCreateCR }) {
  if (!picked) {
    return (
      <div className="panel fp-insp-panel">
        <div className="phead"><span className="eyebrow"><Icon name="eye" className="glyph" style={{ width: 13, height: 13 }} /> Element inspector</span></div>
        <div className="fp-insp-empty">
          <span className="fp-insp-ring"><Icon name="filter" className="glyph" style={{ width: 20, height: 20 }} /></span>
          <b>No element selected</b>
          <em>Turn on Inspect, then click an element in the preview to capture it as an edit target.</em>
        </div>
      </div>
    );
  }
  const rows = [
    ["Element type", picked.type], ["Selector", picked.sel], ["Accessible name", picked.name || "—"],
    ["Visible text", picked.text || "—"], ["Bounding box", `${picked.box.x}, ${picked.box.y} · ${picked.box.w}×${picked.box.h}`],
    ["Nearby context", picked.context], ["Component hint", picked.file || "—"],
  ];
  return (
    <div className="panel fp-insp-panel">
      <div className="phead"><span className="eyebrow"><Icon name="eye" className="glyph" style={{ width: 13, height: 13 }} /> Edit target captured</span>
        <button className="minilink" onClick={onClear}>clear</button></div>
      <div className="fp-insp-body comms-scroll">
        <div className="fp-shotgrab"><div className="fctl-shot-stripe" /><span className="fp-shotgrab-tag">{picked.sel}</span><span className="fp-shotgrab-cap">capture · {project.domain} · 1280×800</span></div>
        <div className="fp-meta">
          <div className="fp-meta-row"><span>URL</span><b className="mono">{url}</b></div>
          <div className="fp-meta-row"><span>Viewport</span><b className="mono">1280 × 800</b></div>
          {rows.map(([k, v]) => <div key={k} className="fp-meta-row"><span>{k}</span><b className={k === "Selector" || k === "Component hint" ? "mono" : ""}>{v}</b></div>)}
        </div>
        <div className="fp-insp-note"><Icon name="shield" className="glyph" style={{ width: 12, height: 12 }} />Inspect can only open a change request. Production stays locked behind approval.</div>
      </div>
      <div className="fp-insp-act">
        <button className="btn primary full" onClick={() => onCreateCR(picked)}><Icon name="plus" className="glyph" style={{ width: 14, height: 14 }} /> Create change request</button>
      </div>
    </div>
  );
}

/* ====================================== MOBILE — screenshot annotation ==== */
function MobileAnnotate({ project, onCreateCR }) {
  const [shot, setShot] = useStateP(false);
  const [mark, setMark] = useStateP(null);     // { x, y } in %  (tap point)
  const ref = useRefP(null);
  function tap(e) {
    if (!shot) return;
    const r = ref.current.getBoundingClientRect();
    const x = ((e.clientX - r.left) / r.width) * 100, y = ((e.clientY - r.top) / r.height) * 100;
    setMark({ x: Math.max(3, Math.min(97, x)), y: Math.max(3, Math.min(97, y)) });
  }
  return (
    <div className="fctl-pad fp-annot">
      <div className="fctl-h"><div><b>Inspect</b><span>Mark a target on a screenshot</span></div></div>
      {!shot ? (
        <button className="fp-annot-drop focusable" onClick={() => setShot(true)}>
          <Icon name="evidence" className="glyph" style={{ width: 22, height: 22 }} />
          <b>Upload or capture a screenshot</b>
          <em>Hover-inspect is hard on mobile — mark the spot instead.</em>
        </button>
      ) : (
        <>
          <div className="fp-annot-stage" ref={ref} onClick={tap}>
            <div className="fp-annot-shot"><div className="fctl-shot-stripe" /><span className="fp-shotgrab-cap">{project.domain} · tap the area to edit</span></div>
            {mark && <span className="fp-annot-pin" style={{ left: mark.x + "%", top: mark.y + "%" }}><span className="fp-annot-ring" /><span className="fp-annot-dot" /></span>}
          </div>
          <div className="fp-annot-meta">
            <div className="fp-meta-row"><span>Project</span><b>{project.name}</b></div>
            <div className="fp-meta-row"><span>Screenshot</span><b className="mono">capture-{project.id}.png</b></div>
            <div className="fp-meta-row"><span>Marker</span><b className="mono">{mark ? `${Math.round(mark.x)}%, ${Math.round(mark.y)}%` : "tap to place"}</b></div>
          </div>
          <button className="btn primary fctl-submit" disabled={!mark} onClick={() => onCreateCR({ sel: "annotation@" + Math.round(mark.x) + "," + Math.round(mark.y), type: "annotated region", name: "Marked area", text: "", box: { x: Math.round(mark.x), y: Math.round(mark.y), w: 0, h: 0 }, context: "screenshot", file: null, annotated: true })}>
            <Icon name="plus" className="glyph" style={{ width: 15, height: 15 }} /> Describe the edit
          </button>
        </>
      )}
    </div>
  );
}

/* turn a captured element into a NewRequest seed ------------------------- */
function elementToSeed(picked, project) {
  if (!picked) return null;
  return {
    target: project.name, project: project.id,
    area: picked.context && picked.context !== "document" ? picked.context + " · " + picked.sel : picked.sel,
    type: picked.annotated ? "UI" : (picked.type === "text" || picked.type === "heading" ? "Copy" : "UI"),
    element: picked,
  };
}

Object.assign(window, {
  FOUNDRY_PROJECTS, EXTRA_SEED, fproj, projOpenCRs, projAwaiting,
  ProjectSelector, ProjectSwitcher, SitePreview, InspectProject, ElementInspector, MobileAnnotate, elementToSeed,
});
