// playground.jsx — interactive hero demo (OrgLens scan & ReleaseGuard review)

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ──────────────── OrgLens demo ────────────────────────────────────────── */

const ORGLENS_CATEGORIES = [
  { key: "data",  label: "Data Model Hygiene",   score: 61, status: "warn", note: "1,284 unused fields · 22 duplicate candidates" },
  { key: "auto",  label: "Automation Health",     score: 48, status: "risk", note: "42 flows missing fault paths · 7 stack on Opportunity" },
  { key: "sec",   label: "Security & Access",     score: 72, status: "warn", note: "17 inactive users own assets · 4 broad profiles" },
  { key: "apex",  label: "Apex & Test Quality",   score: 67, status: "warn", note: "Coverage 78% · concentration risk in 2 classes" },
  { key: "rel",   label: "Release Readiness",     score: 58, status: "warn", note: "14 metadata drift items · UAT vs Prod" },
  { key: "ai",    label: "AI / Agentforce Readiness", score: 44, status: "risk", note: "36% of key fields lack descriptions" },
];

const ORGLENS_FINDINGS = [
  { priority: "P1", title: "Opportunity has 7 overlapping automations",   where: "Object: Opportunity · 3 flows + 1 trigger + 2 wf rules + 1 PB" },
  { priority: "P1", title: "14 record-triggered flows missing fault paths", where: "Across Opportunity, Case, Renewal" },
  { priority: "P2", title: "382 Account fields appear unused",             where: "0 records populated · 0 references · 0 reports" },
];

function OrgLensDemo({ autoStart }) {
  const [stage, setStage] = useStateP("idle"); // idle | scanning | done
  const [progress, setProgress] = useStateP(0);
  const [activeCat, setActiveCat] = useStateP(-1);
  const startedRef = useRefP(false);

  const runScan = () => {
    setStage("scanning");
    setProgress(0);
    setActiveCat(0);
  };

  useEffectP(() => {
    if (autoStart && !startedRef.current) {
      startedRef.current = true;
      const t = setTimeout(runScan, 600);
      return () => clearTimeout(t);
    }
  }, [autoStart]);

  useEffectP(() => {
    if (stage !== "scanning") return;
    const total = ORGLENS_CATEGORIES.length;
    let i = 0;
    const tick = () => {
      i += 1;
      setActiveCat(i);
      setProgress(Math.round((i / total) * 100));
      if (i >= total) {
        setTimeout(() => setStage("done"), 320);
      } else {
        setTimeout(tick, 420);
      }
    };
    const t = setTimeout(tick, 420);
    return () => clearTimeout(t);
  }, [stage]);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.1fr) minmax(0, 1fr)", gap: 0, minHeight: 460 }}
         className="ol-demo-grid">
      {/* LEFT: scan panel */}
      <div style={{ padding: "24px 28px", borderRight: "1px solid var(--border-subtle)" }} className="ol-demo-left">
        <div className="row between" style={{ marginBottom: 18 }}>
          <div className="row gap-8">
            <span className="dot dot-ok" />
            <span className="mono-sm" style={{ color: "var(--text-primary)" }}>acme-fed-prod.my.salesforce.com</span>
          </div>
          <span className="pill pill-dim">PRODUCTION · v62</span>
        </div>

        <div className="row between" style={{ marginBottom: 24 }}>
          <div>
            <div className="eyebrow">Scan</div>
            <div className="h3" style={{ marginTop: 4 }}>Deep org analysis</div>
          </div>
          {stage === "done" ? (
            <button className="btn btn-secondary btn-sm" onClick={runScan}>
              <IconRefresh /> Rescan
            </button>
          ) : stage === "idle" ? (
            <button className="btn btn-primary btn-sm" onClick={runScan}>
              <IconScan /> Start scan
            </button>
          ) : (
            <span className="mono-sm" style={{ color: "var(--accent)" }}>
              <span className="spin" style={{ display: "inline-block", marginRight: 8, transformOrigin: "center" }}>◐</span>
              SCANNING · {progress}%
            </span>
          )}
        </div>

        <div className="bar" style={{ marginBottom: 24 }}>
          <div style={{ width: `${progress}%` }} />
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
          {ORGLENS_CATEGORIES.map((c, i) => {
            const state = stage === "idle" ? "pending"
                        : stage === "done" ? "done"
                        : i < activeCat ? "done"
                        : i === activeCat ? "active" : "pending";
            return <ScanRow key={c.key} cat={c} state={state} reveal={stage === "done"} />;
          })}
        </div>
      </div>

      {/* RIGHT: result panel */}
      <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column" }} className="ol-demo-right">
        <div className="eyebrow eyebrow-accent" style={{ marginBottom: 16 }}>// OrgScore</div>

        {stage !== "done" ? (
          <div style={{
            flex: 1, display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center", textAlign: "center",
            color: "var(--text-muted)",
            border: "1px dashed var(--border)",
            borderRadius: "var(--r-2)",
            padding: 32,
          }}>
            <Mark size={28} color="var(--text-dim)" />
            <div className="mono-sm" style={{ marginTop: 16, color: "var(--text-secondary)" }}>
              {stage === "idle" ? "Awaiting scan" : "Computing score…"}
            </div>
            <div className="body-sm" style={{ marginTop: 8, maxWidth: 28 + "ch" }}>
              Connects via OAuth · pulls metadata, usage, and audit signals.
            </div>
          </div>
        ) : (
          <>
            <div className="row" style={{ gap: 24, marginBottom: 20 }}>
              <ScoreRing value={57} size={120} stroke={6} label="OrgScore" animated />
              <div style={{ flex: 1 }}>
                <span className="pill pill-warn">AT RISK · 57/100</span>
                <p className="body-sm" style={{ margin: "12px 0 0", color: "var(--text-secondary)" }}>
                  Your org is in the bottom-risk band for automation complexity and AI readiness.
                  Fixing <span style={{ color: "var(--text-primary)" }}>9 P1 items</span> would reduce operational risk by ~31%.
                </p>
              </div>
            </div>

            <div style={{
              borderTop: "1px solid var(--border-subtle)",
              paddingTop: 16, marginTop: 4,
            }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>// Top findings</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {ORGLENS_FINDINGS.map((f, i) => (
                  <div key={i} style={{
                    display: "grid",
                    gridTemplateColumns: "auto 1fr",
                    gap: 14, alignItems: "start",
                    padding: "10px 0",
                    borderBottom: i < ORGLENS_FINDINGS.length - 1 ? "1px solid var(--border-subtle)" : "none",
                    animation: `fadeUp 360ms ${i * 80}ms both cubic-bezier(0.2, 0.6, 0.2, 1)`,
                  }}>
                    <RiskPill level={f.priority} />
                    <div>
                      <div style={{ fontSize: 13.5, color: "var(--text-primary)", marginBottom: 2 }}>{f.title}</div>
                      <div className="mono-sm muted">{f.where}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="row between" style={{ marginTop: "auto", paddingTop: 20 }}>
              <span className="mono-sm muted">3 of 173 shown · Deep scan complete</span>
              <button className="btn btn-ghost btn-sm">View fix backlog <IconArrow /></button>
            </div>
          </>
        )}
      </div>

      <style>{`
        @media (max-width: 760px) {
          .ol-demo-grid { grid-template-columns: 1fr !important; }
          .ol-demo-left { border-right: 0 !important; border-bottom: 1px solid var(--border-subtle); }
        }
      `}</style>
    </div>
  );
}

function ScanRow({ cat, state, reveal }) {
  const icon = state === "done"   ? <span style={{ color: "var(--ok)" }}><IconCheck /></span>
            : state === "active" ? <span className="spin" style={{ color: "var(--accent)", display: "inline-block", lineHeight: 1 }}>◐</span>
            : <span style={{ width: 16, height: 16, borderRadius: "50%", border: "1px solid var(--border)", display: "inline-block" }} />;

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "20px 1fr auto",
      gap: 12,
      alignItems: "center",
      padding: "11px 0",
      borderBottom: "1px solid var(--border-subtle)",
      opacity: state === "pending" ? 0.45 : 1,
      transition: "opacity 200ms",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{icon}</div>
      <div>
        <div style={{ fontSize: 13.5, color: "var(--text-primary)" }}>{cat.label}</div>
        {reveal && <div className="mono-sm muted" style={{ marginTop: 2 }}>{cat.note}</div>}
      </div>
      {reveal ? (
        <div className="row gap-8" style={{ minWidth: 110, justifyContent: "flex-end" }}>
          <div className={`bar bar-${cat.status}`} style={{ width: 70 }}>
            <div style={{ width: `${cat.score}%` }} />
          </div>
          <span className="mono" style={{ minWidth: 24, textAlign: "right", color: "var(--text-primary)" }}>{cat.score}</span>
        </div>
      ) : (
        <span className="mono-sm muted">
          {state === "active" ? "checking" : state === "done" ? "done" : "queued"}
        </span>
      )}
    </div>
  );
}


/* ──────────────── ReleaseGuard demo ───────────────────────────────────── */

const RG_CHECKS = [
  { key: "story",  label: "User story & acceptance criteria",     status: "ok",   detail: "JIRA-4271 · 6 ACs · all linked" },
  { key: "test",   label: "Test evidence & coverage delta",       status: "warn", detail: "Apex coverage 81% · evidence missing for 2 of 4 negative paths" },
  { key: "sec",    label: "Security / permission impact review",  status: "ok",   detail: "No new system perms · 1 reviewed FLS change" },
  { key: "naming", label: "Naming convention & description policy", status: "ok",  detail: "All metadata named per CoE-A-103" },
  { key: "depend", label: "Dependency & rollback plan",            status: "risk", detail: "Rollback script absent · references AccountTrigger (deprecated)" },
  { key: "blackout", label: "Blackout window check",                status: "ok",   detail: "Window 2026-05-15 21:00 UTC · within approved" },
  { key: "audit",  label: "Audit trail completeness",              status: "ok",   detail: "Approver chain · CAB notes · waiver log present" },
  { key: "ai",     label: "AI-authored change disclosure",          status: "warn", detail: "3 of 12 components flagged AI-assisted · 1 lacks human review tag" },
];

function ReleaseGuardDemo({ autoStart }) {
  const [stage, setStage] = useStateP("idle");
  const [activeIdx, setActiveIdx] = useStateP(-1);
  const startedRef = useRefP(false);

  const run = () => {
    setStage("reviewing");
    setActiveIdx(0);
  };

  useEffectP(() => {
    if (autoStart && !startedRef.current) {
      startedRef.current = true;
      const t = setTimeout(run, 600);
      return () => clearTimeout(t);
    }
  }, [autoStart]);

  useEffectP(() => {
    if (stage !== "reviewing") return;
    let i = 0;
    const tick = () => {
      i += 1;
      setActiveIdx(i);
      if (i >= RG_CHECKS.length) {
        setTimeout(() => setStage("done"), 320);
      } else {
        setTimeout(tick, 320);
      }
    };
    const t = setTimeout(tick, 320);
    return () => clearTimeout(t);
  }, [stage]);

  const okCount   = RG_CHECKS.filter(c => c.status === "ok").length;
  const warnCount = RG_CHECKS.filter(c => c.status === "warn").length;
  const riskCount = RG_CHECKS.filter(c => c.status === "risk").length;
  const verdict   = riskCount > 0 ? "blocked" : warnCount > 1 ? "conditional" : "ready";

  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.1fr) minmax(0, 1fr)", minHeight: 460 }}
         className="rg-demo-grid">
      {/* LEFT */}
      <div style={{ padding: "24px 28px", borderRight: "1px solid var(--border-subtle)" }} className="rg-demo-left">
        <div className="row between" style={{ marginBottom: 18 }}>
          <div className="row gap-8">
            <span className="mono-sm" style={{ color: "var(--text-primary)" }}>release/2026.05.15-r2</span>
            <span className="pill pill-dim">12 COMPONENTS</span>
          </div>
          <span className="mono-sm muted">Policy Pack · CoE-Fed-v3.2</span>
        </div>

        <div className="row between" style={{ marginBottom: 24 }}>
          <div>
            <div className="eyebrow">Review</div>
            <div className="h3" style={{ marginTop: 4 }}>Promotion to UAT</div>
          </div>
          {stage === "done" ? (
            <button className="btn btn-secondary btn-sm" onClick={run}>
              <IconRefresh /> Re-run review
            </button>
          ) : stage === "idle" ? (
            <button className="btn btn-primary btn-sm" onClick={run}>
              <IconShield /> Run review
            </button>
          ) : (
            <span className="mono-sm" style={{ color: "var(--accent)" }}>
              <span className="spin" style={{ display: "inline-block", marginRight: 8 }}>◐</span>
              REVIEWING · {activeIdx} / {RG_CHECKS.length}
            </span>
          )}
        </div>

        <div style={{ display: "flex", flexDirection: "column" }}>
          {RG_CHECKS.map((c, i) => {
            const isDone = stage === "done" || i < activeIdx;
            const isActive = stage === "reviewing" && i === activeIdx;
            return (
              <div key={c.key} style={{
                display: "grid",
                gridTemplateColumns: "20px 1fr auto",
                gap: 12, alignItems: "center",
                padding: "10px 0",
                borderBottom: "1px solid var(--border-subtle)",
                opacity: !isDone && !isActive ? 0.4 : 1,
                transition: "opacity 200ms",
              }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
                  {isDone
                    ? <span className={`dot dot-${c.status}`} />
                    : isActive
                      ? <span className="spin" style={{ color: "var(--accent)", display: "inline-block" }}>◐</span>
                      : <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
                  }
                </div>
                <div>
                  <div style={{ fontSize: 13.5, color: "var(--text-primary)" }}>{c.label}</div>
                  {isDone && <div className="mono-sm muted" style={{ marginTop: 2 }}>{c.detail}</div>}
                </div>
                {isDone && (
                  <span className={`pill pill-${c.status === "ok" ? "ok" : c.status === "warn" ? "warn" : "risk"}`}>
                    {c.status === "ok" ? "PASS" : c.status === "warn" ? "REVIEW" : "BLOCK"}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* RIGHT */}
      <div style={{ padding: "24px 28px", display: "flex", flexDirection: "column" }} className="rg-demo-right">
        <div className="eyebrow eyebrow-accent" style={{ marginBottom: 16 }}>// Readiness</div>

        {stage !== "done" ? (
          <div style={{
            flex: 1, display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center", textAlign: "center",
            color: "var(--text-muted)",
            border: "1px dashed var(--border)",
            borderRadius: "var(--r-2)",
            padding: 32,
          }}>
            <IconShield s={28} c="var(--text-dim)" />
            <div className="mono-sm" style={{ marginTop: 16, color: "var(--text-secondary)" }}>
              {stage === "idle" ? "Awaiting review" : "Applying policy pack…"}
            </div>
            <div className="body-sm" style={{ marginTop: 8, maxWidth: 30 + "ch" }}>
              Checks artifacts against CoE-Fed-v3.2 governance rules.
            </div>
          </div>
        ) : (
          <>
            <div className="row" style={{ gap: 20, marginBottom: 20, alignItems: "flex-start" }}>
              <div style={{
                width: 64, height: 64, borderRadius: 12,
                background: verdict === "blocked" ? "var(--risk-dim)" : verdict === "conditional" ? "var(--warn-dim)" : "var(--ok-dim)",
                border: `1px solid ${verdict === "blocked" ? "rgba(217,99,112,0.35)" : verdict === "conditional" ? "rgba(212,160,64,0.35)" : "rgba(95,176,134,0.35)"}`,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: verdict === "blocked" ? "var(--risk)" : verdict === "conditional" ? "var(--warn)" : "var(--ok)",
              }}>
                <IconShield s={28} />
              </div>
              <div style={{ flex: 1 }}>
                <div className={`pill ${verdict === "blocked" ? "pill-risk" : verdict === "conditional" ? "pill-warn" : "pill-ok"}`}>
                  {verdict === "blocked" ? "BLOCKED" : verdict === "conditional" ? "CONDITIONAL" : "READY"}
                </div>
                <div className="h3" style={{ marginTop: 8 }}>
                  {verdict === "blocked" ? "Not ready for UAT" : verdict === "conditional" ? "Ready with caveats" : "Ready for promotion"}
                </div>
                <div className="body-sm" style={{ marginTop: 4, color: "var(--text-secondary)" }}>
                  {okCount} pass · {warnCount} review · {riskCount} block
                </div>
              </div>
            </div>

            <div style={{
              background: "var(--bg-elevated)",
              border: "1px solid var(--border-subtle)",
              borderLeft: "2px solid var(--risk)",
              padding: "12px 14px",
              borderRadius: "var(--r-2)",
              marginBottom: 12,
            }}>
              <div className="mono-sm" style={{ color: "var(--risk)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 4 }}>
                Blocker · 1
              </div>
              <div style={{ fontSize: 13.5, color: "var(--text-primary)", marginBottom: 2 }}>
                Rollback plan missing for AccountTrigger deprecation
              </div>
              <div className="mono-sm muted">Policy: CoE-Fed-v3.2 §4.2 · Required artifact: rollback.sql</div>
            </div>

            <div style={{
              background: "var(--bg-elevated)",
              border: "1px solid var(--border-subtle)",
              borderLeft: "2px solid var(--warn)",
              padding: "12px 14px",
              borderRadius: "var(--r-2)",
            }}>
              <div className="mono-sm" style={{ color: "var(--warn)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 4 }}>
                Review · 2
              </div>
              <div style={{ fontSize: 13.5, color: "var(--text-primary)", marginBottom: 2 }}>
                Negative-path test evidence incomplete · 1 AI change lacks reviewer
              </div>
              <div className="mono-sm muted">Suggested owner: QA Lead</div>
            </div>

            <div className="row between" style={{ marginTop: "auto", paddingTop: 20 }}>
              <span className="mono-sm muted">Generate CAB packet · audit log written</span>
              <button className="btn btn-ghost btn-sm">Open release <IconArrow /></button>
            </div>
          </>
        )}
      </div>

      <style>{`
        @media (max-width: 760px) {
          .rg-demo-grid { grid-template-columns: 1fr !important; }
          .rg-demo-left { border-right: 0 !important; border-bottom: 1px solid var(--border-subtle); }
        }
      `}</style>
    </div>
  );
}


/* ──────────────── Playground wrapper ──────────────────────────────────── */

function Playground({ defaultDemo = "orglens" }) {
  const [tab, setTab] = useStateP(defaultDemo);
  const [ref, inView] = useInView({ threshold: 0.25 });
  const [armed, setArmed] = useStateP(false);

  useEffectP(() => { setTab(defaultDemo); }, [defaultDemo]);
  useEffectP(() => { if (inView) setArmed(true); }, [inView]);

  return (
    <div ref={ref} className="card" style={{
      background: "var(--surface-0)",
      borderColor: "var(--border)",
      overflow: "hidden",
      boxShadow: "0 24px 64px rgba(0,0,0,0.4)",
    }}>
      {/* fake window chrome / tab bar */}
      <div style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        padding: "10px 14px 0",
        borderBottom: "1px solid var(--border-subtle)",
      }}>
        <div className="row gap-8" style={{ paddingBottom: 10 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
          <span className="mono-sm muted" style={{ marginLeft: 12 }}>// live demo · synthetic data</span>
        </div>
        <div className="row" style={{ gap: 0, paddingBottom: 0 }}>
          <DemoTab active={tab === "orglens"} onClick={() => setTab("orglens")}>OrgLens AI · scan</DemoTab>
          <DemoTab active={tab === "releaseguard"} onClick={() => setTab("releaseguard")}>ReleaseGuard · review</DemoTab>
        </div>
      </div>

      {tab === "orglens" ? (
        <OrgLensDemo autoStart={armed} key={`ol-${armed}`} />
      ) : (
        <ReleaseGuardDemo autoStart={armed} key={`rg-${armed}`} />
      )}
    </div>
  );
}

function DemoTab({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      background: "transparent",
      border: 0,
      color: active ? "var(--text-primary)" : "var(--text-muted)",
      padding: "10px 14px",
      fontSize: 13,
      fontWeight: 500,
      letterSpacing: "-0.005em",
      borderBottom: `2px solid ${active ? "var(--accent)" : "transparent"}`,
      marginBottom: -1,
      transition: "color 120ms, border-color 120ms",
    }}>
      {children}
    </button>
  );
}

Object.assign(window, { Playground, OrgLensDemo, ReleaseGuardDemo });
