/* Sentinel — Review console. The product's centre of gravity.
   Three layouts (split | document | card-stack) over one shared ChangeDetail.
   Role-aware: Head decides non-high; CEO decides high; RM is read-only. */

/* Who the change is routed to for decision. */
function assignedRole(ch) { return ch.risk === "high" ? "ceo" : "head"; }
/* Head decides low/medium only. CEO approves high AND can review/override
   anything the Head has already done. RM is always read-only. */
function canDecide(role, ch) {
  if (ch.auto) return false;
  if (role === "head") return ch.risk !== "high";
  if (role === "ceo") return true;
  return false;
}
const CHANGE_TYPE = {
  edit:     { label: "Edit",         icon: "pencil",      tone: "var(--status-info)" },
  deletion: { label: "Deletion",     icon: "scissors",    tone: "var(--status-danger)" },
  addition: { label: "Addition",     icon: "plus-circle", tone: "var(--status-warning)" },
  missing:  { label: "Missing clause", icon: "file-x",    tone: "var(--status-danger)" },
};

/* Recommendation text from the change. */
function recoText(ch) {
  if (ch.auto) return "Auto-accepted — cosmetic, within the allow-list.";
  if (ch.changeType === "deletion" || ch.changeType === "missing") return "Re-insert our standard wording.";
  if (ch.risk === "low") return "Accept with the minor counter shown.";
  return "Counter with the wording below — holds our position.";
}

/* ── Shared decision detail ─────────────────────────────────────────────*/
function ChangeDetail({ contract, ch, decision, role, onDecide, embedded }) {
  const ctx = React.useContext(SentinelCtx);
  const [redMode, setRedMode] = React.useState(ctx.redline === "side" ? "side" : "inline");
  React.useEffect(() => { setRedMode(ctx.redline === "side" ? "side" : "inline"); }, [ctx.redline]);
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(ch.counter);
  const [showProv, setShowProv] = React.useState(ctx.aiPanel === "full");
  React.useEffect(() => { setShowProv(ctx.aiPanel === "full"); setEditing(false); setDraft(ch.counter); }, [ch.id, contract.id, ctx.aiPanel]);

  const r = RISK[ch.risk];
  const ct = CHANGE_TYPE[ch.changeType];
  const decided = decision && decision.action;
  const mine = canDecide(role, ch);
  const assigned = assignedRole(ch);
  const isOverride = role === "ceo" && assigned === "head"; // CEO acting on a Head-tier item
  const isHigh = ch.risk === "high";

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ flex: 1, overflowY: embedded ? "visible" : "auto", padding: embedded ? 0 : "22px 26px" }}>
        {/* Heading */}
        <div style={{ display: "flex", alignItems: "flex-start", gap: 12, marginBottom: 14 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 5 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, color: "var(--content-base)", background: "var(--bg-sunken)", border: "1px solid var(--border-base)", borderRadius: "var(--radius-sm)", padding: "2px 7px" }} title="Clause number in our standard template"><Icon name="file-text" size={12} style={{ color: "var(--content-muted)" }} />Std. clause {ch.clauseRef}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: ct.tone }}>
                <Icon name={ct.icon} size={13} />{ct.label}</span>
              {CLAUSES[ch.clause].protected && (
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11.5, fontWeight: 600, color: "var(--content-muted)" }}>
                  <Icon name="lock" size={12} />Protected</span>
              )}
            </div>
            <div style={{ fontSize: 19, fontWeight: 600, color: "var(--content-strong)", letterSpacing: "-0.01em", lineHeight: 1.25 }}>{CLAUSES[ch.clause].title}</div>
          </div>
          <RiskBadge risk={ch.risk} style={ctx.riskStyle} />
        </div>

        {/* Approval / visibility banner (routing & permissions) */}
        {!ch.auto && isHigh && (
          <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 14px", marginBottom: 16, borderRadius: "var(--radius-lg)",
            background: role === "ceo" ? "var(--status-danger-bg)" : "var(--bg-sunken)",
            border: role === "ceo" ? "1px solid var(--destructive-200)" : "1px solid var(--border-base)" }}>
            <Icon name={role === "ceo" ? "shield-alert" : "lock"} size={17} style={{ color: role === "ceo" ? "var(--status-danger)" : "var(--content-muted)", flex: "none" }} />
            <div style={{ flex: 1, fontSize: 13, lineHeight: 1.45 }}>
              {role === "ceo" ? <span style={{ color: "var(--content-strong)" }}><strong>Your approval required.</strong> High-risk items are decided only by the CEO.</span>
                : role === "head" ? <span style={{ color: "var(--content-base)" }}><strong style={{ color: "var(--content-strong)" }}>Awaiting CEO approval.</strong> High-risk — visible to you for context, but only the CEO can decide it.</span>
                : <span style={{ color: "var(--content-base)" }}>High-risk — escalated to the CEO for approval.</span>}
            </div>
          </div>
        )}
        {!ch.auto && !isHigh && isOverride && (
          <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 14px", marginBottom: 16, borderRadius: "var(--radius-lg)", background: "var(--ec-status-info-bg)", border: "1px solid var(--accent-100)" }}>
            <Icon name="eye" size={16} style={{ color: "var(--status-info)", flex: "none" }} />
            <div style={{ flex: 1, fontSize: 13, color: "var(--content-base)", lineHeight: 1.45 }}>
              <strong style={{ color: "var(--content-strong)" }}>{RISK[ch.risk].label} — Head of SP Contracting's call.</strong> You can review and override it as CEO.</div>
          </div>
        )}
        {/* AI co-pilot recommendation banner */}
        {!ch.auto && (
          <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 15px", marginBottom: 16,
            background: "var(--green-50)", border: "1px solid var(--green-100)", borderRadius: "var(--radius-lg)" }}>
            <span style={{ flex: "none", width: 30, height: 30, borderRadius: "var(--radius-md)", background: "var(--bg-surface)", color: "var(--green-700)",
              display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "var(--elev-1)" }}><Icon name="sparkles" size={16} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--green-700)", marginBottom: 1 }}>Sentinel recommends</div>
              <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--content-strong)" }}>{recoText(ch)}</div>
            </div>
            {ctx.aiPanel !== "minimal" ? <div style={{ width: 150, flex: "none" }}><Confidence value={ch.confidence} compact /></div>
              : <span className="text-mono" style={{ fontWeight: 600, color: ch.confidence >= 80 ? "var(--status-success)" : "var(--status-warning)" }}>{ch.confidence}%</span>}
          </div>
        )}

        {/* Plain-language summary */}
        <div style={{ marginBottom: 8 }}>
          <Label style={{ marginBottom: 6, display: "block" }}>What changed</Label>
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6, color: "var(--content-base)" }}>{ch.summary}</p>
        </div>
        <div style={{ display: "flex", gap: 9, padding: "11px 13px", marginBottom: 18, background: "var(--bg-sunken)", borderRadius: "var(--radius-md)" }}>
          <Icon name="target" size={15} style={{ color: "var(--content-muted)", flex: "none", marginTop: 2 }} />
          <div><span style={{ fontSize: 13, fontWeight: 600, color: "var(--content-strong)" }}>Impact on our position. </span>
            <span style={{ fontSize: 13.5, color: "var(--content-base)", lineHeight: 1.55 }}>{ch.delta}</span></div>
        </div>

        {/* Redline */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
          <Label>Deviation from our standard</Label>
          <div style={{ display: "inline-flex", background: "var(--bg-sunken)", borderRadius: "var(--radius-full)", padding: 3, gap: 2 }}>
            {[["inline", "Inline redline", "file-diff"], ["side", "Side-by-side", "columns-2"]].map(([m, lbl, ic]) => (
              <button key={m} onClick={() => setRedMode(m)} style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 11px", borderRadius: "var(--radius-full)",
                border: "none", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600,
                background: redMode === m ? "var(--bg-surface)" : "transparent", color: redMode === m ? "var(--content-strong)" : "var(--content-muted)",
                boxShadow: redMode === m ? "var(--elev-1)" : "none" }}><Icon name={ic} size={13} />{lbl}</button>
            ))}
          </div>
        </div>
        <div style={{ marginBottom: 18 }}>
          <RedlineDiff standard={ch.standard} provider={ch.provider} mode={redMode} />
          <div style={{ display: "flex", gap: 16, marginTop: 8, fontSize: 12, color: "var(--content-muted)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 2, background: "var(--status-danger-bg)", border: "1px solid var(--status-danger)" }} /> Our standard (removed by provider)</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 2, background: "var(--ec-status-success-bg)", border: "1px solid var(--status-success)" }} /> Provider's wording (added)</span>
          </div>
        </div>

        {/* Proposed counter-redline */}
        {!ch.auto && (
          <div style={{ marginBottom: 18 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
              <Label style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <Icon name="sparkles" size={13} style={{ color: "var(--green-700)" }} />
                {ch.changeType === "deletion" || ch.changeType === "missing" ? "Proposed re-insertion" : "Proposed counter-redline"}</Label>
              {!decided && mine && !editing && <Button variant="link" size="sm" leadingIcon="pencil" onClick={() => setEditing(true)} style={{ padding: "2px 4px" }}>Edit wording</Button>}
            </div>
            {editing ? (
              <div>
                <textarea value={draft} onChange={(e) => setDraft(e.target.value)} rows={5} style={{ width: "100%", boxSizing: "border-box",
                  fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.6, padding: "12px 14px", borderRadius: "var(--radius-md)",
                  border: "1px solid var(--ec-primary)", outline: "2px solid var(--ec-ring)", outlineOffset: 1, color: "var(--content-base)", resize: "vertical" }} />
                <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                  <Button size="sm" leadingIcon="check" onClick={() => { onDecide(ch, "edit", draft); setEditing(false); }}>Save & accept edited</Button>
                  <Button size="sm" variant="secondary" onClick={() => { setEditing(false); setDraft(ch.counter); }}>Cancel</Button>
                </div>
              </div>
            ) : (
              <div style={{ background: "var(--bg-surface)", border: "1px solid var(--green-200)", borderLeft: "3px solid var(--ec-primary)",
                borderRadius: "var(--radius-md)", padding: "13px 15px", fontSize: 13.5, lineHeight: 1.65, color: "var(--content-base)" }}>
                {decision && decision.action === "edit" ? decision.finalText : ch.counter}
                <div style={{ marginTop: 8, fontSize: 12, color: "var(--content-faint)", fontStyle: "italic", display: "flex", alignItems: "center", gap: 5 }}>
                  <Icon name="shield" size={12} /> Drafted to protect Eden Care while reading as neutral, market-standard language.</div>
              </div>
            )}
          </div>
        )}

        {/* Provenance + precedent (AI panel treatment) */}
        {!ch.auto && ctx.aiPanel !== "minimal" && (
          <div style={{ background: "var(--bg-page)", border: "1px solid var(--border-base)", borderRadius: "var(--radius-lg)", padding: 16, marginBottom: 16 }}>
            <button onClick={() => setShowProv((s) => !s)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", background: "none", border: "none", cursor: "pointer", padding: 0, fontFamily: "var(--font-body)" }}>
              <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 24, height: 24, borderRadius: "var(--radius-md)", background: "var(--green-50)", color: "var(--green-700)" }}><Icon name="route" size={14} /></span>
              <span style={{ fontSize: 14, fontWeight: 600, color: "var(--content-strong)" }}>How Sentinel assessed this</span>
              <Icon name={showProv ? "chevron-up" : "chevron-down"} size={16} style={{ marginLeft: "auto", color: "var(--content-muted)" }} />
            </button>
            {showProv && <div style={{ marginTop: 8 }}><Provenance checks={ch.checks} /></div>}
          </div>
        )}

        {/* Precedent */}
        {!ch.auto && (
          <div style={{ marginBottom: 4 }}>
            <Label style={{ marginBottom: 6, display: "block" }}>Precedent from the tracker</Label>
            {ch.precedent ? (
              <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", background: "var(--bg-surface)", border: "1px solid var(--border-base)", borderRadius: "var(--radius-md)" }}>
                <span style={{ flex: "none", color: ch.precedent.accepted ? "var(--status-success)" : "var(--status-warning)" }}>
                  <Icon name={ch.precedent.accepted ? "history" : "git-branch"} size={16} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: "var(--content-strong)", fontWeight: 500 }}>{ch.precedent.outcome}</div>
                  <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{ch.precedent.provider} · Round {ch.precedent.round}</div>
                </div>
                <StatusBadge tone={ch.precedent.accepted ? "success" : "warning"}>{ch.precedent.accepted ? "Held" : "Compromised"}</StatusBadge>
              </div>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "11px 13px", background: "var(--bg-sunken)", borderRadius: "var(--radius-md)", fontSize: 13, color: "var(--content-muted)" }}>
                <Icon name="search-x" size={15} /> No prior precedent for this clause — first time a provider has raised it.</div>
            )}
          </div>
        )}
        {ch.auto && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 15px", background: "var(--ec-status-neutral-bg)", borderRadius: "var(--radius-lg)", marginTop: 4 }}>
            <Icon name="check-circle-2" size={17} style={{ color: "var(--content-muted)" }} />
            <div style={{ fontSize: 13.5, color: "var(--content-base)" }}>Auto-accepted and logged. Visible and reversible in the audit trail — no human decision required.</div>
          </div>
        )}
      </div>

      {/* Decision footer */}
      {!ch.auto && (
        <div style={{ flex: "none", borderTop: "1px solid var(--border-base)", background: "var(--bg-surface)", padding: "14px 26px" }}>
          {decided ? (
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span style={{ flex: "none", width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff",
                background: decision.action === "reject" ? "var(--status-danger)" : "var(--status-success)" }}>
                <Icon name={decision.action === "reject" ? "x" : "check"} size={15} strokeWidth={3} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: "var(--content-strong)" }}>
                  {isHigh ? (decision.action === "reject" ? "Rejected by CEO" : "Approved by CEO")
                    : decision.action === "accept" ? "Counter accepted" : decision.action === "edit" ? "Accepted with edit" : "Change rejected"}</div>
                <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>by {decision.by}{decision.when ? " · " + decision.when : " · just now"}</div>
              </div>
              {mine && <Button variant="secondary" size="sm" leadingIcon="pencil" onClick={() => setEditing(true)}>{isOverride ? "Override" : "Edit"}</Button>}
              {mine && <Button variant="secondary" size="sm" leadingIcon="undo-2" onClick={() => onDecide(ch, null)}>Undo</Button>}
              {!mine && <span style={{ fontSize: 12.5, color: "var(--content-faint)", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="lock" size={13} />Read-only</span>}
            </div>
          ) : mine ? (
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <Button variant="destructive" leadingIcon="x" onClick={() => onDecide(ch, "reject")}>Reject</Button>
              <div style={{ flex: 1 }} />
              <Button variant="secondary" leadingIcon="pencil" onClick={() => setEditing(true)}>Edit</Button>
              <Button variant="primary" leadingIcon={isHigh ? "shield-check" : "check"} onClick={() => onDecide(ch, "accept")}>{isHigh ? "Approve & accept" : "Accept counter"}</Button>
            </div>
          ) : (
            <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13.5, color: "var(--content-muted)" }}>
              <Icon name={role === "rm" ? "eye" : "lock"} size={15} />
              {role === "rm" ? "Read-only — reviewers decide each change; you'll receive the final documents."
                : isHigh ? "High-risk — awaiting the CEO's approval. You can review but not decide."
                : `Routed to ${RISK[ch.risk].routeLabel}.`}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { canDecide, CHANGE_TYPE, ChangeDetail });
