// mint-app.jsx, interactive "Mint a xCIPHR" prototype (V5 self-custody).
// Faithful to the real xCIPHR iOS flow: welcome → Sign in with Apple → Face ID
// + Apple sheet → activation funding (QR) → on-device key generation + encrypted
// backup + onboarding txns → on-chain.
// White brutalist surface, mono, `>` system strips; in-app GREEN for verified/Face ID.

const XC = {
  black: '#000', white: '#fff',
  grayLight: '#E0E0E0', grayMed: '#C0C0C0', grayDark: '#808080', grayDarker: '#404040',
  green: '#00C853', testnet: '#FFB800', error: '#FF3B30',
  tRed: '#FF5F56', tAmber: '#FFBD2E', tGreen: '#27C93F',
};
const MONO = 'Menlo, ui-monospace, SFMono-Regular, "JetBrains Mono", Consolas, "Liberation Mono", "Courier New", monospace';

// ── in-app primitives ──────────────────────────────────────────────────────
function RetroButton({ children, primary, onClick, disabled }) {
  const [p, setP] = React.useState(false);
  const bg = disabled ? XC.grayLight : p ? XC.grayLight : primary ? XC.black : XC.white;
  const fg = primary && !p && !disabled ? XC.white : XC.black;
  return (
    <div onPointerDown={() => setP(true)} onPointerUp={() => setP(false)} onPointerLeave={() => setP(false)}
      onClick={disabled ? undefined : onClick}
      style={{
        padding: '15px 22px', background: bg, color: fg, border: `2px solid ${XC.black}`,
        borderRightWidth: 3, borderBottomWidth: 3, boxShadow: `2px 2px 0 0 ${XC.black}`,
        fontFamily: MONO, fontSize: 14, fontWeight: 700, letterSpacing: '0.04em',
        textAlign: 'center', cursor: disabled ? 'not-allowed' : 'pointer', userSelect: 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, opacity: disabled ? 0.5 : 1,
      }}>{children}</div>
  );
}

function Caret() {
  const [on, setOn] = React.useState(true);
  React.useEffect(() => { const id = setInterval(() => setOn(v => !v), 500); return () => clearInterval(id); }, []);
  return <span style={{ display: 'inline-block', width: '0.6ch', fontWeight: 700, opacity: on ? 1 : 0 }}>_</span>;
}

function SystemStrip({ title }) {
  return (
    <div style={{ background: XC.black, color: XC.white, padding: '8px 18px 12px', display: 'flex',
      alignItems: 'center', justifyContent: 'space-between', fontFamily: MONO, fontSize: 13, letterSpacing: '0.1em' }}>
      <span>&gt;{title && <span style={{ marginLeft: 8, textTransform: 'uppercase', letterSpacing: '0.18em' }}>{title}</span>}</span>
      <span style={{ fontSize: 18, lineHeight: 1 }}>···</span>
    </div>
  );
}

function Traffic({ label }) {
  const dot = bg => <span style={{ width: 11, height: 11, borderRadius: '50%', display: 'inline-block', border: `1px solid ${XC.black}`, background: bg }} />;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 10px', background: XC.black, position: 'relative' }}>
      {dot(XC.tRed)}{dot(XC.tAmber)}{dot(XC.tGreen)}
      {label && <span style={{ position: 'absolute', left: 0, right: 0, textAlign: 'center', color: XC.white, fontFamily: MONO, fontSize: 11, letterSpacing: '0.2em', fontWeight: 600 }}>{label}</span>}
    </div>
  );
}

function AppTerminal({ children, style, label }) {
  return (
    <div style={{ background: XC.white, border: `2px solid ${XC.black}`, borderRightWidth: 3, borderBottomWidth: 3,
      boxShadow: `2px 2px 0 0 ${XC.black}`, display: 'flex', flexDirection: 'column', ...style }}>
      <Traffic label={label} />
      <div style={{ padding: '14px 14px', fontFamily: MONO, fontSize: 12.5, lineHeight: 1.7, color: XC.black, flex: 1 }}>{children}</div>
    </div>
  );
}

function Screen({ title, children, footer }) {
  return (
    <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', background: XC.white }}>
      <div style={{ height: 52 }} />
      <SystemStrip title={title} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '0 18px' }}>{children}</div>
      {footer && <div style={{ padding: '16px 18px 30px', display: 'flex', flexDirection: 'column', gap: 10 }}>{footer}</div>}
    </div>
  );
}

// ── Face ID (green smiley, matches the real app) ─────────────────────────────
function FaceID() {
  return (
    <div style={{ width: 86, height: 86, borderRadius: 20, background: XC.black, display: 'grid', placeItems: 'center' }}>
      <svg width="52" height="52" viewBox="0 0 52 52">
        <circle cx="26" cy="26" r="22" fill="none" stroke={XC.green} strokeWidth="3"/>
        <rect x="18" y="19" width="3.2" height="9" rx="1.6" fill={XC.green}/>
        <rect x="31" y="19" width="3.2" height="9" rx="1.6" fill={XC.green}/>
        <path d="M26 22 L26 30 L23 30" fill="none" stroke={XC.green} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M18 35 Q26 42 34 35" fill="none" stroke={XC.green} strokeWidth="2.8" strokeLinecap="round"/>
      </svg>
    </div>
  );
}

// native-ish "Sign in with Apple" sheet
function AppleSheet() {
  return (
    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, background: '#1c1c1e', borderTopLeftRadius: 16, borderTopRightRadius: 16,
      padding: '20px 20px 30px', fontFamily: '-apple-system, system-ui, sans-serif', color: '#fff', boxShadow: '0 -10px 40px rgba(0,0,0,0.5)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 19, fontWeight: 700 }}>Sign in with Apple</span>
        <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', fontSize: 15, color: '#aaa' }}>×</span>
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 18 }}>
        <img src="assets/sciphr-logo.png" alt="" style={{ width: 38, height: 38, background: '#fff', borderRadius: 9, padding: 4, boxSizing: 'border-box' }} />
        <span style={{ fontSize: 14, color: 'rgba(255,255,255,0.85)', lineHeight: 1.4 }}>Sign in to xCIPHR using your Apple Account.</span>
      </div>
      <div style={{ marginTop: 16, background: 'rgba(255,255,255,0.06)', borderRadius: 12, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'linear-gradient(135deg,#666,#333)' }} />
        <div><div style={{ fontSize: 15, fontWeight: 600 }}>Jarod Vyent</div><div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>Your account</div></div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, marginTop: 16 }}>
        <div style={{ width: 26, height: 26, border: '3px solid rgba(0,122,255,0.3)', borderTopColor: '#0a84ff', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
        <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>Signing in…</span>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
    </div>
  );
}

// pseudo-QR (decorative, deterministic)
function QR({ size = 116 }) {
  const n = 21, cell = size / n;
  const finder = (r, c) => (r < 7 && c < 7) || (r < 7 && c >= n - 7) || (r >= n - 7 && c < 7);
  const cells = [];
  for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
    let on;
    if (finder(r, c)) {
      const lr = r >= n - 7 ? r - (n - 7) : r, lc = c >= n - 7 ? c - (n - 7) : c;
      on = lr === 0 || lr === 6 || lc === 0 || lc === 6 || (lr >= 2 && lr <= 4 && lc >= 2 && lc <= 4);
    } else { on = ((r * 7 + c * 13 + r * c) % 3) === 0; }
    if (on) cells.push(<rect key={r + '-' + c} x={c * cell} y={r * cell} width={cell + 0.5} height={cell + 0.5} fill={XC.black} />);
  }
  return <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ background: '#fff' }}>{cells}</svg>;
}

function Field({ k, v, vColor }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '7px 0', borderBottom: `1px solid ${XC.grayLight}` }}>
      <span style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: XC.grayDark, flex: 'none' }}>{k}</span>
      <span style={{ fontSize: 12, color: vColor || XC.black, fontWeight: 600, textAlign: 'right', wordBreak: 'break-all' }}>{v}</span>
    </div>
  );
}

function TxRow({ label, time }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: `1px solid ${XC.grayLight}` }}>
      <span style={{ width: 18, height: 18, borderRadius: '50%', background: XC.green, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, flex: 'none' }}>✓</span>
      <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', color: XC.black, flex: 1 }}>{label}</span>
      <span style={{ fontSize: 10, color: XC.grayDark }}>{time}</span>
    </div>
  );
}

// ── flow model ───────────────────────────────────────────────────────────────
const SCREENS = ['welcome', 'create', 'apple', 'funding', 'confirmed'];
const STEP_LABELS = ['Welcome', 'Sign in with Apple', 'Authorize', 'Activate & back up', 'On-chain'];
const NOTES = {
  welcome:   { k: 'Step 01 · Welcome', t: 'Keys are born on your device.', b: 'The app finds no stored identity. There is nothing here yet, and when your wallet is created, its keys are generated on this phone and stay on it.' },
  create:    { k: 'Step 02 · Bootstrap', t: 'Passwordless from the start.', b: 'Sign in with Apple bootstraps recovery. Your wallet keys are generated on-device and held in device-only Keychain; the Secure Enclave proves the device and wraps the backup key.' },
  apple:     { k: 'Step 03 · Authorize', t: 'You authorize. Hardware proves it.', b: 'Face ID unlocks the keychain and Apple confirms your account. From here on, every signature happens on this device, behind your biometric, nothing signs without it.' },
  funding:   { k: 'Step 04 · Activate & back up', t: 'Generated on device, backed up as sciphrtext.', b: 'XRPL accounts need a small reserve to exist. In parallel, your wallet keys are generated on the device; the master key is sealed into an AES-256-GCM backup envelope (wrapped to your Enclave, iCloud, and recovery code) and pinned to IPFS. SciPHR never sees a key.' },
  confirmed: { k: 'Step 05 · On-chain', t: 'One identity, signed on your device.', b: 'PAYMENT activates the account; SET REGULAR KEY and SIGNER LIST SET install your day-to-day key and recovery quorum; NFT MINT anchors the provenance pointer (sciphr:v5:<cid>#<sha256>) and DID SET publishes your identity. Self-custody, only your device can sign.' },
};
// funding/seal/mint stream
const FUND_LINES = [
  { t: '> Authenticated as Jarod Vyent', k: 'ok' },
  { t: '> Generating wallet on device (funding required)…', k: 'out' },
  { t: '> Wallet activation requires a small XRP deposit.', k: 'out' },
  { t: '> Send 1.61 XRP to activate rhVDMMzr8Xm5…', k: 'dim' },
  { t: '> Requesting testnet treasury funding…', k: 'out', fund: true },
  { t: '> Funding confirmed · 1.61 XRP', k: 'ok' },
  { t: '> Keys generated on device · Ed25519', k: 'out' },
  { t: '> Sealing master · AES-256-GCM under WBK', k: 'ok' },
  { t: '> Wrapping WBK · Enclave · iCloud · code', k: 'out' },
  { t: '> Pinning envelope · ipfs://QmXjr1iYoRb…', k: 'out' },
  { t: '> NFT URI · sciphr:v5:<cid>#<sha256>', k: 'amber' },
  { t: '> PAYMENT · SET REGULAR KEY · SIGNER LIST · NFT MINT · DID SET', k: 'out', mark: true },
  { t: '✓ identity online', k: 'done' },
];

function MintApp() {
  const [screen, setScreen] = React.useState('welcome');
  const [lines, setLines] = React.useState([]);
  const idx = SCREENS.indexOf(screen);

  React.useEffect(() => {
    if (screen !== 'apple') return;
    const t = setTimeout(() => setScreen('funding'), 2600);
    return () => clearTimeout(t);
  }, [screen]);

  React.useEffect(() => {
    if (screen !== 'funding') { setLines([]); return; }
    let i = 0; setLines([]);
    const id = setInterval(() => {
      i++; setLines(FUND_LINES.slice(0, i));
      if (i >= FUND_LINES.length) { clearInterval(id); setTimeout(() => setScreen('confirmed'), 1100); }
    }, 700);
    return () => clearInterval(id);
  }, [screen]);

  function restart() { setScreen('welcome'); setLines([]); }
  const fundReached = lines.some(l => l.fund);
  const note = NOTES[screen];

  const lineColor = (k) => k === 'ok' || k === 'done' ? XC.black : k === 'amber' ? XC.testnet : k === 'dim' ? XC.grayDark : XC.grayDark;

  return (
    <React.Fragment>
      {/* LEFT, synced info column */}
      <div>
        <div className="stepnote">
          <div className="sn-k">{note.k}</div>
          <div className="sn-t">{note.t}</div>
          <div className="sn-b">{note.b}</div>
        </div>
        <div className="step-rows">
          {STEP_LABELS.map((l, i) => (
            <div key={l} className={'step-row ' + (i === idx ? 'is-cur' : i < idx ? 'is-done' : '')}>
              <span className="sr-n">{String(i + 1).padStart(2, '0')}</span><span>{l}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 22, fontSize: 11, letterSpacing: '0.04em', lineHeight: 1.6, color: XC.grayDark }}>
          <span style={{ color: XC.testnet }}>›</span> A faithful mock of the xCIPHR flow. The pipeline shown is the
          real V5 model, your keys are generated and held on the device, your master key is backed up as sciphrtext
          only you can open, and SciPHR never holds a key that can sign or decrypt.
        </div>
      </div>

      {/* RIGHT, phone */}
      <div className="demo-phone">
        <div className="phone-scale">
          <IOSDevice width={392} height={840}>
            <div style={{ minHeight: '100%', position: 'relative' }}>

              {screen === 'welcome' && (
                <Screen title="xCIPHR" footer={<React.Fragment>
                  <RetroButton primary onClick={() => setScreen('create')}>INITIALIZE</RetroButton>
                  <RetroButton onClick={() => setScreen('create')}>EXPLORE WITHOUT IDENTITY</RetroButton>
                </React.Fragment>}>
                  <div style={{ display: 'flex', justifyContent: 'center', padding: '20px 0 16px' }}>
                    <img src="assets/sciphr-logo.png" alt="SciPHR" style={{ width: 44, height: 44, opacity: 0.55 }} />
                  </div>
                  <AppTerminal style={{ flex: 1, minHeight: 320 }}>
                    <div style={{ fontWeight: 700 }}>xCIPHR v1.0</div>
                    <div style={{ borderBottom: `1px solid ${XC.grayLight}`, margin: '8px 0 10px' }} />
                    <div style={{ color: XC.grayDark }}>Secure enclave: ENABLED</div>
                    <div style={{ color: XC.grayDark }}>Good evening! Happy Thorough Thursday!</div>
                    <div style={{ borderBottom: `1px solid ${XC.grayLight}`, margin: '10px 0' }} />
                    <div style={{ fontWeight: 700 }}>Welcome to xCIPHR</div>
                    <div>You hold the keys.</div>
                    <div style={{ fontWeight: 700, marginTop: 8 }}>&gt; No stored identity found</div>
                    <div style={{ color: XC.grayDark }}>&gt; Initialize new xCIPHR identity?</div>
                    <div>&gt; <Caret /></div>
                  </AppTerminal>
                </Screen>
              )}

              {screen === 'create' && (
                <Screen title="create" footer={<React.Fragment>
                  <RetroButton primary onClick={() => setScreen('apple')}>Sign in with Apple</RetroButton>
                  <RetroButton onClick={() => setScreen('welcome')}>Go Back</RetroButton>
                </React.Fragment>}>
                  <AppTerminal style={{ flex: 1, minHeight: 360, marginTop: 16 }}>
                    <div style={{ color: XC.grayDark }}>$ npx create-xciphr-identity</div>
                    <div style={{ fontWeight: 700 }}>&gt; Hardware security enabled</div>
                    <div style={{ fontWeight: 700 }}>How it works:</div>
                    <div style={{ color: XC.grayDark }}>• One tap to create or recover your wallet</div>
                    <div style={{ color: XC.grayDark }}>• Face ID secures everything</div>
                    <div style={{ color: XC.grayDark }}>• No passwords or seed phrases</div>
                    <div style={{ color: XC.grayDark }}>• Recovery works on any Apple device</div>
                    <div>&gt; <Caret /></div>
                  </AppTerminal>
                </Screen>
              )}

              {screen === 'apple' && (
                <React.Fragment>
                  <Screen title="create">
                    <AppTerminal style={{ flex: 1, minHeight: 360, marginTop: 16, opacity: 0.5 }}>
                      <div style={{ color: XC.grayDark }}>$ npx create-xciphr-identity</div>
                      <div style={{ fontWeight: 700 }}>&gt; Hardware security enabled</div>
                      <div style={{ color: XC.grayDark }}>• Face ID secures everything</div>
                      <div style={{ color: XC.grayDark }}>• No passwords or seed phrases</div>
                      <div style={{ marginTop: 6 }}>&gt; Initiating Apple Sign In…</div>
                      <div>&gt; <Caret /></div>
                    </AppTerminal>
                  </Screen>
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(40,40,40,0.55)' }} />
                  <div style={{ position: 'absolute', top: 70, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}><FaceID /></div>
                  <AppleSheet />
                </React.Fragment>
              )}

              {screen === 'funding' && (
                <Screen title="provisioning">
                  <AppTerminal style={{ marginTop: 14 }}>
                    {lines.map((l, i) => (
                      <div key={i} style={{ color: lineColor(l.k), fontWeight: l.k === 'ok' || l.k === 'done' ? 700 : 400 }}>{l.t}</div>
                    ))}
                    <div>&gt; <Caret /></div>
                  </AppTerminal>
                  {fundReached && (
                    <div style={{ marginTop: 14 }}>
                      <AppTerminal label="FUNDING REQUEST">
                        <div style={{ fontWeight: 700 }}>&gt; Activate identity funding:</div>
                        <div style={{ border: `2px solid ${XC.black}`, borderRightWidth: 3, borderBottomWidth: 3, padding: 12, marginTop: 10 }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                            <span style={{ fontWeight: 700 }}>[1] rhVDMM…SyMUZ7</span>
                            <span style={{ color: XC.testnet, fontWeight: 700, fontSize: 11, letterSpacing: '0.12em' }}>REQUESTING</span>
                          </div>
                          <div style={{ color: XC.grayDark, fontSize: 11, marginTop: 6 }}>XRP: 0.0000 / 1.61</div>
                          <div style={{ color: XC.grayDark, fontSize: 11 }}>Reserve 1 + slots 3 × 0.2 + buffer 0.01</div>
                          <div style={{ display: 'flex', justifyContent: 'center', margin: '14px 0 10px' }}><QR /></div>
                          <div style={{ textAlign: 'center', border: `1px solid ${XC.testnet}`, background: 'rgba(255,184,0,0.12)', color: XC.testnet, fontWeight: 700, fontSize: 11, letterSpacing: '0.18em', padding: '8px' }}>PROCESSING</div>
                        </div>
                      </AppTerminal>
                    </div>
                  )}
                </Screen>
              )}

              {screen === 'confirmed' && (
                <Screen title="xCIPHR" footer={<RetroButton primary onClick={restart}>↺ Run it again</RetroButton>}>
                  <div style={{ display: 'flex', justifyContent: 'center', padding: '18px 0 12px' }}>
                    <img src="assets/sciphr-logo.png" alt="SciPHR" style={{ width: 40, height: 40, opacity: 0.55 }} />
                  </div>
                  <AppTerminal label="XRPL · CONFIRMED">
                    <div style={{ fontWeight: 700, color: XC.green }}>✓ xCIPHR minted on TESTNET</div>
                    <div style={{ borderBottom: `1px solid ${XC.grayLight}`, margin: '10px 0' }} />
                    <TxRow label="NFT MINT" time="11:03:22" />
                    <TxRow label="DID SET" time="11:03:21" />
                    <TxRow label="SIGNER LIST SET" time="11:03:20" />
                    <TxRow label="SET REGULAR KEY" time="11:03:19" />
                    <TxRow label="PAYMENT · 1.61 XRP" time="11:03:10" />
                  </AppTerminal>
                  <div style={{ marginTop: 12 }}>
                    <AppTerminal>
                      <Field k="Address" v="rhVDMM…SyMUZ7" />
                      <Field k="DID" v="did:xrpl:testnet:rhVDMM…" />
                      <Field k="NFT URI" v="sciphr:v5:Qm…#sha256" vColor={XC.testnet} />
                      <Field k="Keys" v="Ed25519 · on-device" />
                      <Field k="Custody" v="self · non-custodial" />
                    </AppTerminal>
                    <div style={{ fontFamily: MONO, fontSize: 12, color: XC.black, fontWeight: 700, marginTop: 12 }}>You hold the keys.</div>
                    <div style={{ fontFamily: MONO, fontSize: 12, color: XC.grayDark }}>&gt; identity online <Caret /></div>
                  </div>
                </Screen>
              )}

            </div>
          </IOSDevice>
        </div>

        <div className="demo-ctrls">
          {SCREENS.map((s, i) => <span key={s} className={'demo-dot ' + (i <= idx ? 'on' : '')} />)}
          <button className="demo-restart" onClick={restart}>↺ Restart</button>
        </div>
      </div>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('demo-root')).render(<MintApp />);
