/* Sentinel — Review console layouts (split | document | card-stack) + header. */

function decisionKey(contract, ch) { return contract.id + ":" + ch.id; }
function orderedChanges(contract) {
  return contract.changes.slice().sort((a, b) => {
    if (a.auto !== b.auto) return a.auto ? 1 : -1;
    return RISK[b.risk].sev - RISK[a.risk].sev;
  });
}
function roleActionable(contract, role) {
  return contract.changes.filter((ch) => canDecide(role, ch));
}

/* ── Header ──────────────────────────────────────────────────────────────*/
function ConsoleHeader({ contract, role, decisions, onBack, onGenerate }) {
  const prov = PROVIDERS[contract.provider];
  const actionable = roleActionable(contract, role);
  const done = actionable.filter((ch) => (decisions[decisionKey(contract, ch)] || {}).action).length;
  const roleDone = actionable.length > 0 && done === actionable.length;
  const subst = contract.changes.filter((c) => !c.auto);
  const allResolved = subst.length > 0 && subst.every((c) => (decisions[decisionKey(contract, c)] || {}).action);
  const pct = actionable.length ? Math.round(done / actionable.length * 100) : 100;
  return (
    <div style={{ flex: "none", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-base)", padding: "13px 26px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <button onClick={onBack} style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", border: "1px solid var(--border-base)", background: "var(--bg-surface)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--content-base)", flex: "none" }}><Icon name="arrow-left" size={17} /></button>
        <Avatar name={prov.name} size={36} tone={prov.tone} />
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <span style={{ fontSize: 16, fontWeight: 600, color: "var(--content-strong)" }}>{prov.name}</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--content-muted)" }}>{contract.id}</span>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{contract.type} · Round {contract.round} · uploaded by {contract.rm}</div>
        </div>
        <div style={{ flex: 1 }} />
        {role !== "rm" && actionable.length > 0 && (
          <div style={{ textAlign: "right" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
              <span style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{done} of {actionable.length} decided</span>
              <div style={{ width: 90, height: 6, borderRadius: 999, background: "var(--bg-sunken)", overflow: "hidden" }}>
                <div style={{ width: pct + "%", height: "100%", background: roleDone ? "var(--status-success)" : "var(--ec-primary)", borderRadius: 999, transition: "width var(--motion-base)" }} /></div>
            </div>
          </div>
        )}
        <SlaPill uploadedMs={contract.uploadedMs} />
        {role !== "rm" && (
          <Button variant={allResolved ? "primary" : "secondary"} leadingIcon="file-output" disabled={!allResolved}
            onClick={allResolved ? onGenerate : undefined}
            title={!allResolved ? (roleDone ? "Your items are done — awaiting CEO approval on the high-risk items" : "Decide every change first") : ""}
            style={!allResolved ? { opacity: 0.55, cursor: "not-allowed" } : {}}>Generate outputs</Button>
        )}
      </div>
    </div>
  );
}

/* ── Change list rail (split layout) ────────────────────────────────────*/
function ChangeRow({ contract, ch, role, decisions, selected, onSelect }) {
  const ctx = React.useContext(SentinelCtx);
  const d = decisions[decisionKey(contract, ch)];
  const mine = canDecide(role, ch);
  const ct = CHANGE_TYPE[ch.changeType];
  return (
    <button onClick={() => onSelect(ch.id)} style={{ display: "block", width: "100%", textAlign: "left", padding: "11px 13px", border: "none",
      borderBottom: "1px solid var(--border-subtle)", cursor: "pointer", background: selected ? "var(--green-50)" : "transparent",
      borderLeft: selected ? "3px solid var(--ec-primary)" : "3px solid transparent", fontFamily: "var(--font-body)" }}
      onMouseEnter={(e) => { if (!selected) e.currentTarget.style.background = "var(--bg-sunken)"; }}
      onMouseLeave={(e) => { if (!selected) e.currentTarget.style.background = "transparent"; }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 4 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--content-muted)" }}>{ch.clauseRef}</span>
        <Icon name={ct.icon} size={12} style={{ color: ct.tone }} />
        <span style={{ flex: 1 }} />
        {ch.auto ? <Icon name="check-circle-2" size={15} style={{ color: "var(--content-faint)" }} />
          : d && d.action ? <Icon name={d.action === "reject" ? "x-circle" : "check-circle-2"} size={15} style={{ color: d.action === "reject" ? "var(--status-danger)" : "var(--status-success)" }} />
          : <span style={{ width: 7, height: 7, borderRadius: "50%", background: `var(--status-${RISK[ch.risk].tone === "neutral" ? "info" : RISK[ch.risk].tone})` }} />}
      </div>
      <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--content-strong)", lineHeight: 1.3, marginBottom: 5 }}>{CLAUSES[ch.clause].title}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
        {ch.auto ? <span style={{ fontSize: 11.5, color: "var(--content-muted)" }}>Auto-accepted</span> : <RiskBadge risk={ch.risk} style={ctx.riskStyle === "badge" ? "badge" : ctx.riskStyle} size="sm" />}
        {!mine && !ch.auto && role !== "rm" && <Icon name="lock" size={11} style={{ color: "var(--content-faint)" }} title="Routed to another tier" />}
      </div>
    </button>
  );
}

function SplitConsole({ contract, role, decisions, selId, setSel, onDecide }) {
  const list = orderedChanges(contract);
  const ch = contract.changes.find((c) => c.id === selId) || list[0];
  const subst = list.filter((c) => !c.auto), auto = list.filter((c) => c.auto);
  return (
    <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
      <div style={{ width: 270, flex: "none", borderRight: "1px solid var(--border-base)", background: "var(--bg-surface)", overflowY: "auto" }}>
        <div className="text-label" style={{ padding: "13px 14px 7px" }}>Changes · {subst.length}</div>
        {subst.map((c) => <ChangeRow key={c.id} contract={contract} ch={c} role={role} decisions={decisions} selected={c.id === ch.id} onSelect={setSel} />)}
        {auto.length > 0 && <>
          <div className="text-label" style={{ padding: "14px 14px 7px", display: "flex", alignItems: "center", gap: 6 }}><Icon name="zap" size={12} /> Auto-accepted · {auto.length}</div>
          {auto.map((c) => <ChangeRow key={c.id} contract={contract} ch={c} role={role} decisions={decisions} selected={c.id === ch.id} onSelect={setSel} />)}
        </>}
      </div>
      <div style={{ flex: 1, minWidth: 0, background: "var(--bg-page)" }}>
        <ChangeDetail contract={contract} ch={ch} decision={decisions[decisionKey(contract, ch)]} role={role} onDecide={onDecide} />
      </div>
    </div>
  );
}

/* ── Document layout ────────────────────────────────────────────────────*/
function DocumentConsole({ contract, role, decisions, selId, setSel, onDecide }) {
  const docOrder = contract.changes.slice().sort((a, b) => parseFloat(a.clauseRef) - parseFloat(b.clauseRef));
  const ch = contract.changes.find((c) => c.id === selId) || orderedChanges(contract)[0];
  const ctx = React.useContext(SentinelCtx);
  return (
    <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
      {/* paper */}
      <div style={{ flex: 1, minWidth: 0, overflowY: "auto", padding: "28px 32px", background: "var(--bg-page)" }}>
        <div style={{ maxWidth: 640, margin: "0 auto", background: "var(--bg-surface)", border: "1px solid var(--border-base)", borderRadius: "var(--radius-lg)", boxShadow: "var(--elev-1)", padding: "40px 48px" }}>
          <div style={{ textAlign: "center", marginBottom: 28, paddingBottom: 20, borderBottom: "1px solid var(--border-base)" }}>
            <div className="text-display-s" style={{ fontSize: 24 }}>{contract.type}</div>
            <div style={{ fontSize: 13, color: "var(--content-muted)", marginTop: 4 }}>between Eden Care Medical Ltd and {PROVIDERS[contract.provider].name} · Round {contract.round}</div>
          </div>
          {docOrder.map((c) => {
            const d = decisions[decisionKey(contract, c)];
            const active = c.id === ch.id;
            const rt = RISK[c.risk];
            const col = c.auto ? "var(--neutral-400)" : `var(--status-${rt.tone === "neutral" ? "info" : rt.tone})`;
            return (
              <div key={c.id} id={"doc-" + c.id} onClick={() => setSel(c.id)} style={{ position: "relative", padding: "14px 16px", marginBottom: 10, cursor: "pointer",
                borderRadius: "var(--radius-md)", border: `1px solid ${active ? "var(--ec-primary)" : "var(--border-subtle)"}`,
                background: active ? "var(--green-50)" : "var(--bg-surface)", transition: "border-color var(--motion-fast)" }}>
                <span style={{ position: "absolute", left: -1, top: 14, bottom: 14, width: 3, borderRadius: 2, background: col }} />
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--content-muted)" }}>{c.clauseRef}</span>
                  <span style={{ fontSize: 14, fontWeight: 600, color: "var(--content-strong)" }}>{CLAUSES[c.clause].title}</span>
                  <span style={{ flex: 1 }} />
                  {c.auto ? <span style={{ fontSize: 11.5, color: "var(--content-muted)", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="zap" size={12} /> auto</span>
                    : d && d.action ? <Icon name={d.action === "reject" ? "x-circle" : "check-circle-2"} size={15} style={{ color: d.action === "reject" ? "var(--status-danger)" : "var(--status-success)" }} />
                    : <RiskBadge risk={c.risk} style="badge" size="sm" />}
                </div>
                <div style={{ fontSize: 12.5, lineHeight: 1.55, color: "var(--content-muted)", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
                  {c.changeType === "deletion" || c.changeType === "missing" ? "⚠ Provider removed this clause — " : ""}{c.summary}</div>
              </div>
            );
          })}
          <div style={{ textAlign: "center", fontSize: 12, color: "var(--content-faint)", marginTop: 18 }}>· · ·  18 further clauses unchanged from the standard template  · · ·</div>
        </div>
      </div>
      {/* detail drawer */}
      <div style={{ width: 480, flex: "none", borderLeft: "1px solid var(--border-base)", background: "var(--bg-surface)", display: "flex", flexDirection: "column", minHeight: 0 }}>
        <ChangeDetail contract={contract} ch={ch} decision={decisions[decisionKey(contract, ch)]} role={role} onDecide={onDecide} />
      </div>
    </div>
  );
}

/* ── Card-stack layout ──────────────────────────────────────────────────*/
function CardStackConsole({ contract, role, decisions, selId, setSel, onDecide }) {
  const list = orderedChanges(contract);
  const idx = Math.max(0, list.findIndex((c) => c.id === selId));
  const ch = list[idx] || list[0];
  const go = (d) => { const n = Math.min(list.length - 1, Math.max(0, idx + d)); setSel(list[n].id); };
  return (
    <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column", background: "var(--bg-page)" }}>
      <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 12, padding: "12px 26px", justifyContent: "center" }}>
        <Button variant="secondary" size="sm" leadingIcon="chevron-left" onClick={() => go(-1)} disabled={idx === 0} style={idx === 0 ? { opacity: 0.5 } : {}}>Prev</Button>
        <div style={{ display: "flex", gap: 5, alignItems: "center" }}>
          {list.map((c, i) => {
            const d = decisions[decisionKey(contract, c)];
            const done = c.auto || (d && d.action);
            return <button key={c.id} onClick={() => setSel(c.id)} title={CLAUSES[c.clause].title} style={{ width: i === idx ? 22 : 9, height: 9, borderRadius: 999, border: "none", cursor: "pointer",
              background: i === idx ? "var(--ec-primary)" : done ? "var(--green-300)" : "var(--border-strong)", transition: "all var(--motion-base)" }} />;
          })}
        </div>
        <Button variant="secondary" size="sm" trailingIcon="chevron-right" onClick={() => go(1)} disabled={idx === list.length - 1} style={idx === list.length - 1 ? { opacity: 0.5 } : {}}>Next</Button>
        <span style={{ fontSize: 12.5, color: "var(--content-muted)", marginLeft: 6 }}>Change {idx + 1} of {list.length}</span>
      </div>
      <div style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "8px 0 28px" }}>
        <div style={{ maxWidth: 720, margin: "0 auto", background: "var(--bg-surface)", border: "1px solid var(--border-base)", borderRadius: "var(--radius-xl)", boxShadow: "var(--elev-2)", display: "flex", flexDirection: "column", minHeight: "calc(100% - 16px)" }}>
          <ChangeDetail contract={contract} ch={ch} decision={decisions[decisionKey(contract, ch)]} role={role} onDecide={(c, a, t) => { onDecide(c, a, t); if (a && idx < list.length - 1) setTimeout(() => go(1), 280); }} />
        </div>
      </div>
    </div>
  );
}

function ReviewConsole({ contract, role, decisions, onBack, onDecide, onGenerate }) {
  const ctx = React.useContext(SentinelCtx);
  const [selId, setSel] = React.useState(orderedChanges(contract)[0] ? orderedChanges(contract)[0].id : null);
  React.useEffect(() => { const o = orderedChanges(contract)[0]; setSel(o ? o.id : null); }, [contract.id]);
  const Layout = ctx.consoleLayout === "document" ? DocumentConsole : ctx.consoleLayout === "cards" ? CardStackConsole : SplitConsole;
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0 }}>
      <ConsoleHeader contract={contract} role={role} decisions={decisions} onBack={onBack} onGenerate={onGenerate} />
      <Layout contract={contract} role={role} decisions={decisions} selId={selId} setSel={setSel} onDecide={onDecide} />
    </div>
  );
}

Object.assign(window, { ReviewConsole });
