// Ship New App + New Test modals.
const { useState: useStateS } = React;
const { Pill: PillS } = window;
const { Icons: IconsS, DATA: DATAS } = window;
const { Modal: ModalS } = window;

// ---------- Ship New App modal ----------
function ShipNewAppModal({ open, onClose }) {
  const [path, setPath] = useStateS(null); // 'import' | 'new' | null
  const [step, setStep] = useStateS(1);
  const [name, setName] = useStateS("");
  const [desc, setDesc] = useStateS("");
  const [generator, setGenerator] = useStateS("Claude Code");

  const reset = () => { setPath(null); setStep(1); setName(""); setDesc(""); };
  const close = () => { reset(); onClose(); };

  const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "new-app";

  return (
    <ModalS open={open} onClose={close} width={780}
      eyebrow="Ship a new app"
      title={path === null ? <>How are you <em>starting?</em></> : path === "import" ? <>Import from <em>GitHub.</em></> : <>Start from <em>template.</em></>}>

      {/* PATH PICKER */}
      {path === null && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 4 }}>
          <button onClick={() => setPath("import")}
            style={{ textAlign: "left", padding: 18, border: "1px solid var(--tan-2)", borderRadius: 10, background: "var(--cream-3)", cursor: "pointer", fontFamily: "inherit" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <IconsS.Github/>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>Import existing from GitHub</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
              Pull in a repo you've already built. Stoda will scan it for skills, dependencies, and outbound calls and run the audit.
            </div>
          </button>
          <button onClick={() => setPath("new")}
            style={{ textAlign: "left", padding: 18, border: "1px solid var(--tan-2)", borderRadius: 10, background: "var(--cream-3)", cursor: "pointer", fontFamily: "inherit" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <IconsS.Plus/>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>Start a new app</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
              Stoda creates the GitHub repo, scaffolds it from <code style={{ fontSize: 11 }}>meridia/app-template v4.2.1</code>, and hands you a starter prompt for Claude / Cursor / Codex.
            </div>
          </button>
        </div>
      )}

      {/* IMPORT FLOW */}
      {path === "import" && (
        <div style={{ marginTop: 4 }}>
          <Field label="GitHub repo URL">
            <input className="input" placeholder="https://github.com/meridia/your-app" defaultValue="https://github.com/meridia/"/>
          </Field>
          <Field label="App name">
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Quote Lookup"/>
          </Field>
          <Field label="What does it do?">
            <textarea className="input" rows={3} value={desc} onChange={e => setDesc(e.target.value)}
              placeholder="One sentence. Used in the audit and on the fleet page."/>
          </Field>
          <div style={{ background: "var(--cream-3)", border: "1px solid var(--tan-2)", borderRadius: 8, padding: 12, fontSize: 12, color: "var(--muted)", lineHeight: 1.5, marginTop: 4 }}>
            On import, Stoda will: scan dependencies against the approved list, detect outbound calls, run the rule library, generate an audit score, and propose missing skills from the template.
          </div>
        </div>
      )}

      {/* NEW FLOW */}
      {path === "new" && step === 1 && (
        <div style={{ marginTop: 4 }}>
          <Field label="App name">
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Renewal Forecaster" autoFocus/>
            {name && <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 6, fontFamily: "var(--mono, ui-monospace)" }}>github.com/meridia/{slug}</div>}
          </Field>
          <Field label="What does it do?">
            <textarea className="input" rows={3} value={desc} onChange={e => setDesc(e.target.value)}
              placeholder="One or two sentences. Stoda uses this to seed the starter prompt and the audit description."/>
          </Field>
          <Field label="Code with">
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {["Claude Code", "Cursor", "Codex CLI", "v0", "Bolt"].map(g => (
                <button key={g} onClick={() => setGenerator(g)}
                  style={{
                    padding: "7px 12px", fontSize: 12, fontWeight: 500,
                    border: "1px solid " + (generator === g ? "var(--ink-2)" : "var(--tan-2)"),
                    background: generator === g ? "var(--ink-2)" : "var(--paper)",
                    color: generator === g ? "#fff" : "var(--muted)",
                    borderRadius: 7, cursor: "pointer", fontFamily: "inherit",
                  }}>{g}</button>
              ))}
            </div>
          </Field>
        </div>
      )}

      {path === "new" && step === 2 && (
        <div style={{ marginTop: 4 }}>
          <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 12 }}>
            Stoda created <span style={{ fontFamily: "var(--mono, ui-monospace)", color: "var(--ink)" }}>github.com/meridia/{slug}</span> from <code style={{ fontSize: 11 }}>meridia/app-template v4.2.1</code>. Paste this into {generator} to get started:
          </div>
          <pre style={{
            fontFamily: "var(--mono, ui-monospace)", fontSize: 11.5, lineHeight: 1.55,
            background: "var(--cream-3)", border: "1px solid var(--tan-2)", borderRadius: 6,
            padding: "12px 14px", margin: 0, color: "var(--ink)", whiteSpace: "pre-wrap",
            maxHeight: 360, overflow: "auto",
          }}>
{`You're working in github.com/meridia/${slug}, scaffolded from
meridia/app-template v4.2.1.

App: ${name || "(unnamed)"}
Purpose: ${desc || "(describe what it does)"}

The template gives you these skills out of the box:
  - customer-lookup    (Salesforce ↔ Hubspot via salesforce_id)
  - pii-redaction      (strip PII before LLM calls)
  - audit-log          (append-only S3 with 7y retention)
  - budget-guard       (per-app cost ceiling, 70% in first 30d)
  - staged-deploy      (operator tests gate prod cutover)
  - secret-rotation    (Vault refresh, no env-baked secrets)

Approved deps are pre-locked in package.json. Do NOT add new
deps without running \`stoda dep request\`.

Base prompt rules already loaded:
  - Stripe: apiVersion '2024-06-20', differentiate billing on
    customer.metadata.customer_type ('standard' | 'enterprise')
  - Postgres: read-only role for analytics, parameterize all
    queries, never DDL from app code
  - LLM: temperature=0 for extraction, Sonnet for reasoning,
    Haiku for classification

Outbound posture is default-deny. To call a new service, run
\`stoda outbound request <domain>\`.

Start by writing the smallest version that works. Then add a
workflow test for the happy path before shipping to staging.`}
          </pre>
          <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
            <button className="btn sm">Copy prompt</button>
            <button className="btn sm"><IconsS.Github/> Open repo</button>
            <button className="btn sm">Open in {generator}</button>
          </div>
        </div>
      )}

      {/* FOOTER */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 0 0", borderTop: "1px solid var(--tan-2)", marginTop: 18 }}>
        <button className="btn sm" onClick={path === null ? close : () => { if (path === "new" && step === 2) setStep(1); else setPath(null); }}>
          {path === null ? "Cancel" : "Back"}
        </button>
        <div style={{ display: "flex", gap: 8 }}>
          {path === "import" && <button className="btn accent sm" onClick={close}>Import & audit</button>}
          {path === "new" && step === 1 && <button className="btn accent sm" disabled={!name} onClick={() => setStep(2)} style={{ opacity: name ? 1 : 0.5 }}>Create repo</button>}
          {path === "new" && step === 2 && <button className="btn accent sm" onClick={close}>Done</button>}
        </div>
      </div>
    </ModalS>
  );
}

// ---------- New Test modal ----------
function NewTestModal({ open, onClose, app }) {
  const [mode, setMode] = useStateS(null); // 'describe' | 'record' | null
  const [name, setName] = useStateS("");
  const [desc, setDesc] = useStateS("");

  const close = () => { setMode(null); setName(""); setDesc(""); onClose(); };

  return (
    <ModalS open={open} onClose={close} width={720}
      eyebrow={`New test${app ? ` · ${app.name}` : ""}`}
      title={mode === null ? <>How do you want to <em>write it?</em></> : mode === "describe" ? <>Describe the <em>test.</em></> : <>Record your <em>workflow.</em></>}>

      {mode === null && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 4 }}>
          <button onClick={() => setMode("describe")}
            style={{ textAlign: "left", padding: 18, border: "1px solid var(--tan-2)", borderRadius: 10, background: "var(--cream-3)", cursor: "pointer", fontFamily: "inherit" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <IconsS.Doc/>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>Describe it in plain English</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
              Tell Stoda what should be true. We'll generate the assertion and wire it into the test runner.
            </div>
          </button>
          <button onClick={() => setMode("record")}
            style={{ textAlign: "left", padding: 18, border: "1px solid var(--tan-2)", borderRadius: 10, background: "var(--cream-3)", cursor: "pointer", fontFamily: "inherit" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <IconsS.Record/>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>Record your workflow</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
              Click through the app once. Stoda turns it into a click-through test that runs at every deploy.
            </div>
          </button>
        </div>
      )}

      {mode === "describe" && (
        <div style={{ marginTop: 4 }}>
          <Field label="Test name">
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. enterprise customers get net-30 terms" autoFocus/>
          </Field>
          <Field label="What should be true?">
            <textarea className="input" rows={5} value={desc} onChange={e => setDesc(e.target.value)}
              placeholder="When a quote is generated for a customer with metadata.customer_type='enterprise', the payment terms should be net-30. For 'standard', it should be due-on-receipt."/>
          </Field>
          <div style={{ background: "var(--cream-3)", border: "1px solid var(--tan-2)", borderRadius: 8, padding: 12, fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
            Stoda will draft an assertion, run it against the last 30 prod traces to check it passes today, then wire it into the test suite. Runs on every deploy.
          </div>
        </div>
      )}

      {mode === "record" && (
        <div style={{ marginTop: 4 }}>
          <div style={{ background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 10, padding: 24, textAlign: "center", marginBottom: 12 }}>
            <div style={{ width: 48, height: 48, borderRadius: 24, background: "var(--red-bg)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--red)", marginBottom: 12 }}>
              <IconsS.Record s={22}/>
            </div>
            <div style={{ fontSize: 14, fontWeight: 500, color: "var(--ink)", marginBottom: 4 }}>Ready to record</div>
            <div style={{ fontSize: 12, color: "var(--muted)", maxWidth: 380, margin: "0 auto", lineHeight: 1.5 }}>
              We'll open {app?.name || "your app"} in a new tab. Click through the workflow you want to test. When you're done, hit Stop and Stoda will turn it into a click-through test that runs at every deploy.
            </div>
          </div>
          <Field label="Test name">
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. happy path: standard customer · 5 seats · checkout"/>
          </Field>
        </div>
      )}

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 0 0", borderTop: "1px solid var(--tan-2)", marginTop: 18 }}>
        <button className="btn sm" onClick={mode === null ? close : () => setMode(null)}>
          {mode === null ? "Cancel" : "Back"}
        </button>
        <div style={{ display: "flex", gap: 8 }}>
          {mode === "describe" && <button className="btn accent sm" disabled={!name || !desc} onClick={close} style={{ opacity: (name && desc) ? 1 : 0.5 }}>Generate test</button>}
          {mode === "record" && <button className="btn accent sm" disabled={!name} onClick={close} style={{ opacity: name ? 1 : 0.5 }}><IconsS.Record/> Start recording</button>}
        </div>
      </div>
    </ModalS>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 11.5, color: "var(--muted)", marginBottom: 6, textTransform: "uppercase", letterSpacing: 0.4, fontWeight: 600 }}>{label}</div>
      {children}
    </div>
  );
}

// Inject input styles once.
if (typeof document !== "undefined" && !document.getElementById("__ship-test-input-css")) {
  const s = document.createElement("style");
  s.id = "__ship-test-input-css";
  s.textContent = `.input { width: 100%; font-family: inherit; font-size: 13px; padding: 9px 12px; background: var(--paper); color: var(--ink); border: 1px solid var(--tan-2); border-radius: 7px; outline: none; box-sizing: border-box; resize: vertical; } .input:focus { border-color: var(--ink-2); }`;
  document.head.appendChild(s);
}

window.ShipNewAppModal = ShipNewAppModal;
window.NewTestModal = NewTestModal;
