// detail.jsx — jurisdiction detail panel + override modal

const { Badge: D_Badge } = window.MC_HELPERS;
const { useState: dUseState } = React;

function DetailPanel({ rec, matter, onOpenOverride, onApprove }) {
  if (!rec) {
    return (
      <div className="card detail">
        <div className="detail-empty">
          Select a jurisdiction to inspect its assessment.
        </div>
      </div>
    );
  }

  const eff = rec.lawyerOutcome || rec.outcome;
  const showOverride = rec.overridden && rec.lawyerOutcome && rec.lawyerOutcome !== rec.toolOutcome;

  return (
    <div className="card detail">
      <div className="scroll">
        <div className="hd">
          <div>
            <div className="name">{rec.name}</div>
            <div className="iso">{rec.iso} · {matter.transactionType} · FY{matter.reportingYear}</div>
          </div>
        </div>

        {rec.approved && (
          <div className="approved-bar">✓ Partner-approved by {matter.partner}</div>
        )}

        {showOverride && (
          <div className="override-bar">
            <span>Lawyer override:</span>
            <span className="strike">AI said <b>{window.MC_HELPERS.OUTCOME_LABELS[rec.toolOutcome]}</b></span>
            <span>→ now <b>{window.MC_HELPERS.OUTCOME_LABELS[rec.lawyerOutcome]}</b></span>
          </div>
        )}

        <div className="outcome-row">
          <D_Badge outcome={eff} />
          <span style={{ fontFamily: "var(--font-ui)", fontSize: "var(--text-xs)", color: "var(--fg-muted)", alignSelf: "center" }}>
            Confidence: <b style={{ color: "var(--fg)" }}>{window.MC_HELPERS.CONF_LABELS[rec.confidence] || "—"}</b>
            {rec.borderline && <span> · Borderline</span>}
          </span>
        </div>

        {rec.rule && (
          <div className="section">
            <div className="section-label">Rule applied</div>
            <div className="body">{rec.rule}</div>
          </div>
        )}

        {rec.rationale && (
          <div className="section">
            <div className="section-label">Rationale</div>
            <div className="body">{rec.rationale}</div>
          </div>
        )}

        {rec.missingInfo && rec.missingInfo.length > 0 && (
          <div className="section">
            <div className="section-label">Missing information</div>
            <div className="missing">
              <div>The tool needs the following to complete this assessment:</div>
              <ul>{rec.missingInfo.map((m, i) => <li key={i}>{m}</li>)}</ul>
            </div>
          </div>
        )}

        {rec.supranationalNote && (
          <div className="section">
            <div className="section-label">Supranational note</div>
            <div className="supra">{rec.supranationalNote}</div>
          </div>
        )}

        {(rec.filingDeadline || rec.reviewPhase1 || rec.gunJumping || rec.fee) && (
          <div className="section">
            <div className="section-label">Filing logistics</div>
            <dl className="kv">
              {rec.filingDeadline && (<><dt>Deadline</dt><dd>{rec.filingDeadline}</dd></>)}
              {rec.reviewPhase1 && (<><dt>Phase 1 review</dt><dd>{rec.reviewPhase1}</dd></>)}
              {rec.gunJumping && (<><dt>Gun-jumping</dt><dd>{rec.gunJumping}</dd></>)}
              {rec.individualPenalty && (<><dt>Individual penalty</dt><dd>{rec.individualPenalty}</dd></>)}
              {rec.fee && (<><dt>Filing fee</dt><dd>{rec.fee}</dd></>)}
              {rec.localCounselRequired != null && (<><dt>Local counsel</dt><dd>{rec.localCounselRequired ? "Required" : "Optional"}</dd></>)}
              <dt>Table last updated</dt><dd>{rec.lastTableUpdate}</dd>
            </dl>
          </div>
        )}

        {rec.lawyerNote && (
          <div className="section">
            <div className="section-label">Lawyer note</div>
            <div className="body" style={{ fontStyle: "italic" }}>“{rec.lawyerNote}”</div>
          </div>
        )}

        <div className="actions-row">
          <button className="btn" onClick={onOpenOverride}>
            {rec.overridden ? "✎ Edit override" : "Override outcome"}
          </button>
          {!rec.approved ? (
            <button className="btn primary" onClick={() => onApprove(true)}>Mark partner-approved</button>
          ) : (
            <button className="btn ghost" onClick={() => onApprove(false)}>Unapprove</button>
          )}
        </div>
      </div>
    </div>
  );
}

function OverrideModal({ rec, onClose, onSave }) {
  const [outcome, setOutcome] = dUseState(rec.lawyerOutcome || rec.toolOutcome);
  const [note, setNote] = dUseState(rec.lawyerNote || "");
  const [error, setError] = dUseState(null);

  const choices = ["required", "borderline", "info_needed", "not_required"];

  const handleSave = () => {
    const isChange = outcome !== rec.toolOutcome;
    if (isChange && !note.trim()) {
      setError("A reason is required when overriding the tool's outcome.");
      return;
    }
    onSave({
      lawyerOutcome: isChange ? outcome : null,
      lawyerNote: note,
      overridden: isChange,
    });
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="hd">
          <h2>Override outcome — {rec.name}</h2>
          <div className="sub">
            AI said <b>{window.MC_HELPERS.OUTCOME_LABELS[rec.toolOutcome]}</b>.
            Lawyer overrides are layered on top — the AI assessment is never erased.
          </div>
        </div>
        <div className="bd">
          <div className="field">
            <label>Effective outcome</label>
            <div className="outcome-picker">
              {choices.map((c) => (
                <button
                  key={c}
                  className={outcome === c ? "active" : ""}
                  onClick={() => setOutcome(c)}
                >
                  <D_Badge outcome={c} />
                  {c === rec.toolOutcome && <span style={{ fontSize: 10, color: "var(--fg-faint)" }}>AI's view</span>}
                </button>
              ))}
            </div>
          </div>
          <div className="field">
            <label>Reason {outcome !== rec.toolOutcome && <span style={{ color: "var(--required-fg)" }}>(required)</span>}</label>
            <textarea
              value={note}
              onChange={(e) => { setNote(e.target.value); if (error) setError(null); }}
              placeholder="Why are you departing from the tool's view? (audit trail)"
            />
            {error && <div className="hint err">{error}</div>}
          </div>
          <div className="field hint">
            This change will be recorded in the audit trail with your name and the timestamp.
          </div>
        </div>
        <div className="ft">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave}>Save override</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DetailPanel, OverrideModal });
