/* Onboarding — 3 steps post-signup
   Step 1: Tenant — name + vertical
   Step 2: App — name + compliance preset
   Step 3: Install — code + API key + live polling for first call
*/

const VERTICALS = [
  { id: "healthcare", title: "Healthcare", sub: "HIPAA · FDA · clinical-grade verification", icon: "shieldCheck" },
  { id: "legal", title: "Legal", sub: "Citation provenance · statute lookup", icon: "fileText" },
  { id: "fintech", title: "Financial services", sub: "SOX · SR 11-7 · model risk", icon: "card" },
  { id: "other", title: "Other regulated", sub: "Custom compliance frameworks", icon: "shield" },
];

const PRESETS = {
  healthcare: [
    { id: "hipaa", title: "HIPAA", sub: "PHI redaction · BAA-eligible · 6-year retention" },
    { id: "fda21cfr11", title: "FDA 21 CFR Part 11", sub: "Electronic records · e-signatures · audit chain" },
    { id: "none", title: "Custom / none", sub: "Configure manually later" },
  ],
  legal: [
    { id: "abamr", title: "ABA Model Rule 1.6 + 5.3", sub: "Confidentiality · supervised use" },
    { id: "none", title: "Custom / none", sub: "Configure manually later" },
  ],
  fintech: [
    { id: "sox", title: "SOX §302/§404", sub: "Internal-controls evidence chain" },
    { id: "sr117", title: "SR 11-7 model risk", sub: "Federal Reserve model governance" },
    { id: "none", title: "Custom / none", sub: "Configure manually later" },
  ],
  other: [
    { id: "euaiact", title: "EU AI Act Art. 12", sub: "Tamper-evident logging for high-risk AI" },
    { id: "none", title: "Custom / none", sub: "Configure manually later" },
  ],
};

const Onboarding = ({ onFinish }) => {
  const [step, setStep] = React.useState(1);
  const [tenant, setTenant] = React.useState({
    name: "Meridian Health Network",
    vertical: "healthcare",
    org: "MHN-04221",
  });
  const [app, setApp] = React.useState({
    name: "Encounter Summary Drafter",
    preset: "hipaa",
    purpose: "Drafts clinician-facing summaries of patient encounters",
  });
  const [installed, setInstalled] = React.useState({ npm: false, signed: false, firstCall: false });

  // Auto-progress the "Waiting for first call" indicator on step 3.
  React.useEffect(() => {
    if (step !== 3) return;
    const t1 = setTimeout(() => setInstalled((s) => ({ ...s, npm: true })), 1800);
    const t2 = setTimeout(() => setInstalled((s) => ({ ...s, signed: true })), 3800);
    const t3 = setTimeout(() => setInstalled((s) => ({ ...s, firstCall: true })), 6000);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, [step]);

  const next = () => setStep((s) => Math.min(3, s + 1));
  const prev = () => setStep((s) => Math.max(1, s - 1));

  return (
    <div className="onb">
      <header className="onb__top">
        <div className="onb__brand">
          <span>Attestia</span>
        </div>
        <div className="onb__progress">
          <OnbStep n={1} label="Tenant" active={step === 1} done={step > 1} />
          <OnbConnector done={step > 1} />
          <OnbStep n={2} label="App" active={step === 2} done={step > 2} />
          <OnbConnector done={step > 2} />
          <OnbStep n={3} label="Install" active={step === 3} done={false} />
        </div>
        <div className="onb__user">
          <span className="text-xs muted">{SCENARIO.tenant.user.name}</span>
          <div className="avatar">{SCENARIO.tenant.user.initials}</div>
        </div>
      </header>

      <div className="onb__main">
        <div className="onb__inner">
          {step === 1 && <StepTenant value={tenant} onChange={setTenant} onNext={next} />}
          {step === 2 && <StepApp value={app} tenant={tenant} onChange={setApp} onNext={next} onPrev={prev} />}
          {step === 3 && (
            <StepInstall
              app={app}
              tenant={tenant}
              installed={installed}
              onPrev={prev}
              onFinish={onFinish}
            />
          )}
        </div>
      </div>

      <footer className="onb__foot">
        <div className="onb__foot-inner">
          <span className="text-xs muted">Step {step} of 3 · Setup takes ~2 minutes</span>
          <span className="text-xs muted">Need help? <a href="#" onClick={(e) => e.preventDefault()}>docs.attestia.ai/quickstart</a></span>
        </div>
      </footer>
    </div>
  );
};

const OnbStep = ({ n, label, active, done }) => (
  <div className={`onb-step ${active ? "onb-step--active" : ""} ${done ? "onb-step--done" : ""}`}>
    <span className="onb-step__dot">
      {done ? window.Icon.checkSimple({ size: 12 }) : n}
    </span>
    <span className="onb-step__label">{label}</span>
  </div>
);

const OnbConnector = ({ done }) => (
  <span className={`onb-connector ${done ? "onb-connector--done" : ""}`} />
);

/* -------- Step 1: Tenant -------- */
const StepTenant = ({ value, onChange, onNext }) => (
  <div className="onb-card">
    <div className="onb-card__header">
      <span className="onb-card__eyebrow">Step 1 of 3</span>
      <h1>Name your tenant</h1>
      <p className="onb-card__sub">
        A tenant scopes evidence, sources, and team. Most organizations use one tenant per legal entity.
      </p>
    </div>
    <div className="onb-card__body">
      <div className="grid-2">
        <Field label="Organization name" required hint="Visible to your team and auditors">
          <input
            className="input"
            placeholder="Meridian Health Network"
            value={value.name}
            onChange={(e) => onChange({ ...value, name: e.target.value })}
            autoFocus
          />
        </Field>
        <Field label="Tenant identifier" hint="Used in URLs and bulletins. Letters, digits, dashes.">
          <input
            className="input mono"
            value={value.org}
            onChange={(e) => onChange({ ...value, org: e.target.value.toUpperCase() })}
          />
        </Field>
      </div>

      <Field label="Regulatory context" hint="Sets default compliance presets in the next step.">
        <div className="vertical-grid">
          {VERTICALS.map((v) => (
            <RadioCard
              key={v.id}
              selected={value.vertical === v.id}
              title={v.title}
              sub={v.sub}
              icon={window.Icon[v.icon]({ size: 18 })}
              onClick={() => onChange({ ...value, vertical: v.id })}
            />
          ))}
        </div>
      </Field>

      <div className="onb-note">
        <span style={{ color: "var(--brand-ink)" }}>{window.Icon.shield({ size: 14 })}</span>
        <div>
          <strong>Data residency:</strong> Healthcare tenants are routed to our US-East BAA-eligible region.
          <span className="muted"> Change in Settings · Tenant after setup.</span>
        </div>
      </div>
    </div>
    <div className="onb-card__foot">
      <span className="text-xs muted">Press <kbd className="kbd">Enter</kbd> to continue</span>
      <Button variant="primary" onClick={onNext} iconRight={window.Icon.arrowRight({ size: 14 })} disabled={!value.name}>
        Continue
      </Button>
    </div>
  </div>
);

/* -------- Step 2: App -------- */
const StepApp = ({ value, tenant, onChange, onNext, onPrev }) => {
  const presets = PRESETS[tenant.vertical] || PRESETS.other;
  return (
    <div className="onb-card">
      <div className="onb-card__header">
        <span className="onb-card__eyebrow">Step 2 of 3 · {tenant.name}</span>
        <h1>Create your first app</h1>
        <p className="onb-card__sub">
          An app is one LLM workflow you'll wrap with Attestia. You can add more later — most tenants run 1–4 apps.
        </p>
      </div>
      <div className="onb-card__body">
        <div className="grid-2">
          <Field label="App name" required>
            <input
              className="input"
              placeholder="Encounter Summary Drafter"
              value={value.name}
              onChange={(e) => onChange({ ...value, name: e.target.value })}
              autoFocus
            />
          </Field>
          <Field label="Purpose tag" hint="A short, stable label that appears on every trace.">
            <input
              className="input mono"
              placeholder="discharge_summary"
              value={value.purpose}
              onChange={(e) => onChange({ ...value, purpose: e.target.value })}
            />
          </Field>
        </div>

        <Field label="Compliance preset" hint="Configures redaction, retention, and evidence-pack defaults. Editable later.">
          <div className="preset-grid">
            {presets.map((p) => (
              <RadioCard
                key={p.id}
                selected={value.preset === p.id}
                title={p.title}
                sub={p.sub}
                onClick={() => onChange({ ...value, preset: p.id })}
              />
            ))}
          </div>
        </Field>

        <div className="preset-detail">
          <div className="preset-detail__head">
            <Badge tone="sealed" icon={window.Icon.shieldCheck({ size: 12 })}>{presets.find((p) => p.id === value.preset)?.title}</Badge>
            <span className="text-xs muted">Pre-configured defaults</span>
          </div>
          <div className="preset-detail__rows">
            <PresetRow label="PHI redaction" value="18 HIPAA identifiers · auto-redact" />
            <PresetRow label="Retention" value="6 years · cryptographic stubs un-purgeable" />
            <PresetRow label="Evidence chain" value="Ed25519 · daily public bulletin" />
            <PresetRow label="Sandbox region" value="US-East · BAA in place" />
            <PresetRow label="Multi-judge consensus" value="3 judges · Cohen's κ ≥ 0.7 required" />
          </div>
        </div>
      </div>
      <div className="onb-card__foot">
        <Button variant="ghost" onClick={onPrev} icon={window.Icon.arrowLeft({ size: 14 })}>Back</Button>
        <div className="spacer" />
        <Button variant="primary" onClick={onNext} iconRight={window.Icon.arrowRight({ size: 14 })} disabled={!value.name}>
          Continue
        </Button>
      </div>
    </div>
  );
};

const PresetRow = ({ label, value }) => (
  <div className="preset-row">
    <span className="muted text-xs no-wrap">{label}</span>
    <span className="text-sm">{value}</span>
  </div>
);

/* -------- Step 3: Install + Poll for first call -------- */
const SNIPPET = `import { Attestia } from "@attestia/sdk";
import OpenAI from "openai";

const attestia = new Attestia({ apiKey: process.env.ATTESTIA_KEY });
const openai = attestia.wrap(new OpenAI());

// Drop-in. Same OpenAI surface — every call is now sealed.
const r = await openai.chat.completions.create({
  model: "gpt-4o-mini",
  purpose: "discharge_summary",          // appears on every trace
  user_tag: clinicianId,                 // de-identified per HIPAA
  messages: [...]
});`;

const StepInstall = ({ app, tenant, installed, onPrev, onFinish }) => {
  const [copied, setCopied] = React.useState({ npm: false, key: false, code: false });
  const apiKey = "af_live_x3k2qz9a8mn4lp2rt7yv";
  const apiKeyMasked = "af_live_••••••••••••••••rt7yv";
  const [reveal, setReveal] = React.useState(false);

  const copy = (k, val) => {
    try { navigator.clipboard?.writeText(val); } catch (_) {}
    setCopied((c) => ({ ...c, [k]: true }));
    setTimeout(() => setCopied((c) => ({ ...c, [k]: false })), 1500);
  };

  return (
    <div className="onb-card onb-card--wide">
      <div className="onb-card__header">
        <span className="onb-card__eyebrow">Step 3 of 3 · {app.name}</span>
        <h1>Wrap your first call</h1>
        <p className="onb-card__sub">
          One install, one wrap. Same OpenAI surface — every call gets a tamper-evident audit chain.
        </p>
      </div>
      <div className="onb-card__body">
        <div className="install-row">
          <span className="install-row__label">1. Install</span>
          <div className="install-code install-code--inline">
            <code>npm install @attestia/sdk</code>
            <Button variant="ghost" size="sm" onClick={() => copy("npm", "npm install @attestia/sdk")}
              icon={copied.npm ? window.Icon.checkSimple({ size: 12 }) : window.Icon.copy({ size: 12 })}>
              {copied.npm ? "Copied" : "Copy"}
            </Button>
          </div>
        </div>

        <div className="install-row">
          <span className="install-row__label">2. API key</span>
          <div className="install-key">
            <code className="mono">{reveal ? apiKey : apiKeyMasked}</code>
            <Button variant="ghost" size="sm" onClick={() => setReveal((r) => !r)}
              icon={window.Icon.eye({ size: 12 })}>
              {reveal ? "Hide" : "Reveal"}
            </Button>
            <Button variant="ghost" size="sm" onClick={() => copy("key", apiKey)}
              icon={copied.key ? window.Icon.checkSimple({ size: 12 }) : window.Icon.copy({ size: 12 })}>
              {copied.key ? "Copied" : "Copy"}
            </Button>
          </div>
          <div className="install-warn">
            <span style={{ color: "var(--partial)" }}>{window.Icon.alertTriangle({ size: 12 })}</span>
            Shown once. Store in your secret manager. You can rotate keys in Settings · API keys.
          </div>
        </div>

        <div className="install-row">
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
            <span className="install-row__label" style={{ margin: 0 }}>3. Wrap your client</span>
            <Badge tone="info" size="lg">TypeScript</Badge>
            <span className="spacer" />
            <Button variant="ghost" size="sm" onClick={() => copy("code", SNIPPET)}
              icon={copied.code ? window.Icon.checkSimple({ size: 12 }) : window.Icon.copy({ size: 12 })}>
              {copied.code ? "Copied" : "Copy"}
            </Button>
          </div>
          <pre className="install-code"><code>{SNIPPET}</code></pre>
        </div>

        <div className="poll">
          <div className="poll__head">
            <span className={`poll-dot ${installed.firstCall ? "poll-dot--done" : "poll-dot--pulse"}`} />
            <div style={{ flex: 1 }}>
              <div className="fw-600">
                {installed.firstCall ? "First trace received and sealed" : "Listening for your first verified call…"}
              </div>
              <div className="text-xs muted">
                {installed.firstCall
                  ? `Trace af_x3k…7yv · sealed at 10:34:03 UTC · ✓ Verified`
                  : `Run the snippet above. We auto-detect the first call typically within 30 seconds.`}
              </div>
            </div>
            {installed.firstCall && <Badge tone="sealed" size="lg" icon={window.Icon.lock({ size: 12 })}>Sealed</Badge>}
          </div>
          <div className="poll__steps">
            <PollStep label="SDK detected (handshake)" done={installed.npm} />
            <PollStep label="First call forwarded · response signed" done={installed.signed} />
            <PollStep label="Evidence sealed · added to Block #1,247" done={installed.firstCall} />
          </div>
        </div>
      </div>
      <div className="onb-card__foot">
        <Button variant="ghost" onClick={onPrev} icon={window.Icon.arrowLeft({ size: 14 })}>Back</Button>
        <div className="spacer" />
        <Button variant="ghost" onClick={onFinish}>Skip for now</Button>
        <Button
          variant="primary"
          onClick={onFinish}
          iconRight={window.Icon.arrowRight({ size: 14 })}
          disabled={!installed.firstCall}
        >
          {installed.firstCall ? "Go to dashboard" : "Waiting…"}
        </Button>
      </div>
    </div>
  );
};

const PollStep = ({ label, done }) => (
  <div className={`poll-step ${done ? "poll-step--done" : ""}`}>
    <span className="poll-step__icon">
      {done
        ? window.Icon.checkSimple({ size: 12 })
        : <span className="poll-step__pending" />}
    </span>
    <span className={done ? "" : "muted"}>{label}</span>
    {done && <span className="text-xs muted right">just now</span>}
  </div>
);

window.Onboarding = Onboarding;
