// Overview + Integration handoff screens

const OverviewScreen = ({ setRoute, openModal }) => {
  const steps = [
    { key: "proj", label: "Create project", done: true, desc: "Ledger Payments" },
    { key: "env", label: "Configure environments", done: true, desc: "dev · staging · prod" },
    { key: "keys", label: "Issue API credentials", done: true, desc: "3 active keys" },
    { key: "oidc", label: "Register OIDC client", done: true, desc: "Sign in with Swop — Web" },
    { key: "policy", label: "Attach signing policy", done: false, desc: "Required before prod traffic" },
    { key: "webhook", label: "Verify webhook endpoint", done: false, desc: "Ingest events at scale" },
  ];
  const completed = steps.filter(s => s.done).length;
  const pct = Math.round((completed / steps.length) * 100);
  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Overview</h1>
          <p className="page-sub">Monitor integration health, pending actions, and traffic across Ledger Payments.</p>
        </div>
        <div className="page-actions">
          <Btn variant="secondary" icon={<IBook size={13}/>}>Docs</Btn>
          <Btn variant="primary" icon={<IPlus size={13}/>} onClick={() => setRoute("handoff")}>Integrate</Btn>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 24, marginBottom: 24 }}>
        <Card
          title="Integration progress"
          sub={`${completed} of ${steps.length} complete · estimated 12 minutes left`}
          actions={<Btn size="sm" variant="ghost" onClick={() => setRoute("handoff")}>Open handoff →</Btn>}
        >
          <div style={{ marginBottom: 16 }}>
            <Progress value={pct}/>
            <div className="row" style={{ justifyContent: "space-between", marginTop: 8 }}>
              <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{pct}%</span>
              <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Ready for staging traffic</span>
            </div>
          </div>
          <div style={{ display: "grid", gap: 0 }}>
            {steps.map((s, i) => (
              <div key={s.key} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "11px 0", borderTop: i === 0 ? "none" : "1px dashed var(--line)",
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: "50%", display: "grid", placeItems: "center",
                  background: s.done ? "var(--ok-soft)" : "var(--bg-sunken)",
                  color: s.done ? "var(--ok)" : "var(--ink-4)",
                  border: s.done ? "1px solid color-mix(in oklch, var(--ok) 30%, var(--line))" : "1px dashed var(--line-strong)",
                }}>
                  {s.done ? <ICheck size={12}/> : <span className="mono" style={{ fontSize: 11 }}>{i + 1}</span>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 500, color: s.done ? "var(--ink-2)" : "var(--ink)" }}>{s.label}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{s.desc}</div>
                </div>
                {!s.done && <Btn size="sm" variant="secondary">Continue</Btn>}
              </div>
            ))}
          </div>
        </Card>

        <div className="stack" style={{ gap: 20 }}>
          <Card title="Pending approvals" sub="Requests waiting on a human" actions={<Btn size="sm" variant="ghost" onClick={() => setRoute("signing")}>All →</Btn>}>
            <div className="stack" style={{ gap: 10 }}>
              <div className="row" style={{ alignItems: "flex-start", gap: 12, padding: "8px 0" }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent-ink)", display: "grid", placeItems: "center" }}><IFingerprint size={15}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>Sign transfer · 1.20 ETH</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>wlt_7bf24xA → 0xf2c3…9a11 · 3m ago</div>
                </div>
                <Btn size="sm" variant="primary" onClick={() => openModal("sign")}>Review</Btn>
              </div>
              <div className="row" style={{ alignItems: "flex-start", gap: 12, padding: "8px 0", borderTop: "1px dashed var(--line)" }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--warn-soft)", color: "var(--warn)", display: "grid", placeItems: "center" }}><IWarn size={15}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>Policy change · daily cap +50%</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Requested by Omar Vega · 12m ago</div>
                </div>
                <Btn size="sm" variant="secondary">Review</Btn>
              </div>
            </div>
          </Card>

          <Card title="Environment health">
            <div className="stack" style={{ gap: 10 }}>
              {["prod", "staging", "dev"].map(e => (
                <div key={e} className="row" style={{ justifyContent: "space-between", padding: "6px 0", borderBottom: e !== "dev" ? "1px dashed var(--line)" : "none" }}>
                  <div className="row" style={{ gap: 10 }}>
                    <span style={{ width: 7, height: 7, borderRadius: "50%", background: `var(--env-${e})` }}/>
                    <span style={{ fontSize: 13, fontWeight: 500, textTransform: "capitalize" }}>{e === "prod" ? "Production" : e === "staging" ? "Staging" : "Development"}</span>
                  </div>
                  <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
                    {e === "prod" ? "842 req/min · 0 err" : e === "staging" ? "41 req/min · 1 err" : "idle"}
                  </span>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>

      <Card title="Recent activity" sub="Live stream — newest first" actions={<Btn size="sm" variant="ghost" onClick={() => setRoute("audit")}>Audit log →</Btn>} bodyClass="pad-0">
        <table className="table">
          <tbody>
            {AUDIT_EVENTS.slice(0, 5).map(e => (
              <tr key={e.id}>
                <td className="mono" style={{ width: 90, color: "var(--ink-3)", fontSize: 12 }}>{e.t}</td>
                <td style={{ width: 140 }}>{e.who === "system" ? <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>system</span> : <span style={{ fontSize: 13 }}>{e.who}</span>}</td>
                <td style={{ fontSize: 13 }}>{e.action}</td>
                <td className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>{e.target}</td>
                <td style={{ fontSize: 12, color: "var(--ink-3)" }}>{e.meta}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
};

// --- Integration handoff — the hero flow
const HandoffScreen = ({ setRoute, openModal, tweaks }) => {
  const [step, setStep] = useStateS(2); // pretend user is mid-flow
  const total = 5;
  const steps = [
    { key: "proj", label: "Project", desc: "Ledger Payments · prj_7QkA2vN" },
    { key: "env", label: "Environments", desc: "dev · staging · prod" },
    { key: "keys", label: "API credentials", desc: "Server key + webhook secret" },
    { key: "oidc", label: "OIDC client", desc: "Hosted auth + Sign in with Swop" },
    { key: "sdk", label: "SDK snippet", desc: "Ship to a real login" },
  ];
  return (
    <>
      <div className="page-header">
        <div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>Developer handoff</div>
          <h1 className="page-title">Ship Swivy in under 10 minutes.</h1>
          <p className="page-sub">A guided path from a fresh project to your first authenticated, wallet-backed user — with credentials, policy scaffolding, and SDK snippets ready to paste.</p>
        </div>
        <div className="page-actions">
          <Btn variant="ghost" icon={<IDownload size={13}/>}>Export as runbook</Btn>
        </div>
      </div>

      {/* Stepper rail */}
      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 40, alignItems: "flex-start" }}>
        <div style={{ position: "sticky", top: 88 }}>
          <div className="stack" style={{ gap: 2 }}>
            {steps.map((s, i) => (
              <button key={s.key} onClick={() => setStep(i)} style={{
                display: "grid", gridTemplateColumns: "24px 1fr", gap: 10, padding: "10px 8px",
                borderRadius: 8, textAlign: "left", alignItems: "flex-start",
                background: step === i ? "var(--bg-sunken)" : "transparent",
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 6, display: "grid", placeItems: "center",
                  background: i < step ? "var(--ok-soft)" : i === step ? "var(--ink)" : "var(--bg-sunken)",
                  color: i < step ? "var(--ok)" : i === step ? "var(--bg)" : "var(--ink-3)",
                  fontSize: 11, fontWeight: 600,
                  border: i === step ? "none" : "1px solid var(--line)",
                  fontFamily: "var(--font-mono)",
                }}>
                  {i < step ? <ICheck size={12}/> : i + 1}
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: i === step ? "var(--ink)" : "var(--ink-2)" }}>{s.label}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>{s.desc}</div>
                </div>
              </button>
            ))}
          </div>
          <div style={{ marginTop: 16, padding: 12, border: "1px dashed var(--line-strong)", borderRadius: 10 }}>
            <div className="row" style={{ gap: 8, marginBottom: 6 }}>
              <ILock size={12} style={{ color: "var(--ink-3)" }}/>
              <span style={{ fontSize: 11.5, fontWeight: 500 }}>Production gate</span>
            </div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
              Prod environment unlocks after passkey step-up and a review by an Owner.
            </div>
          </div>
        </div>

        <div className="stack" style={{ gap: 20 }}>
          {step === 0 && <StepProject onNext={() => setStep(1)}/>}
          {step === 1 && <StepEnv onNext={() => setStep(2)}/>}
          {step === 2 && <StepKeys onNext={() => setStep(3)} openModal={openModal} tweaks={tweaks}/>}
          {step === 3 && <StepOidc onNext={() => setStep(4)} tweaks={tweaks}/>}
          {step === 4 && <StepSdk onDone={() => setRoute("overview")} tweaks={tweaks}/>}

          <div className="row" style={{ justifyContent: "space-between", paddingTop: 12, borderTop: "1px solid var(--line)" }}>
            <Btn variant="ghost" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0}>← Previous</Btn>
            <div className="row" style={{ gap: 12 }}>
              <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Step {step + 1} of {total}</span>
              {step < total - 1 && <Btn variant="primary" onClick={() => setStep(step + 1)}>Continue →</Btn>}
              {step === total - 1 && <Btn variant="primary" onClick={() => setRoute("overview")}>Finish ✓</Btn>}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

const StepProject = ({ onNext }) => (
  <Card title="Project" sub="A project groups credentials, policies, and audit scope.">
    <div className="stack" style={{ gap: 16 }}>
      <Field label="Project name" hint="Shown in console and in end-user consent screens.">
        <input className="input" defaultValue="Ledger Payments"/>
      </Field>
      <div className="grid-2">
        <Field label="Slug" hint="Used in URLs and webhook paths. Lowercase, hyphens.">
          <input className="input mono" defaultValue="ledger-payments"/>
        </Field>
        <Field label="Default chain" hint="Used when a request omits the chain field.">
          <select className="select" defaultValue="ETH">
            {CHAINS.map(c => <option key={c.key} value={c.key}>{c.label}</option>)}
          </select>
        </Field>
      </div>
      <Banner kind="info" title="Identity first, wallet second, chain third.">
        Swivy uses this order by default — you can expose chain detail progressively in your UI.
      </Banner>
    </div>
  </Card>
);

const StepEnv = ({ onNext }) => (
  <Card title="Environments" sub="Environments are the security boundary. Each has its own keys, policies, and audit stream.">
    <div className="stack" style={{ gap: 12 }}>
      {[
        { e: "dev", desc: "Sandbox keys · test data · no rate limits", ok: true },
        { e: "staging", desc: "Production-shaped · forked chain state", ok: true },
        { e: "prod", desc: "Live keys · real assets · passkey step-up", ok: false },
      ].map(x => (
        <div key={x.e} style={{
          display: "grid", gridTemplateColumns: "12px 1fr auto", gap: 14, alignItems: "center",
          padding: "14px 16px", background: "var(--bg-sunken)", borderRadius: 10,
          border: "1px solid var(--line)",
        }}>
          <span style={{ width: 10, height: 10, borderRadius: "50%", background: `var(--env-${x.e})` }}/>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500, textTransform: "capitalize" }}>{x.e === "prod" ? "Production" : x.e === "staging" ? "Staging" : "Development"}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{x.desc}</div>
          </div>
          {x.ok ? <Status kind="active">Provisioned</Status> : <Status kind="pending">Locked</Status>}
        </div>
      ))}
    </div>
  </Card>
);

const StepKeys = ({ onNext, openModal, tweaks }) => {
  const [revealed, setRevealed] = useStateS(false);
  const fakeKey = "sk_live_a94fE3rT8vNq91KpMnBxYzC2hA5jK0sL";
  return (
    <>
      <Card
        title="API credentials"
        sub="You'll see the server secret once. Store it in your secrets manager."
        actions={<Btn size="sm" variant="secondary" icon={<IRotate size={12}/>} onClick={() => openModal("rotate")}>Rotate</Btn>}
      >
        <div className="stack" style={{ gap: 14 }}>
          <div style={{ padding: 16, background: "var(--bg-sunken)", border: "1px solid var(--line)", borderRadius: 10 }}>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 10 }}>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>Server secret</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Use from your backend only. Never ship to a client.</div>
              </div>
              <Status kind="pending">One-time reveal</Status>
            </div>
            <div className="row" style={{ gap: 8 }}>
              <div style={{
                flex: 1, fontFamily: "var(--font-mono)", fontSize: 12.5,
                background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 8,
                padding: "10px 12px", color: revealed ? "var(--ink)" : "var(--ink-4)",
                letterSpacing: revealed ? "-0.01em" : "0.2em",
                overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis",
              }}>
                {revealed ? fakeKey : "•".repeat(40)}
              </div>
              <Btn variant="secondary" icon={revealed ? <IEyeOff size={13}/> : <IEye size={13}/>} onClick={() => setRevealed(v => !v)}>
                {revealed ? "Hide" : "Reveal"}
              </Btn>
              <Btn variant="secondary" icon={<ICopy size={13}/>}>Copy</Btn>
            </div>
            <div className="row" style={{ marginTop: 10, gap: 10, fontSize: 11.5, color: "var(--ink-3)" }}>
              <IFingerprint size={12}/>
              <span>Reveal required passkey — <span className="mono">Touch ID · Lena Osei</span> · {new Date().toLocaleTimeString()}</span>
            </div>
          </div>

          <Field label="Webhook signing secret" hint="Swivy signs webhook payloads with HMAC-SHA256. Verify on your endpoint.">
            <div className="row" style={{ gap: 8 }}>
              <input className="input mono" readOnly value="whsec_1f8A…B3qZ" />
              <Btn variant="secondary" icon={<ICopy size={13}/>}>Copy</Btn>
            </div>
          </Field>
        </div>
      </Card>

      <Card title="Scopes" sub="Least privilege. Each key gets exactly what it needs.">
        <div className="stack" style={{ gap: 8 }}>
          {[
            { k: "wallets:write", d: "Create wallets, rotate keys, attach policies", on: true },
            { k: "signing:write", d: "Request signatures; execution is policy-gated", on: true },
            { k: "audit:read", d: "Read audit events and export compliance reports", on: true },
            { k: "webhooks:read", d: "Subscribe to event stream", on: false },
            { k: "admin:write", d: "Create projects, invite members, change billing", on: false },
          ].map(s => (
            <div key={s.k} className="row" style={{ padding: "8px 10px", borderRadius: 6, justifyContent: "space-between" }}>
              <div>
                <div className="mono" style={{ fontSize: 12.5 }}>{s.k}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{s.d}</div>
              </div>
              <Toggle on={s.on} onChange={() => {}}/>
            </div>
          ))}
        </div>
      </Card>
    </>
  );
};

const StepOidc = ({ onNext, tweaks }) => (
  <>
    <Card title="OIDC client" sub="Register the app that will use Sign in with Swop.">
      <div className="stack" style={{ gap: 14 }}>
        <div className="grid-2">
          <Field label="Client name"><input className="input" defaultValue="Ledger — Web"/></Field>
          <Field label="Client type" hint="Use PKCE for public clients (mobile, SPA).">
            <select className="select" defaultValue="confidential">
              <option>confidential</option>
              <option>public (PKCE)</option>
            </select>
          </Field>
        </div>
        <Field label="Redirect URIs" hint="One per line. Must be exact match on callback.">
          <textarea className="textarea" defaultValue={"https://app.northbridge.io/callback\nhttps://staging.northbridge.io/callback"}/>
        </Field>
        <Field label="Token lifetimes" hint="Access token exp · refresh token rotation">
          <div className="row" style={{ gap: 10 }}>
            <input className="input mono" defaultValue="15m" style={{ maxWidth: 120 }}/>
            <span style={{ color: "var(--ink-4)" }}>/</span>
            <input className="input mono" defaultValue="30d" style={{ maxWidth: 120 }}/>
          </div>
        </Field>
      </div>
    </Card>

    <Card title="Discovery" sub="Share these with your auth library. They're stable per environment.">
      <div className="stack" style={{ gap: 0 }}>
        <KV k="Issuer"><span className="mono" style={{ fontSize: 12 }}>https://auth.swivy.dev/o/prj_7QkA2vN</span></KV>
        <KV k="Authorization"><span className="mono" style={{ fontSize: 12 }}>/authorize</span></KV>
        <KV k="Token"><span className="mono" style={{ fontSize: 12 }}>/token</span></KV>
        <KV k="JWKS"><span className="mono" style={{ fontSize: 12 }}>/.well-known/jwks.json</span></KV>
        <KV k="Userinfo"><span className="mono" style={{ fontSize: 12 }}>/userinfo</span></KV>
      </div>
    </Card>
  </>
);

const StepSdk = ({ onDone, tweaks }) => {
  const tsCode = `import { createSwivy } from "@swivy/sdk";

const swivy = createSwivy({
  projectId: "prj_7QkA2vN",
  environment: "staging",
  authMethods: ["email", "passkey"],
  // Chain defaults — override per-call if needed
  defaultChain: "ETH",
});

export async function handleLogin() {
  const session = await swivy.auth.loginWithEmail({
    email: "user@example.com",
  });

  // Identity first, wallet second.
  const wallet = await swivy.wallets.getOrCreate({
    chain: "ETH",
  });

  return { session, wallet };
}`;
  const curlCode = `curl https://api.swivy.dev/v1/wallets \\
  -H "Authorization: Bearer sk_live_a94f..." \\
  -H "Swivy-Environment: staging" \\
  -H "Content-Type: application/json" \\
  -d '{
    "owner": "user_29Kxa",
    "chain": "ETH"
  }'`;
  const reactCode = `import { SwivyProvider, useSwivy } from "@swivy/react";

export default function App() {
  return (
    <SwivyProvider projectId="prj_7QkA2vN">
      <Checkout />
    </SwivyProvider>
  );
}

function Checkout() {
  const { user, signAndSend } = useSwivy();
  return (
    <button onClick={() => signAndSend({ to: "0x…", value: "0.1" })}>
      Pay with {user.email}
    </button>
  );
}`;
  return (
    <>
      <Card title="SDK snippet" sub="Drop into your app. We've pre-filled credentials for this project and environment.">
        <CodeBlock
          style={tweaks.codeBlockStyle}
          files={[
            { name: "auth.ts", lang: "TypeScript", code: tsCode },
            { name: "App.tsx", lang: "React", code: reactCode },
            { name: "curl", lang: "Shell", code: curlCode },
          ]}
        />
      </Card>

      <Card title="Hand it off" sub="Everything your dev team needs, bundled.">
        <div className="grid-3">
          {[
            { t: "Starter repo", d: "Next.js + Swivy preconfigured", i: <IExternal size={14}/> },
            { t: "Postman collection", d: "50 endpoints, realistic payloads", i: <IDownload size={14}/> },
            { t: "Slack handoff", d: "Invite your devs to #swivy-ledger", i: <IExternal size={14}/> },
          ].map((x, i) => (
            <button key={i} style={{
              textAlign: "left", padding: 14, background: "var(--bg-sunken)",
              border: "1px solid var(--line)", borderRadius: 10,
              display: "flex", flexDirection: "column", gap: 6,
            }}>
              <div className="row" style={{ justifyContent: "space-between" }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{x.t}</div>
                <span style={{ color: "var(--ink-4)" }}>{x.i}</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{x.d}</div>
            </button>
          ))}
        </div>
      </Card>
    </>
  );
};

Object.assign(window, { OverviewScreen, HandoffScreen });
