// Modals — signing approval, rotate key, new key, generic confirm

const SigningModal = ({ onClose, style = "drawer" }) => {
  const [stage, setStage] = useStateS("review"); // review → authenticate → broadcasting → done
  const [expanded, setExpanded] = useStateS(false);
  const W = style === "drawer" ? 620 : 560;
  const Container = ({ children }) => style === "drawer" ? (
    <div className="drawer">{children}</div>
  ) : (
    <div className="modal" style={{ width: W }}>{children}</div>
  );

  const headerIcon = (
    <div className="modal-icon" style={{ background: "var(--accent-soft)", color: "var(--accent-ink)" }}>
      <IFingerprint size={18}/>
    </div>
  );

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <Container>
        <div className="modal-hd">
          {headerIcon}
          <div style={{ flex: 1 }}>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>
              {stage === "review" && "Step 1 of 3 · Review"}
              {stage === "authenticate" && "Step 2 of 3 · Authenticate"}
              {stage === "broadcasting" && "Step 3 of 3 · Broadcasting"}
              {stage === "done" && "Confirmed"}
            </div>
            <div className="modal-title">
              {stage === "review" && "Sign transfer · 1.20 ETH"}
              {stage === "authenticate" && "Confirm with passkey"}
              {stage === "broadcasting" && "Broadcasting to Ethereum"}
              {stage === "done" && "Signed and broadcast"}
            </div>
            <div className="modal-desc">
              {stage === "review" && "Review the payload. Signing produces a signature; broadcast happens in the next step."}
              {stage === "authenticate" && "Touch ID or your security key is required to release the signature."}
              {stage === "broadcasting" && "Waiting for the first block confirmation."}
              {stage === "done" && "Receipt recorded in the audit log."}
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><IX size={14}/></button>
        </div>

        <div className="modal-body">
          {stage === "review" && (
            <div className="stack" style={{ gap: 14 }}>
              <div style={{ padding: 14, background: "var(--bg-sunken)", border: "1px solid var(--line)", borderRadius: 10 }}>
                <div className="stack" style={{ gap: 0 }}>
                  <KV k="From"><MonoId full="0x9a4c2b1eFa0987a2C5cD6f4E3D8bC9Ae21f">0x9a4c…e21f</MonoId></KV>
                  <KV k="To"><MonoId full="0xf2c3aB8e01d9a7b3F6c59E2d84a0C91aAa9a11">0xf2c3…9a11</MonoId></KV>
                  <KV k="Value"><span className="mono" style={{ fontSize: 13, fontWeight: 500 }}>1.20 ETH</span> <span style={{ fontSize: 12, color: "var(--ink-3)" }}>≈ $3,942.00</span></KV>
                  <KV k="Chain"><Chain chain="ETH"/></KV>
                  <KV k="Gas (est.)"><span className="mono" style={{ fontSize: 12.5 }}>0.00042 ETH</span> <span style={{ fontSize: 12, color: "var(--ink-3)" }}>· priority medium</span></KV>
                  <KV k="Nonce"><span className="mono" style={{ fontSize: 12.5 }}>#1,284</span></KV>
                </div>
              </div>

              <div style={{ padding: "12px 14px", background: "var(--ok-soft)", border: "1px solid color-mix(in oklch, var(--ok) 25%, var(--line))", borderRadius: 10, display: "flex", alignItems: "flex-start", gap: 10 }}>
                <ICheck size={14} style={{ color: "var(--ok)", marginTop: 2 }}/>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "oklch(from var(--ok) calc(l - 0.18) c h)" }}>Policy <span className="mono">payments_v3</span> passed</div>
                  <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 2 }}>
                    Within daily cap (8 / 250 ETH). Recipient on allowlist. Requires 1 approver — <b>you</b>.
                  </div>
                </div>
              </div>

              <button style={{
                padding: "10px 14px", background: "var(--panel)", border: "1px solid var(--line)",
                borderRadius: 10, display: "flex", alignItems: "center", gap: 8, textAlign: "left", width: "100%",
              }} onClick={() => setExpanded(v => !v)}>
                <IArrow size={12} style={{ transform: expanded ? "rotate(90deg)" : "rotate(0deg)", transition: "transform 160ms", color: "var(--ink-3)" }}/>
                <span style={{ fontSize: 12.5, color: "var(--ink-2)" }}>Raw payload (EIP-1559)</span>
                <span className="mono" style={{ marginLeft: "auto", fontSize: 11, color: "var(--ink-4)" }}>0x02f873…</span>
              </button>
              {expanded && (
                <div className="code" style={{ marginTop: -8 }}>
                  <div className="code-header"><span className="mono" style={{ fontSize: 11 }}>tx.json</span><span className="code-lang">EIP-1559</span></div>
                  <pre className="code-body" style={{ margin: 0, maxHeight: 200 }}>
                    <Highlight code={`{
  "to": "0xf2c3aB8e…9a11",
  "value": "0x10a741a462780000",
  "chainId": 1,
  "type": 2,
  "maxFeePerGas": "0x1dcd6500",
  "maxPriorityFeePerGas": "0x59682f00",
  "gas": "0x5208",
  "nonce": 1284,
  "data": "0x"
}`}/>
                  </pre>
                </div>
              )}
            </div>
          )}

          {stage === "authenticate" && (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 18, padding: "28px 20px" }}>
              <div style={{
                width: 88, height: 88, borderRadius: "50%",
                background: "var(--accent-soft)", color: "var(--accent-ink)",
                display: "grid", placeItems: "center",
                boxShadow: "0 0 0 0 var(--accent-soft)",
                animation: "pulse 1.6s ease-in-out infinite",
              }}>
                <IFingerprint size={40}/>
              </div>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16, letterSpacing: "-0.015em" }}>Touch the sensor to confirm</div>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>Lena's MacBook Pro · Touch ID</div>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <Btn variant="ghost" onClick={() => setStage("review")}>Cancel</Btn>
                <Btn variant="secondary" icon={<IKey size={12}/>}>Use security key</Btn>
              </div>
            </div>
          )}

          {stage === "broadcasting" && (
            <div className="stack" style={{ gap: 14, padding: "12px 0" }}>
              {[
                { t: "Signed", done: true, note: "sig 0x4f1a… produced" },
                { t: "Submitted to mempool", done: true, note: "0.4s" },
                { t: "Block confirmed", done: false, note: "waiting (12s avg)" },
                { t: "Webhook delivered", done: false, note: "signing.confirmed → alerts.policy" },
              ].map((s, i) => (
                <div key={i} className="row" style={{ gap: 12 }}>
                  <div style={{
                    width: 20, height: 20, borderRadius: "50%",
                    background: s.done ? "var(--ok-soft)" : "transparent",
                    color: s.done ? "var(--ok)" : "var(--ink-4)",
                    border: s.done ? "1px solid color-mix(in oklch, var(--ok) 30%, var(--line))" : "1.5px dashed var(--line-strong)",
                    display: "grid", placeItems: "center",
                  }}>
                    {s.done ? <ICheck size={11}/> : <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--warn)", animation: "pulse 1.3s ease-in-out infinite" }}/>}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{s.t}</div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{s.note}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="modal-foot">
          {stage === "review" && <>
            <Btn variant="danger-ghost" onClick={onClose} icon={<IX size={12}/>}>Reject</Btn>
            <div className="spacer"/>
            <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
            <Btn variant="primary" onClick={() => setStage("authenticate")} icon={<IFingerprint size={13}/>}>Sign</Btn>
          </>}
          {stage === "authenticate" && <>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Waiting for passkey…</span>
            <div className="spacer"/>
            <Btn variant="primary" onClick={() => setStage("broadcasting")}>Simulate pass</Btn>
          </>}
          {stage === "broadcasting" && <>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Do not close — webhook pending</span>
            <div className="spacer"/>
            <Btn variant="secondary" onClick={onClose}>Background it</Btn>
          </>}
        </div>
      </Container>
    </>
  );
};

const RotateModal = ({ onClose, pattern = "type-to-confirm" }) => {
  const [confirm, setConfirm] = useStateS("");
  const targetText = "rotate sk_live_a94f";
  const valid = confirm === targetText;
  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="modal">
        <div className="modal-hd">
          <div className="modal-icon" style={{ background: "var(--danger-soft)", color: "var(--danger)" }}><IWarn size={18}/></div>
          <div style={{ flex: 1 }}>
            <div className="modal-title">Rotate production API key?</div>
            <div className="modal-desc">The old secret stops working in <b className="mono">10 minutes</b>. Any deployment still using it will start failing with <span className="mono">401 invalid_key</span>.</div>
          </div>
          <button className="icon-btn" onClick={onClose}><IX size={14}/></button>
        </div>
        <div className="modal-body">
          <div className="stack" style={{ gap: 14 }}>
            <div style={{ padding: 14, background: "var(--bg-sunken)", border: "1px solid var(--line)", borderRadius: 10 }}>
              <div className="row" style={{ gap: 10, marginBottom: 8 }}>
                <IInfo size={13} style={{ color: "var(--ink-3)" }}/>
                <span style={{ fontSize: 12.5, fontWeight: 500 }}>What happens when you rotate</span>
              </div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.65 }}>
                <li>A new secret is revealed once — we'll copy it to your clipboard.</li>
                <li>Old secret enters a 10-minute overlap window, then is revoked.</li>
                <li>Event <span className="mono">key.rotated</span> is emitted to <span className="mono">alerts.security</span>.</li>
                <li>Reversible during the overlap by clicking <b>Undo</b>.</li>
              </ul>
            </div>

            {pattern === "type-to-confirm" && (
              <Field label={<span>Type <span className="mono">{targetText}</span> to confirm</span>}>
                <input className="input mono" placeholder={targetText} value={confirm} onChange={e => setConfirm(e.target.value)}/>
              </Field>
            )}
            {pattern === "passkey-step" && (
              <Banner kind="warn" title="Passkey step-up required">
                You'll be asked to touch your passkey before the rotation commits.
              </Banner>
            )}
            {pattern === "armed-commit" && (
              <Banner kind="warn" title="Two-click commit">
                Click <b>Arm</b>, then <b>Rotate now</b>. You'll have 5 seconds to undo with the toast at the bottom-right.
              </Banner>
            )}
          </div>
        </div>
        <div className="modal-foot">
          <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
          <div className="spacer"/>
          {pattern === "type-to-confirm" && (
            <Btn variant="danger" onClick={onClose} disabled={!valid}>Rotate key</Btn>
          )}
          {pattern === "passkey-step" && (
            <Btn variant="danger" onClick={onClose} icon={<IFingerprint size={13}/>}>Verify & rotate</Btn>
          )}
          {pattern === "armed-commit" && (
            <Btn variant="danger" onClick={onClose}>Arm</Btn>
          )}
        </div>
      </div>
    </>
  );
};

const NewKeyModal = ({ onClose }) => (
  <>
    <div className="scrim" onClick={onClose}/>
    <div className="modal">
      <div className="modal-hd">
        <div className="modal-icon" style={{ background: "var(--accent-soft)", color: "var(--accent-ink)" }}><IKey size={18}/></div>
        <div style={{ flex: 1 }}>
          <div className="modal-title">Create API key</div>
          <div className="modal-desc">Give it a label, pick its environment, and grant only the scopes it needs.</div>
        </div>
        <button className="icon-btn" onClick={onClose}><IX size={14}/></button>
      </div>
      <div className="modal-body">
        <div className="stack" style={{ gap: 14 }}>
          <Field label="Label" hint="Where this key will be used. Shown in audit logs."><input className="input" placeholder="e.g. Webhooks receiver"/></Field>
          <Field label="Environment">
            <Segmented value="prod" onChange={() => {}} options={[
              { value: "dev", label: "Dev" }, { value: "staging", label: "Staging" }, { value: "prod", label: "Production" },
            ]}/>
          </Field>
          <Field label="Scopes">
            <div className="stack" style={{ gap: 6 }}>
              {["wallets:write","signing:write","audit:read","webhooks:read","admin:write"].map(s => (
                <label key={s} className="row" style={{ padding: "6px 10px", background: "var(--bg-sunken)", border: "1px solid var(--line)", borderRadius: 6 }}>
                  <input type="checkbox" defaultChecked={s === "wallets:write" || s === "signing:write"}/>
                  <span className="mono" style={{ fontSize: 12 }}>{s}</span>
                </label>
              ))}
            </div>
          </Field>
        </div>
      </div>
      <div className="modal-foot">
        <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
        <div className="spacer"/>
        <Btn variant="primary" onClick={onClose}>Create key</Btn>
      </div>
    </div>
  </>
);

Object.assign(window, { SigningModal, RotateModal, NewKeyModal });
