// wf-bootstrap.jsx — Section 5: Bootstrap (PUC-10 / PUC-11, INV-1/INV-7).
// Operator & developer surfaces — terminals and a runbook, not app screens.
const { Screen: BScreen, Wordmark: BWordmark, WF_T: BT, WF_DS: BDS } = window;
const { Eyebrow: BEyebrow, Soul: BSoul, Tag: BTag, Callout: BCallout } = BDS;

const MONO = 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace';

// ── Terminal window ────────────────────────────────────────────────────────
function Terminal({ title, lines, style = {} }) {
  return (
    <div style={{
      background: 'var(--wv-night)', border: `1px solid ${BT.hair}`, borderRadius: 12,
      overflow: 'hidden', display: 'flex', flexDirection: 'column', ...style,
    }}>
      <div style={{ flex: '0 0 auto', height: 40, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${BT.hair}`, background: 'rgba(155,140,255,.05)' }}>
        <span style={{ display: 'flex', gap: 6 }}>
          {['rgba(155,140,255,.5)', 'rgba(244,199,107,.5)', 'rgba(237,234,255,.3)'].map((c, i) => (
            <span key={i} style={{ width: 9, height: 9, borderRadius: 5, background: c }} />
          ))}
        </span>
        <span style={{ fontFamily: MONO, fontSize: 12, color: BT.mute, marginLeft: 4 }}>{title}</span>
      </div>
      <div style={{ flex: 1, padding: '16px 18px', fontFamily: MONO, fontSize: 12.5, lineHeight: 1.75, whiteSpace: 'pre-wrap', overflow: 'hidden' }}>
        {lines.map((ln, i) => <TLine key={i} ln={ln} />)}
      </div>
    </div>
  );
}
function TLine({ ln }) {
  const [k, t] = ln;
  if (k === 'sp') return <div style={{ height: 9 }} />;
  if (k === 'cmd') return <div><span style={{ color: BT.lilac }}>$ </span><span style={{ color: BT.star }}>{t}</span></div>;
  if (k === 'step') return <div><span style={{ color: BT.lilac }}>→ </span><span style={{ color: BT.soft }}>{t}</span></div>;
  if (k === 'ok') return <div><span style={{ color: BT.gold }}>✓ </span><span style={{ color: BT.star }}>{t}</span></div>;
  if (k === 'hl') return <div style={{ color: BT.gold, background: 'rgba(244,199,107,.08)', margin: '0 -8px', padding: '1px 8px', borderRadius: 4 }}>{t}</div>;
  if (k === 'note') return <div style={{ color: 'var(--wv-starlight-55)', fontStyle: 'italic' }}>{t}</div>;
  return <div style={{ color: BT.mute }}>{t}</div>;
}

// ── Wrap a section artboard on the sky ─────────────────────────────────────
function Bay({ children, pad = 30 }) {
  return <div style={{ height: '100%', background: BT.sky, padding: pad, boxSizing: 'border-box', overflow: 'hidden', fontFamily: BT.body, display: 'flex', flexDirection: 'column' }}>{children}</div>;
}
function BayHead({ kicker, title, sub }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <BEyebrow style={{ margin: '0 0 8px' }}>{kicker}</BEyebrow>
      <h2 style={{ fontFamily: BT.disp, fontWeight: 700, letterSpacing: '-0.015em', fontSize: 22, color: BT.star, margin: '0 0 6px', lineHeight: 1.1 }}>{title}</h2>
      {sub && <p style={{ fontFamily: BT.body, fontSize: 13.5, lineHeight: 1.5, color: BT.soft, margin: 0, maxWidth: 560 }}>{sub}</p>}
    </div>
  );
}

// ── 1 · The principle — empty is a working state (INV-1) ───────────────────
function BootstrapPrinciple() {
  const steps = [
    ['Operator starts the app', 'scripts/dev.sh locally · flotilla deploy when deployed', 'lilac'],
    ['App migrates itself', 'pending .sql migrations apply in order, fail-stop (INV-7)', 'lilac'],
    ['/healthz goes green', 'process up · DB reachable · migrations current', 'gold'],
    ['First merchant walks the product', 'sign up → create storefront → admin (PUC-2 / 4 / 6)', 'gold'],
    ['First rows exist', 'created through the flows alone — nothing placed by hand', 'lilac'],
  ];
  return (
    <Bay>
      <BayHead kicker="INV-1 · the bootstrap property" title="Empty is a working state"
        sub="No seed step, ever. A fresh, empty database is a first-class state the product brings to life itself — which is what makes launching anywhere an ordinary, rehearsed act." />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0, position: 'relative' }}>
        {steps.map(([t, d, c], i) => {
          const col = c === 'gold' ? BT.gold : BT.lilac;
          return (
            <div key={i} style={{ display: 'flex', gap: 16, paddingBottom: i < steps.length - 1 ? 18 : 0 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: '0 0 auto' }}>
                <span style={{ width: 26, height: 26, borderRadius: 13, border: `1.5px solid ${col}`, color: col, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: BT.disp, fontWeight: 700, fontSize: 13 }}>{i + 1}</span>
                {i < steps.length - 1 && <span style={{ width: 1.5, flex: 1, minHeight: 22, background: BT.hair }} />}
              </div>
              <div style={{ paddingTop: 2 }}>
                <div style={{ fontFamily: BT.disp, fontWeight: 500, fontSize: 15, color: BT.star }}>{t}</div>
                <div style={{ fontFamily: MONO, fontSize: 11.5, color: BT.mute, marginTop: 3 }}>{d}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Bay>
  );
}

// ── 2 · The runbook — docs/BOOTSTRAP.md (paper) ────────────────────────────
function RunbookDoc() {
  const envs = [
    ['localhost', './scripts/dev.sh', 'Docker is the one prerequisite. Brings up Postgres, migrates, serves on :5173.'],
    ['pre-prod (PPE)', 'flotilla deploy ecomm --env ppe', 'Provisions Cloud SQL, resolves secrets, migrates at startup. Rehearse here first.'],
    ['production', 'flotilla deploy ecomm --env prod', 'The identical gesture. Day-one prod is simply the bootstrap state.'],
  ];
  return (
    <div style={{ height: '100%', background: 'var(--wv-paper)', padding: '34px 38px', boxSizing: 'border-box', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <span style={{ fontFamily: MONO, fontSize: 12, color: 'var(--wv-violet)', background: 'rgba(124,111,224,.12)', padding: '3px 10px', borderRadius: 999 }}>docs/BOOTSTRAP.md</span>
        <span style={{ fontFamily: MONO, fontSize: 11.5, color: '#8A7FB0' }}>the documented gesture</span>
      </div>
      <h2 style={{ fontFamily: BT.disp, fontWeight: 700, letterSpacing: '-0.015em', fontSize: 26, color: 'var(--wv-ink)', margin: '0 0 8px', lineHeight: 1.08 }}>Bringing ecomm up from empty</h2>
      <p style={{ fontFamily: BT.body, fontSize: 14, lineHeight: 1.55, color: '#4B4170', margin: '0 0 22px', maxWidth: 560 }}>
        One gesture, three environments. No hand-seeded data — the first merchant arrives through the product flows alone.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {envs.map(([env, cmd, note], i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '128px 1fr', gap: 18, alignItems: 'baseline' }}>
            <span style={{ fontFamily: BT.disp, fontWeight: 500, fontSize: 14, color: 'var(--wv-ink)' }}>{env}</span>
            <div>
              <div style={{ fontFamily: MONO, fontSize: 12.5, color: 'var(--wv-ink)', background: '#ECE8F7', border: '1px solid #DCD5F0', borderRadius: 8, padding: '7px 11px', display: 'inline-block' }}>{cmd}</div>
              <div style={{ fontFamily: BT.body, fontSize: 12.5, lineHeight: 1.5, color: '#6A5F90', marginTop: 6 }}>{note}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ flex: 1 }} />
      <BCallout onLight>Empty is a working state — there is no seed.</BCallout>
    </div>
  );
}

// ── 3 · localhost — scripts/dev.sh ─────────────────────────────────────────
function DevTerminal() {
  const lines = [
    ['cmd', 'git clone …/wiggleverse-ecomm && cd wiggleverse-ecomm'],
    ['cmd', './scripts/dev.sh'],
    ['sp'],
    ['step', 'datastore: starting postgres (docker compose up)…'],
    ['ok', 'postgres healthy · ecomm_dev · :5432'],
    ['step', 'migrations: applying pending…'],
    ['ok', '0001_init applied · schema current'],
    ['step', 'backend: uvicorn on :8000'],
    ['step', 'web: vite on :5173 (proxying /api)'],
    ['ok', '/healthz 200 {status:"ok", migrations:"current"}'],
    ['sp'],
    ['out', '  ecomm is up against an empty database.'],
    ['hl', '  open  http://localhost:5173'],
    ['sp'],
    ['note', 'one-time codes print to this log (LogMailer) — no real mail in dev.'],
  ];
  return (
    <Bay>
      <BayHead kicker="PUC-10 · localhost" title="One command from clean checkout"
        sub="A developer reaches “first merchant, first storefront” with Docker as the only prerequisite — the app migrates an empty database itself." />
      <Terminal title="scripts/dev.sh" lines={lines} style={{ flex: 1 }} />
    </Bay>
  );
}

// ── 4 · The code channel — dev log vs real email ───────────────────────────
function DevChannel() {
  return (
    <Bay>
      <BayHead kicker="PUC-10 / PUC-11 · the OTC channel" title="Where the one-time code lands"
        sub="Same issue/verify path everywhere — only the mailer differs by configuration (INV-8)." />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, flex: 1 }}>
        <div>
          <ChanLabel tone="lilac">Dev — the code prints to the backend log</ChanLabel>
          <Terminal title="backend · LogMailer" lines={[
            ['out', '[mailer] adapter=LogMailer'],
            ['out', '  to: mara@studiofern.com'],
            ['hl', '  subject: Your ecomm code: 419 204'],
            ['out', '  code valid 10m · single-use · 5 tries'],
          ]} />
        </div>
        <div>
          <ChanLabel tone="gold">Deployed — the code arrives as real email</ChanLabel>
          <div style={{ background: BT.raised, border: `1px solid ${BT.hairCard}`, borderRadius: 12, padding: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: BT.body, fontSize: 12, color: BT.mute, marginBottom: 8, borderBottom: `1px solid ${BT.hair}`, paddingBottom: 8 }}>
              <span>ecomm &lt;no-reply@ecomm.wiggleverse.org&gt;</span><span>now</span>
            </div>
            <div style={{ fontFamily: BT.disp, fontWeight: 500, fontSize: 15, color: BT.star, marginBottom: 6 }}>Your ecomm code: 419 204</div>
            <div style={{ fontFamily: BT.body, fontSize: 12.5, lineHeight: 1.5, color: BT.soft }}>
              Enter this code to sign in. It's good for 10 minutes. If you didn't request it, ignore this email.
            </div>
          </div>
        </div>
      </div>
    </Bay>
  );
}
function ChanLabel({ children, tone }) {
  const c = tone === 'gold' ? BT.gold : BT.lilac;
  return <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9, fontFamily: BT.body, fontSize: 12.5, color: BT.soft }}>
    <span aria-hidden="true" style={{ color: c }}>{tone === 'gold' ? '◆' : '◇'}</span>{children}
  </div>;
}

// ── 5 · deployed — flotilla (PPE then Prod) ────────────────────────────────
function DeployTerminal() {
  const lines = [
    ['cmd', 'flotilla deploy ecomm --env ppe'],
    ['sp'],
    ['step', 'provision: Cloud SQL (postgres) · backups + PITR…'],
    ['ok', 'database ready · secrets resolved from Secret Manager'],
    ['step', 'deploy: image → single VM · fail-stop'],
    ['step', 'migrations: applying at startup…'],
    ['ok', '0001_init applied'],
    ['ok', '/healthz 200 — ppe live'],
    ['out', '  rehearsal: real sign-up (real email) → storefront → admin ✓'],
    ['sp'],
    ['cmd', 'flotilla deploy ecomm --env prod'],
    ['ok', 'same gesture — day-one prod is the bootstrap state'],
  ];
  return (
    <Bay>
      <BayHead kicker="PUC-11 · pre-prod, then prod" title="The same gesture, deployed"
        sub="The operator runs flotilla; PPE rehearses Prod with real email (BUC-5a). No environment is “later.”" />
      <Terminal title="flotilla — operator front door" lines={lines} style={{ flex: 1 }} />
    </Bay>
  );
}

Object.assign(window, { BootstrapPrinciple, RunbookDoc, DevTerminal, DevChannel, DeployTerminal });
