/* Sentinel — RM upload + diff & omission scan flow (3 steps). */

function UploadFlow({ onDone, onOpenContract }) {
  const [step, setStep] = React.useState("upload"); // upload | scanning | result
  const [type, setType] = React.useState("Hospital Services Agreement");
  const [fileName, setFileName] = React.useState("");
  const [scanIdx, setScanIdx] = React.useState(0);

  const scanSteps = [
    { icon: "file-search", label: "Loading golden template", detail: type + " v4.2 — finalized standard" },
    { icon: "git-compare-arrows", label: "Clause-aware semantic diff", detail: "Matching provider edits to standard clauses" },
    { icon: "file-x", label: "Omission scan", detail: "Checking every standard clause is present" },
    { icon: "sparkles", label: "Hybrid classification", detail: "Rules layer + AI judgement per change" },
    { icon: "route", label: "Risk-based routing", detail: "Assigning each change to a reviewer tier" },
  ];

  React.useEffect(() => {
    if (step !== "scanning") return;
    if (scanIdx >= scanSteps.length) { const t = setTimeout(() => setStep("result"), 500); return () => clearTimeout(t); }
    const t = setTimeout(() => setScanIdx((i) => i + 1), 620);
    return () => clearTimeout(t);
  }, [step, scanIdx]);

  const demo = CONTRACTS[0]; // Nairobi West as the demonstrated result
  const counts = { high: 3, medhigh: 1, medlow: 1, low: 1, minor: 1 };

  if (step === "upload") {
    return (
      <div style={{ padding: 24, maxWidth: 720, margin: "0 auto" }}>
        <Card padding={28}>
          <div className="text-display-s" style={{ fontSize: 26, marginBottom: 6 }}>Upload a provider edit</div>
          <p style={{ margin: "0 0 22px", fontSize: 14.5, color: "var(--content-muted)", maxWidth: 520, lineHeight: 1.55 }}>
            Drop the provider's tracked-changes <span className="text-mono" style={{ fontSize: 13 }}>.docx</span>. Sentinel diffs it against our finalized standard, catches anything they've dropped, classifies every change and routes it — starting the 4-hour clock.</p>

          <Field label="Contract type">
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {["Hospital Services Agreement", "Data Sharing Agreement", "Data Processing Agreement", "Service Level Agreement", "Provider Network Agreement", "Pharmacy Services Agreement", "Laboratory Services Agreement", "Diagnostic Services Agreement", "Other"].map((t) => (
                <button key={t} onClick={() => setType(t)} style={{ padding: "8px 14px", borderRadius: "var(--radius-full)", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 500,
                  border: `1px solid ${type === t ? "var(--ec-primary)" : "var(--border-strong)"}`, background: type === t ? "var(--green-50)" : "var(--bg-surface)", color: type === t ? "var(--green-800)" : "var(--content-base)" }}>{t}</button>
              ))}
            </div>
          </Field>

          <div style={{ marginTop: 20 }}>
            <label style={{ display: "block", border: "1.5px dashed var(--border-strong)", borderRadius: "var(--radius-lg)", padding: "34px 24px", textAlign: "center", cursor: "pointer", background: fileName ? "var(--green-50)" : "var(--bg-page)", transition: "background var(--motion-base)" }}>
              <input type="file" accept=".docx" style={{ display: "none" }} onChange={(e) => setFileName(e.target.files[0] ? e.target.files[0].name : "nairobiwest_hsa_r1.docx")} />
              <span style={{ display: "inline-flex", width: 46, height: 46, borderRadius: "var(--radius-lg)", background: "var(--bg-surface)", color: "var(--green-700)", alignItems: "center", justifyContent: "center", marginBottom: 12, boxShadow: "var(--elev-1)" }}><Icon name={fileName ? "file-check-2" : "upload-cloud"} size={22} /></span>
              <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--content-strong)" }}>{fileName || "Drop .docx or click to browse"}</div>
              <div style={{ fontSize: 13, color: "var(--content-muted)", marginTop: 3 }}>{fileName ? "Ready to scan" : "Tracked-changes Word document, v1 supports .docx only"}</div>
            </label>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 22 }}>
            <Icon name="shield-check" size={15} style={{ color: "var(--content-muted)" }} />
            <span style={{ fontSize: 12.5, color: "var(--content-muted)", flex: 1 }}>Restricted to @edencaremedical.com / @ginja.ai · every action is logged to the audit trail.</span>
            <Button leadingIcon="scan-search" disabled={!fileName} onClick={() => { if (!fileName) setFileName("nairobiwest_hsa_r1.docx"); setScanIdx(0); setStep("scanning"); }}
              style={!fileName ? { opacity: 0.55, cursor: "not-allowed" } : {}}>Scan & classify</Button>
          </div>
        </Card>
      </div>
    );
  }

  if (step === "scanning") {
    return (
      <div style={{ padding: 24, maxWidth: 620, margin: "0 auto" }}>
        <Card padding={28}>
          <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 22 }}>
            <span style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", background: "var(--green-50)", color: "var(--green-700)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="loader" size={18} /></span>
            <div><div style={{ fontSize: 16, fontWeight: 600, color: "var(--content-strong)" }}>Analysing {fileName}</div>
              <div style={{ fontSize: 13, color: "var(--content-muted)" }}>{type} · this runs in minutes, not days</div></div>
          </div>
          {scanSteps.map((s, i) => {
            const state = i < scanIdx ? "done" : i === scanIdx ? "active" : "wait";
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "12px 0", borderTop: i ? "1px solid var(--border-subtle)" : "none", opacity: state === "wait" ? 0.45 : 1, transition: "opacity var(--motion-base)" }}>
                <span style={{ flex: "none", width: 30, height: 30, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center",
                  background: state === "done" ? "var(--status-success)" : state === "active" ? "var(--green-50)" : "var(--bg-sunken)",
                  color: state === "done" ? "#fff" : state === "active" ? "var(--green-700)" : "var(--content-faint)" }}>
                  <Icon name={state === "done" ? "check" : s.icon} size={15} strokeWidth={state === "done" ? 3 : 2} /></span>
                <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 600, color: "var(--content-strong)" }}>{s.label}</div>
                  <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{s.detail}</div></div>
                {state === "active" && <Icon name="loader-2" size={16} style={{ color: "var(--green-600)" }} />}
              </div>
            );
          })}
        </Card>
      </div>
    );
  }

  // result
  return (
    <div style={{ padding: 24, maxWidth: 760, margin: "0 auto" }}>
      <Card padding={0} style={{ overflow: "hidden" }}>
        <div style={{ padding: "22px 26px", background: "var(--green-50)", borderBottom: "1px solid var(--green-100)", display: "flex", alignItems: "center", gap: 13 }}>
          <span style={{ width: 40, height: 40, borderRadius: "50%", background: "var(--status-success)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="check" size={20} strokeWidth={3} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600, color: "var(--content-strong)" }}>Classified &amp; routed · {demo.id}</div>
            <div style={{ fontSize: 13, color: "var(--content-base)" }}>7 changes found — 1 auto-accepted, 6 routed to reviewers. SLA clock started.</div>
          </div>
          <SlaPill uploadedMs={Date.now() - 60000} />
        </div>
        <div style={{ padding: "20px 26px" }}>
          <Label style={{ display: "block", marginBottom: 10 }}>Risk breakdown</Label>
          <div style={{ display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
            {RISK_ORDER.map((rk) => counts[rk] ? (
              <div key={rk} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 13px", border: "1px solid var(--border-base)", borderRadius: "var(--radius-md)", background: "var(--bg-surface)" }}>
                <RiskBadge risk={rk} style="badge" size="sm" /><span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 600, color: "var(--content-strong)" }}>{counts[rk]}</span></div>
            ) : null)}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 8 }}>
            <div style={{ display: "flex", gap: 11, padding: "13px 15px", background: "var(--status-danger-bg)", borderRadius: "var(--radius-md)" }}>
              <Icon name="shield-alert" size={17} style={{ color: "var(--status-danger)", flex: "none", marginTop: 1 }} />
              <div><div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--content-strong)" }}>3 high-risk → CEO</div>
                <div style={{ fontSize: 12.5, color: "var(--content-base)" }}>EHIS access, payment window, liability cap deleted</div></div></div>
            <div style={{ display: "flex", gap: 11, padding: "13px 15px", background: "var(--bg-sunken)", borderRadius: "var(--radius-md)" }}>
              <Icon name="users" size={17} style={{ color: "var(--content-muted)", flex: "none", marginTop: 1 }} />
              <div><div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--content-strong)" }}>3 → Head of SP</div>
                <div style={{ fontSize: 12.5, color: "var(--content-base)" }}>Credit security, dispute process, force majeure</div></div></div>
          </div>
          <div style={{ display: "flex", gap: 9, padding: "11px 13px", background: "var(--ec-status-warning-bg)", borderRadius: "var(--radius-md)", marginTop: 4 }}>
            <Icon name="file-x" size={16} style={{ color: "var(--status-warning)", flex: "none", marginTop: 1 }} />
            <div style={{ fontSize: 13, color: "var(--content-base)" }}><strong style={{ color: "var(--content-strong)" }}>Omission caught:</strong> the provider deleted Clause 11.4 (liability cap) entirely — flagged high-risk with a proposed re-insertion.</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, padding: "16px 26px", borderTop: "1px solid var(--border-base)", background: "var(--bg-page)" }}>
          <Button variant="secondary" leadingIcon="folder-open" onClick={onDone}>Back to my contracts</Button>
          <div style={{ flex: 1 }} />
          <Button leadingIcon="arrow-right" onClick={() => onOpenContract(demo.id)}>Track in console</Button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { UploadFlow });
