/* Apps — workspace of LLM workflows within a tenant.
   List view, app detail (with tabs that scope down to per-app config),
   and a create-new-app modal. */

const APP_EXT = [
  { id: "encounter-summary", calls7d: 412, cost7d: 4.21, verifiedPct: 96, partialPct: 3, contraPct: 0.5,
    keys: 3, webhooks: 1, preset: "HIPAA", region: "US-East · BAA",
    chart: [42, 58, 67, 64, 78, 81, 92], description: "Drafts clinician-facing summaries of patient encounters at discharge." },
  { id: "discharge-bot", calls7d: 218, cost7d: 1.92, verifiedPct: 87, partialPct: 8, contraPct: 2,
    keys: 2, webhooks: 1, preset: "HIPAA", region: "US-East · BAA",
    chart: [24, 31, 28, 35, 32, 39, 42], description: "Generates medication-review notes during the discharge workflow." },
  { id: "intake-triage", calls7d: 187, cost7d: 1.18, verifiedPct: 61, partialPct: 18, contraPct: 11,
    keys: 1, webhooks: 0, preset: "HIPAA", region: "US-East · BAA",
    chart: [12, 18, 22, 19, 28, 31, 34], description: "Summarizes patient-reported symptoms for nurse-triage routing." },
];

const ENRICHED_APPS = SCENARIO.apps.map((a, i) => ({ ...a, ...APP_EXT[i] }));

const AppsList = ({ onOpenApp, onNewApp }) => {
  return (
    <>
      <header className="page-header">
        <div className="page-header__inner">
          <div className="page-header__eyebrow">Workspace</div>
          <h1>Apps</h1>
          <p className="page-header__sub">
            Each app is one LLM workflow you've wrapped with Attestia. Keys, webhooks, redaction rules, and limits are scoped per-app.
          </p>
        </div>
        <div className="page-actions">
          <Button variant="primary" size="sm" icon={window.Icon.plus({ size: 14 })} onClick={onNewApp}>New app</Button>
        </div>
      </header>

      <div className="apps-summary">
        <SummaryStat label="Active apps" value={ENRICHED_APPS.length} />
        <SummaryStat label="Calls (7 days)" value={ENRICHED_APPS.reduce((a, b) => a + b.calls7d, 0).toLocaleString()} />
        <SummaryStat label="Spend (7 days)" value={`$${ENRICHED_APPS.reduce((a, b) => a + b.cost7d, 0).toFixed(2)}`} />
        <SummaryStat label="Avg verified" value={`${Math.round(ENRICHED_APPS.reduce((a, b) => a + b.verifiedPct, 0) / ENRICHED_APPS.length)}%`} />
      </div>

      <div className="apps-grid">
        {ENRICHED_APPS.map((a) => (
          <button key={a.id} className="app-card" onClick={() => onOpenApp(a.id)}>
            <div className="app-card__head">
              <div className="app-card__avatar"><span className="mono">{a.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</span></div>
              <div className="app-card__name">
                <div className="app-card__title">{a.name}</div>
                <div className="app-card__purpose mono">purpose=&quot;{["discharge_summary", "med_review", "symptom_summary"][SCENARIO.apps.indexOf(SCENARIO.apps.find((x) => x.id === a.id))]}&quot;</div>
              </div>
              <Badge tone="sealed" icon={window.Icon.checkSimple({ size: 11 })}>Active</Badge>
            </div>
            <div className="app-card__desc">{a.description}</div>
            <div className="app-card__stats">
              <div className="app-card__stat">
                <div className="muted text-xs mono" style={{ letterSpacing: "0.08em" }}>CALLS 7D</div>
                <div className="app-card__big mono">{a.calls7d}</div>
                <Sparkline values={a.chart} color="var(--ink-1)" w={120} h={28} />
              </div>
              <div className="app-card__stat">
                <div className="muted text-xs mono" style={{ letterSpacing: "0.08em" }}>VERIFIED</div>
                <div className="app-card__big mono">{a.verifiedPct}%</div>
                <div className="app-bar" style={{ height: 6 }}>
                  <div style={{ width: `${a.verifiedPct}%`, background: "#2f6e47" }} />
                  <div style={{ width: `${a.partialPct}%`, background: "#9a6418" }} />
                  <div style={{ width: `${a.contraPct}%`, background: "#9b2c2c" }} />
                </div>
              </div>
            </div>
            <div className="app-card__foot">
              <span className="mono text-xs">{a.preset}</span>
              <span className="muted">·</span>
              <span className="text-xs muted">{a.keys} keys · {a.webhooks} webhook{a.webhooks === 1 ? "" : "s"}</span>
              <span className="spacer" />
              <span className="mono text-xs muted">${a.cost7d.toFixed(2)} / 7d</span>
            </div>
          </button>
        ))}

        <button className="app-card app-card--new" onClick={onNewApp}>
          <div className="app-card__new-icon">{window.Icon.plus({ size: 22 })}</div>
          <div className="app-card__new-title"><em>New app</em></div>
          <div className="text-sm muted" style={{ maxWidth: "30ch" }}>
            Wrap another LLM workflow with its own keys, webhooks, and redaction rules.
          </div>
        </button>
      </div>
    </>
  );
};

const SummaryStat = ({ label, value }) => (
  <div className="summary-stat">
    <div className="summary-stat__label">{label}</div>
    <div className="summary-stat__value mono">{value}</div>
  </div>
);

/* -------- App detail -------- */

const AppDetail = ({ appId, onBack, pushToast }) => {
  const app = ENRICHED_APPS.find((a) => a.id === appId) || ENRICHED_APPS[0];
  const purposes = { "encounter-summary": "discharge_summary", "discharge-bot": "med_review", "intake-triage": "symptom_summary" };
  const purposeTag = purposes[app.id];
  const [tab, setTab] = React.useState("overview");

  return (
    <>
      <div className="tr-header">
        <div className="tr-header__crumb">
          <button className="btn btn--ghost btn--sm" onClick={onBack} style={{ padding: "0 4px", height: 22, letterSpacing: 0, textTransform: "none", fontFamily: "var(--font-sans)" }}>
            {window.Icon.arrowLeft({ size: 12 })} Apps
          </button>
          <span style={{ color: "var(--ink-4)" }}>/</span>
          <span className="mono">{app.id}</span>
        </div>
        <div className="tr-header__title">
          <h1>{app.name}</h1>
          <div className="tr-header__verdict-col">
            <Badge tone="sealed" size="lg" icon={window.Icon.checkSimple({ size: 12 })}>Active</Badge>
          </div>
        </div>
        <div className="tr-header__meta">
          <div><span className="col-label">Purpose tag</span><span className="col-value mono">{purposeTag}</span></div>
          <div><span className="col-label">Compliance preset</span><span className="col-value">{app.preset}</span></div>
          <div><span className="col-label">Region</span><span className="col-value">{app.region}</span></div>
          <div><span className="col-label">Created</span><span className="col-value">Apr 15, 2026</span></div>
          <div className="col-actions">
            <Button variant="ghost" size="sm" icon={window.Icon.more({ size: 14 })} />
          </div>
        </div>
      </div>

      <Tabs items={[
        { value: "overview", label: "Overview" },
        { value: "api-keys", label: `API keys · ${app.keys}` },
        { value: "webhooks", label: `Webhooks · ${app.webhooks}` },
        { value: "redaction", label: "Redaction rules" },
        { value: "limits", label: "Limits" },
        { value: "activity", label: "Activity" },
      ]} value={tab} onChange={setTab} />

      {tab === "overview" && <AppOverview app={app} purposeTag={purposeTag} />}
      {tab === "api-keys" && <APIKeysTab pushToast={pushToast} />}
      {tab === "webhooks" && <WebhooksTab pushToast={pushToast} />}
      {tab === "redaction" && <RedactionTab />}
      {tab === "limits" && <AppLimitsTab app={app} pushToast={pushToast} />}
      {tab === "activity" && <AppActivityTab app={app} />}
    </>
  );
};

/* Overview tab */
const AppOverview = ({ app, purposeTag }) => (
  <div className="col gap-4">
    <div className="card card--padded">
      <div className="text-xs muted fw-600" style={{ letterSpacing: "0.1em", textTransform: "uppercase", fontFamily: "var(--font-mono)" }}>About</div>
      <h2 style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 28, fontWeight: 400, letterSpacing: "-0.02em", margin: "4px 0 8px", color: "var(--ink-1)" }}>{app.description}</h2>
      <div className="text-sm muted" style={{ maxWidth: "60ch" }}>
        Every call this app makes carries <span className="mono">purpose="{purposeTag}"</span>, which surfaces in traces, evidence packs, and the compliance dashboard. PHI redaction, retention, and signing are inherited from the {app.preset} preset.
      </div>
    </div>

    <div className="apps-summary">
      <SummaryStat label="Calls · 7 days" value={app.calls7d.toLocaleString()} />
      <SummaryStat label="Verified" value={`${app.verifiedPct}%`} />
      <SummaryStat label="Spend · 7 days" value={`$${app.cost7d.toFixed(2)}`} />
      <SummaryStat label="p50 latency" value={`${[212, 248, 195][ENRICHED_APPS.indexOf(app)]} ms`} />
    </div>

    <div className="dash-grid">
      <div className="card">
        <div className="card__header">
          <h3>Recent traces · this app</h3>
          <span className="meta">Last 6 calls</span>
          <div className="spacer" />
        </div>
        <table className="table">
          <thead><tr><th style={{ width: 80 }}>Time</th><th>Trace</th><th>Verdict</th><th style={{ width: 80, textAlign: "right" }}>Cost</th></tr></thead>
          <tbody>
            {SCENARIO.recentTraces.slice(0, 5).map((t, i) => (
              <tr key={i} className="clickable">
                <td className="mono text-sm muted">{t.time}</td>
                <td><HashChip value={t.id} short={t.id} /></td>
                <td><Verdict kind={t.verdict === "contradicted" ? "contra" : t.verdict} /></td>
                <td className="mono tabular text-sm" style={{ textAlign: "right" }}>{t.cost}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card card--padded">
        <div className="text-xs muted fw-600" style={{ letterSpacing: "0.1em", textTransform: "uppercase", fontFamily: "var(--font-mono)", marginBottom: 4 }}>Quick links</div>
        <h3 style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 22, fontWeight: 400, margin: "4px 0 16px", color: "var(--ink-1)" }}>This app's config.</h3>
        <div className="qlink-list">
          <QLink icon="key" label="API keys" sub={`${app.keys} active`} />
          <QLink icon="webhook" label="Webhooks" sub={`${app.webhooks} endpoint${app.webhooks === 1 ? "" : "s"}`} />
          <QLink icon="shield" label="Redaction rules" sub="HIPAA-18 + custom" />
          <QLink icon="activity" label="Rate limits" sub="100 req/s · 1M /month" />
          <QLink icon="fileCheck" label="Sample evidence pack" sub="Generated for this app only" />
        </div>
      </div>
    </div>
  </div>
);

const QLink = ({ icon, label, sub }) => (
  <button className="qlink">
    <div className="qlink__icon">{window.Icon[icon]({ size: 14 })}</div>
    <div className="qlink__body">
      <div className="fw-600 text-sm">{label}</div>
      <div className="text-xs muted">{sub}</div>
    </div>
    {window.Icon.chevronRight({ size: 13, props: { color: "var(--ink-4)" } })}
  </button>
);

const AppLimitsTab = ({ app, pushToast }) => (
  <div className="col gap-4">
    <Card title="Rate limits" padded>
      <div className="col gap-4">
        <Field label="Request rate" hint="Calls per second, sustained. Bursts up to 3× this allowed for 60 seconds.">
          <div className="row gap-2">
            <input className="input mono" defaultValue="100" style={{ width: 100 }} />
            <span className="muted">req/s</span>
          </div>
        </Field>
        <Field label="Monthly call budget" hint="Hard limit. Calls beyond this return 429. Set to 0 to disable.">
          <div className="row gap-2">
            <input className="input mono" defaultValue="1000000" style={{ width: 140 }} />
            <span className="muted">calls / month · current usage 8,412</span>
          </div>
        </Field>
        <Field label="Cost ceiling" hint="Soft limit. Triggers a webhook + email to compliance@meridian.health when exceeded.">
          <div className="row gap-2">
            <input className="input mono" defaultValue="500" style={{ width: 100 }} />
            <span className="muted">USD / month · current $42.18</span>
          </div>
        </Field>
        <div className="row" style={{ justifyContent: "flex-end" }}>
          <Button variant="primary" size="sm" onClick={() => pushToast({ kind: "success", title: "Limits updated", sub: "Effective immediately." })}>Save changes</Button>
        </div>
      </div>
    </Card>

    <Card title="Sandbox allocation" padded>
      <div className="col gap-3">
        <div className="row gap-2">
          <span className="muted">Verifier sandbox tier</span>
          <span className="spacer" />
          <Badge tone="info">Standard (3 judges · 2 vCPU)</Badge>
        </div>
        <div className="row gap-2">
          <span className="muted">Max concurrent verifications</span>
          <span className="spacer" />
          <span className="mono">12</span>
        </div>
        <div className="row gap-2">
          <span className="muted">Queue policy on overflow</span>
          <span className="spacer" />
          <span>Queue & retry (max 30s)</span>
        </div>
        <Button variant="link" size="sm" iconRight={window.Icon.external({ size: 11 })}>Upgrade sandbox tier</Button>
      </div>
    </Card>
  </div>
);

const AppActivityTab = ({ app }) => (
  <Card title="App activity" padded={false}>
    <div className="activity-list">
      <ActivityRowApp icon="key" title="API key created · Production" time="2 min ago" sub="Created by Mike Chen · scope read·write" />
      <ActivityRowApp icon="checkSimple" title="Webhook delivery succeeded" time="4 min ago" sub="evidence.signed · 200 OK · 22ms" />
      <ActivityRowApp icon="warning" title="Verification queued" time="38 min ago" sub="Sandbox unreachable · auto-retried 3 times · resolved" />
      <ActivityRowApp icon="fileText" title="Source added to registry" time="2 hours ago" sub="AHA/ACC HF Guidelines 2024 · authoritative for clinical claims" />
      <ActivityRowApp icon="settings" title="Redaction rule updated" time="1 day ago" sub="Custom MRN regex modified · changes audit-logged" />
      <ActivityRowApp icon="users" title="Compliance role granted" time="2 days ago" sub="Dr. Aisha Patel · read access to this app" />
    </div>
  </Card>
);

const ActivityRowApp = ({ icon, title, time, sub }) => (
  <div className="activity">
    <div className="activity__icon" style={{ color: "var(--ink-2)" }}>{window.Icon[icon]({ size: 13 })}</div>
    <div className="activity__body">
      <div className="activity__title">{title}</div>
      <div className="activity__time">{sub} · {time}</div>
    </div>
  </div>
);

/* -------- Create app modal -------- */

const CreateAppModal = ({ open, onClose, onCreated }) => {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({ name: "", purpose: "", preset: "hipaa" });
  const [generated, setGenerated] = React.useState(null);

  React.useEffect(() => { if (open) { setStep(1); setForm({ name: "", purpose: "", preset: "hipaa" }); setGenerated(null); } }, [open]);

  const create = () => {
    setGenerated({
      key: "af_live_NEW9k2qz9a8mn4lp2rt7yvWERrt22aaPP",
      appId: form.name.toLowerCase().replace(/\s+/g, "-"),
    });
    setStep(2);
  };

  return (
    <Modal open={open} onClose={onClose} wide
      title={step === 1 ? "Create a new app" : "App created"}
      sub={step === 1 ? "An app scopes API keys, webhooks, redaction, and limits to one LLM workflow." : "Copy your first API key now — this is the only time the full value is shown."}
      footer={step === 1 ? (
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" disabled={!form.name || !form.purpose} onClick={create} icon={window.Icon.plus({ size: 13 })}>
            Create app
          </Button>
        </>
      ) : (
        <Button variant="primary" onClick={() => { onCreated(generated.appId); onClose(); }}>
          Open {form.name}
        </Button>
      )}
    >
      {step === 1 && (
        <div className="col gap-4">
          <Field label="App name" required hint="Visible to your team and auditors.">
            <input className="input" placeholder="e.g. Radiology Report Drafter" value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })} autoFocus />
          </Field>
          <Field label="Purpose tag" required hint="A short, stable label that appears on every trace. Snake-case.">
            <input className="input mono" placeholder="radiology_report" value={form.purpose}
              onChange={(e) => setForm({ ...form, purpose: e.target.value.replace(/[^a-z0-9_]/gi, "_").toLowerCase() })} />
          </Field>
          <Field label="Compliance preset" hint="Inherited defaults for redaction, retention, and signing. Editable later.">
            <div className="radio-row">
              <RadioCard selected={form.preset === "hipaa"} title="HIPAA" sub="PHI redaction · 6yr retention · BAA region" onClick={() => setForm({ ...form, preset: "hipaa" })} />
              <RadioCard selected={form.preset === "fda"} title="FDA 21 CFR 11" sub="E-signatures · audit chain" onClick={() => setForm({ ...form, preset: "fda" })} />
              <RadioCard selected={form.preset === "none"} title="Custom" sub="Configure manually" onClick={() => setForm({ ...form, preset: "none" })} />
            </div>
          </Field>
          <div className="onb-note">
            <span>{window.Icon.shield({ size: 14 })}</span>
            <div className="text-sm">
              On create: a production-grade API key is generated and shown once. You'll then be able to install the SDK and start wrapping calls.
            </div>
          </div>
        </div>
      )}

      {step === 2 && generated && (
        <div className="col gap-4">
          <div className="share-success">
            <div className="share-success__icon">{window.Icon.checkSimple({ size: 22 })}</div>
            <div>
              <div className="share-success__title"><em style={{ fontStyle: "italic", fontFamily: "var(--font-display)", fontSize: 22 }}>{form.name} created.</em></div>
              <div className="share-success__sub">Purpose <span className="mono">{form.purpose}</span> · preset {form.preset.toUpperCase()} · ready to wrap calls.</div>
            </div>
          </div>
          <div className="reveal-key">
            <div className="reveal-key__label mono">Production API key · {form.name}</div>
            <div className="reveal-key__row">
              <span className="mono">{generated.key}</span>
              <Button variant="ghost" size="sm" icon={window.Icon.copy({ size: 12 })}>Copy</Button>
            </div>
          </div>
          <div className="onb-note" style={{ background: "var(--contra-soft)", borderColor: "rgba(155, 44, 44, 0.25)" }}>
            <span style={{ color: "var(--contra)" }}>{window.Icon.alertTriangle({ size: 14 })}</span>
            <div className="text-sm" style={{ color: "var(--ink-1)" }}>
              <strong>This is the only time we'll show the full key.</strong> Store it in your secret manager. You can rotate it from the app's API keys tab.
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
};

window.AppsList = AppsList;
window.AppDetail = AppDetail;
window.CreateAppModal = CreateAppModal;
