// LeaderReview.jsx — Team Health diagnostic + leadership commitment.
// Stages: 'diagnostic' → 'commit' → 'summary'

const { useState: useStateLR, useMemo: useMemoLR } = React;

// ─────────────────────────────────────────────────────────────
// Container
// ─────────────────────────────────────────────────────────────
function LeaderReview({ journey, escalationLog, score, rank, onRestart, onRunAnotherSprint }) {
  const [phase, setPhase] = useStateLR("diagnostic");
  const [commitment, setCommitment] = useStateLR(null);

  const { scores } = useMemoLR(
    () => window.lrComputeHealth(escalationLog || []),
    [escalationLog]
  );
  const patterns = useMemoLR(
    () => window.lrRelevantPatterns(escalationLog || [], scores),
    [escalationLog, scores]
  );
  const evidence = useMemoLR(
    () => window.lrLeadershipEvidence(escalationLog || []),
    [escalationLog]
  );

  if (phase === "diagnostic") {
    return (
      <LRDiagnostic
        scores={scores}
        patterns={patterns}
        evidence={evidence}
        onContinue={() => setPhase("commit")}
      />
    );
  }
  if (phase === "commit") {
    return (
      <LRCommit
        patterns={patterns}
        scores={scores}
        commitment={commitment}
        onCommit={(p) => { setCommitment(p); setPhase("summary"); }}
        onBack={() => setPhase("diagnostic")}
      />
    );
  }
  return (
    <LRSummary
      journey={journey}
      scores={scores}
      commitment={commitment}
      score={score}
      rank={rank}
      onRestart={onRestart}
      onRunAnotherSprint={onRunAnotherSprint}
    />
  );
}

// ─────────────────────────────────────────────────────────────
// Phase 1 — Diagnostic
// ─────────────────────────────────────────────────────────────
function LRDiagnostic({ scores, patterns, evidence, onContinue }) {
  const hasEvidence = evidence.length > 0;
  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
      padding: "0 20px 16px",
      gap: 12,
      boxSizing: "border-box",
      overflowY: "auto",
    }}>
      <div className="ds-overline" style={{ color: "var(--color-brand-primary)", marginTop: 8 }}>
        Desk-health review
      </div>
      <h2 style={{
        margin: 0,
        fontFamily: "var(--font-family-sans)",
        fontWeight: 600,
        fontSize: 22,
        lineHeight: "28px",
        letterSpacing: "-0.005em",
        color: "var(--color-text-primary)",
        textWrap: "balance",
      }}>
        Desk health, surfaced by what got escalated.
      </h2>
      <p className="ds-body-sm" style={{ margin: 0, color: "var(--color-text-secondary)" }}>
        Most desk-health issues are downstream of how the desk is run, not the
        traders. The risk events that reached you today are the evidence.
      </p>

      {/* 4 dimensions */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: 6,
      }}>
        {window.LR_DIMENSIONS.map((d) => (
          <LRDimensionCard key={d.id} dim={d} score={scores[d.id]} />
        ))}
      </div>

      {/* Evidence */}
      {hasEvidence ? (
        <div style={{
          background: "var(--color-surface-subtle)",
          borderRadius: "var(--radius-md)",
          padding: "10px 12px",
          display: "flex",
          flexDirection: "column",
          gap: 6,
        }}>
          <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-text-muted)" }}>
            Today's escalations &middot; routed to the desk
          </div>
          {evidence.map((ev, i) => (
            <LREvidence key={i} ev={ev} />
          ))}
        </div>
      ) : (
        <div style={{
          background: "var(--color-surface-subtle)",
          borderRadius: "var(--radius-md)",
          padding: "12px 14px",
          fontSize: 12,
          lineHeight: "17px",
          color: "var(--color-text-secondary)",
        }}>
          No risk events reached you today. Either the desk didn't surface them,
          or the strategies' own rules handled it. Both are worth a moment.
        </div>
      )}

      {/* Patterns */}
      {patterns.length > 0 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-text-muted)" }}>
            Patterns observed
          </div>
          {patterns.map((p) => (
            <LRPatternCard key={p.id} pattern={p} />
          ))}
        </div>
      )}

      <button
        onClick={onContinue}
        style={{
          marginTop: 4,
          height: 48,
          background: "var(--color-brand-primary)",
          color: "var(--color-text-on-brand)",
          border: "none",
          borderRadius: "var(--radius-sm)",
          fontFamily: "var(--font-family-sans)",
          fontWeight: 600,
          fontSize: 15,
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
        }}
      >
        Commit to one improvement
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="9 18 15 12 9 6" />
        </svg>
      </button>
    </div>
  );
}

function LRDimensionCard({ dim, score }) {
  const band = window.lrBandFor(score);
  const bandColor = {
    success: "var(--color-success)",
    info: "var(--color-focus-ring)",
    warning: "var(--color-warning, #B36500)",
    danger: "var(--color-danger)",
  }[band.tone];
  return (
    <div style={{
      background: dim.bg,
      border: `1px solid ${dim.border}`,
      borderRadius: "var(--radius-md)",
      padding: "10px 11px 10px",
      display: "flex",
      flexDirection: "column",
      gap: 4,
    }}>
      <div style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 4,
      }}>
        <span style={{
          fontSize: 10,
          fontWeight: 700,
          letterSpacing: "0.1em",
          textTransform: "uppercase",
          color: dim.fg,
        }}>{dim.label}</span>
        <span style={{
          fontSize: 8,
          fontWeight: 700,
          letterSpacing: "0.12em",
          textTransform: "uppercase",
          color: bandColor,
        }}>{band.label}</span>
      </div>
      <div style={{
        fontFamily: "var(--font-family-sans)",
        fontWeight: 700,
        fontSize: 26,
        lineHeight: 1,
        color: "var(--color-text-primary)",
        fontVariantNumeric: "tabular-nums",
        letterSpacing: "-0.014em",
      }}>{score}</div>
      <div style={{
        height: 4,
        background: "rgba(255,255,255,0.55)",
        borderRadius: 2,
        overflow: "hidden",
        marginTop: 2,
      }}>
        <div style={{
          height: "100%",
          width: `${score}%`,
          background: bandColor,
          transition: "width var(--motion-slow) var(--ease-standard)",
        }} />
      </div>
      <div style={{
        fontSize: 10,
        lineHeight: "13px",
        color: "var(--color-text-secondary)",
        marginTop: 2,
      }}>{dim.sub}</div>
    </div>
  );
}

function LREvidence({ ev }) {
  const route = window.FB_ESCALATION_BY_ID?.[ev.routeId];
  return (
    <div style={{
      background: "var(--color-surface-default)",
      border: "1px solid var(--color-border-subtle)",
      borderRadius: "var(--radius-sm)",
      padding: "8px 10px",
      display: "flex",
      flexDirection: "column",
      gap: 3,
    }}>
      <div style={{
        display: "flex",
        alignItems: "center",
        gap: 6,
        fontSize: 9,
        fontWeight: 700,
        letterSpacing: "0.1em",
        textTransform: "uppercase",
      }}>
        <span style={{ color: "var(--color-danger)" }}>{ev.blockerLabel}</span>
        <span style={{ color: "var(--color-text-muted)" }}>→</span>
        <span style={{ color: route?.color || "var(--color-text-secondary)" }}>{route?.short || ev.routeId}</span>
        <span style={{ marginLeft: "auto", color: "var(--color-text-muted)", fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>
          {ev.storyRef}
        </span>
      </div>
      <div style={{
        fontSize: 11,
        lineHeight: "15px",
        color: "var(--color-text-primary)",
        letterSpacing: "-0.002em",
      }}>{ev.description}</div>
    </div>
  );
}

function LRPatternCard({ pattern }) {
  const dim = window.LR_DIMENSION_BY_ID[pattern.dimension];
  return (
    <div style={{
      background: "var(--color-surface-default)",
      borderLeft: `4px solid ${dim.fg}`,
      border: "1px solid var(--color-border-subtle)",
      borderRadius: "var(--radius-md)",
      padding: "10px 12px",
      display: "flex",
      flexDirection: "column",
      gap: 4,
    }}>
      <div style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 6,
      }}>
        <span style={{
          fontFamily: "var(--font-family-sans)",
          fontWeight: 700,
          fontSize: 13,
          color: "var(--color-text-primary)",
          letterSpacing: "-0.003em",
        }}>{pattern.title}</span>
        <span style={{
          fontSize: 9,
          fontWeight: 700,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          color: dim.fg,
          background: dim.bg,
          border: `1px solid ${dim.border}`,
          padding: "2px 7px",
          borderRadius: "var(--radius-pill)",
        }}>{dim.label}</span>
      </div>
      <div style={{
        fontSize: 11.5,
        lineHeight: "16px",
        color: "var(--color-text-secondary)",
      }}>{pattern.diagnostic}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Phase 2 — Commit
// ─────────────────────────────────────────────────────────────
function LRCommit({ patterns, scores, onCommit, onBack }) {
  // If we have patterns from evidence, surface those first.
  // Otherwise show the lowest-scoring dimension's patterns from the full library.
  const options = useMemoLR(() => {
    if (patterns.length > 0) return patterns;
    const lowestDim = window.LR_DIMENSIONS
      .map((d) => ({ id: d.id, score: scores[d.id] }))
      .sort((a, b) => a.score - b.score)[0];
    return window.LR_PATTERNS
      .filter((p) => p.dimension === lowestDim.id)
      .slice(0, 3);
  }, [patterns, scores]);

  const [picked, setPicked] = useStateLR(null);

  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
      padding: "0 20px 16px",
      gap: 12,
      boxSizing: "border-box",
      overflowY: "auto",
    }}>
      <button
        onClick={onBack}
        style={{
          alignSelf: "flex-start",
          background: "none",
          border: "none",
          padding: 0,
          color: "var(--color-text-link)",
          fontFamily: "var(--font-family-sans)",
          fontSize: 13,
          fontWeight: 500,
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          gap: 4,
          marginTop: 8,
        }}
      >
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="15 18 9 12 15 6" />
        </svg>
        Back to diagnostic
      </button>

      <div className="ds-overline" style={{ color: "var(--color-brand-primary)" }}>
        Leadership commitment
      </div>
      <h2 style={{
        margin: 0,
        fontFamily: "var(--font-family-sans)",
        fontWeight: 600,
        fontSize: 22,
        lineHeight: "28px",
        letterSpacing: "-0.005em",
        color: "var(--color-text-primary)",
        textWrap: "balance",
      }}>
        Pick one thing you'll actually change.
      </h2>
      <p className="ds-body-sm" style={{ margin: 0, color: "var(--color-text-secondary)" }}>
        The desk can't fix any of this from where they sit. Pick the change
        you're going to make as desk lead before tomorrow's open.
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {options.map((p) => {
          const dim = window.LR_DIMENSION_BY_ID[p.dimension];
          const isPicked = picked?.id === p.id;
          return (
            <button
              key={p.id}
              onClick={() => setPicked(p)}
              style={{
                background: isPicked ? dim.bg : "var(--color-surface-default)",
                border: `1.5px solid ${isPicked ? dim.fg : "var(--color-border-subtle)"}`,
                borderRadius: "var(--radius-md)",
                padding: "12px 14px",
                textAlign: "left",
                cursor: "pointer",
                font: "inherit",
                color: "inherit",
                display: "flex",
                flexDirection: "column",
                gap: 5,
                transition: "background var(--motion-base) var(--ease-standard), border-color var(--motion-base) var(--ease-standard), transform var(--motion-fast) var(--ease-standard)",
                transform: isPicked ? "translateY(-1px)" : "translateY(0)",
                boxShadow: isPicked ? "var(--shadow-2)" : "none",
              }}
            >
              <div style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                gap: 6,
              }}>
                <span style={{
                  fontFamily: "var(--font-family-sans)",
                  fontWeight: 700,
                  fontSize: 13,
                  color: "var(--color-text-primary)",
                  letterSpacing: "-0.003em",
                }}>{p.title}</span>
                <span style={{
                  fontSize: 9,
                  fontWeight: 700,
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  color: dim.fg,
                  background: dim.bg,
                  border: `1px solid ${dim.border}`,
                  padding: "2px 7px",
                  borderRadius: "var(--radius-pill)",
                }}>{dim.label}</span>
              </div>
              <div style={{
                fontFamily: "var(--font-family-sans)",
                fontSize: 12.5,
                lineHeight: "17px",
                color: "var(--color-text-primary)",
                fontWeight: 600,
                letterSpacing: "-0.003em",
              }}>{p.action}</div>
              <div style={{
                fontSize: 11,
                lineHeight: "15px",
                color: "var(--color-text-secondary)",
              }}>Addresses: {p.diagnostic.split(".")[0]}.</div>
            </button>
          );
        })}
      </div>

      <button
        onClick={() => picked && onCommit(picked)}
        disabled={!picked}
        style={{
          marginTop: "auto",
          height: 48,
          background: picked ? "var(--color-brand-primary)" : "var(--color-surface-subtle)",
          color: picked ? "var(--color-text-on-brand)" : "var(--color-text-muted)",
          border: "none",
          borderRadius: "var(--radius-sm)",
          fontFamily: "var(--font-family-sans)",
          fontWeight: 600,
          fontSize: 15,
          cursor: picked ? "pointer" : "not-allowed",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
        }}
      >
        {picked ? "I commit to this →" : "Pick one above"}
      </button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Phase 3 — Final summary
// ─────────────────────────────────────────────────────────────
function LRSummary({ journey, scores, commitment, score, rank, onRestart, onRunAnotherSprint }) {
  const dim = commitment ? window.LR_DIMENSION_BY_ID[commitment.dimension] : null;
  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
      padding: "0 20px 16px",
      gap: 12,
      boxSizing: "border-box",
      overflowY: "auto",
    }}>
      <div className="ds-overline" style={{ color: "var(--color-brand-primary)", marginTop: 8 }}>
        Session complete
      </div>
      <h2 style={{
        margin: 0,
        fontFamily: "var(--font-family-sans)",
        fontWeight: 600,
        fontSize: 22,
        lineHeight: "28px",
        letterSpacing: "-0.005em",
        color: "var(--color-text-primary)",
        textWrap: "balance",
      }}>
        That's a wrap. Take what changed forward.
      </h2>

      {/* Score recap */}
      <div style={{
        background: "var(--color-surface-default)",
        border: "1.5px solid var(--color-brand-primary)",
        borderRadius: "var(--radius-md)",
        padding: "12px 14px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 12,
      }}>
        <div>
          <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-brand-primary)" }}>
            Your score
          </div>
          <div style={{
            fontFamily: "var(--font-family-sans)",
            fontWeight: 700,
            fontSize: 28,
            lineHeight: 1,
            color: "var(--color-brand-primary)",
            fontVariantNumeric: "tabular-nums",
            letterSpacing: "-0.018em",
          }}>${(score || 0).toLocaleString()}</div>
        </div>
        {rank && (
          <div style={{
            padding: "4px 10px",
            background: "var(--color-surface-promo)",
            border: "1px solid rgba(196,31,62,0.20)",
            borderRadius: "var(--radius-pill)",
            fontFamily: "var(--font-family-sans)",
            fontWeight: 700,
            fontSize: 12,
            color: "var(--color-brand-mark)",
            letterSpacing: "0.04em",
            fontVariantNumeric: "tabular-nums",
          }}>
            RANK #{rank}
          </div>
        )}
      </div>

      {/* Commitment card */}
      {commitment && dim && (
        <div style={{
          background: dim.bg,
          border: `1.5px solid ${dim.fg}`,
          borderRadius: "var(--radius-md)",
          padding: "14px 14px 14px",
          display: "flex",
          flexDirection: "column",
          gap: 6,
          position: "relative",
        }}>
          <div style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
          }}>
            <span style={{
              fontSize: 10,
              fontWeight: 700,
              letterSpacing: "0.14em",
              textTransform: "uppercase",
              color: dim.fg,
            }}>You committed to</span>
            <span style={{
              fontSize: 9,
              fontWeight: 700,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              color: dim.fg,
              background: "rgba(255,255,255,0.6)",
              border: `1px solid ${dim.border}`,
              padding: "1px 7px",
              borderRadius: "var(--radius-pill)",
              marginLeft: "auto",
            }}>{dim.label}</span>
          </div>
          <div style={{
            fontFamily: "var(--font-family-sans)",
            fontWeight: 700,
            fontSize: 15,
            lineHeight: "21px",
            color: "var(--color-text-primary)",
            letterSpacing: "-0.005em",
          }}>{commitment.action}</div>
          <div style={{
            fontSize: 11,
            lineHeight: "15px",
            color: "var(--color-text-secondary)",
            marginTop: 2,
          }}>
            Addresses: {commitment.title.toLowerCase()}.
          </div>
        </div>
      )}

      {/* Mini sprint recap */}
      <div style={{
        background: "var(--color-surface-subtle)",
        borderRadius: "var(--radius-md)",
        padding: "10px 12px",
        display: "flex",
        flexDirection: "column",
        gap: 4,
      }}>
        <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-text-muted)" }}>
          Session recap
        </div>
        <LRRecap label="Regime"  value={journey?.okrTag} />
        <LRRecap label="Closed"  value={`${journey?.shippedCount || 0} of ${journey?.plannedCount || 0}`} />
        <LRRecap label="P&L"     value={journey?.bv != null ? `$${(journey.bv || 0).toLocaleString()} of $${(journey?.maxBV || 0).toLocaleString()}` : "—"} />
        <LRRecap label="Alignment / Autonomy" value={`${scores.alignment} · ${scores.autonomy}`} />
        <LRRecap label="Capability / Safety"  value={`${scores.capability} · ${scores.safety}`} />
      </div>

      <div style={{ marginTop: "auto", display: "flex", gap: 10 }}>
        <button
          onClick={onRestart}
          style={{
            flex: 1,
            height: 46,
            background: "var(--color-surface-default)",
            color: "var(--color-text-primary)",
            border: "1px solid var(--color-border-subtle)",
            borderRadius: "var(--radius-sm)",
            fontFamily: "var(--font-family-sans)",
            fontWeight: 600,
            fontSize: 14,
            cursor: "pointer",
          }}
        >
          Restart
        </button>
        <button
          onClick={onRunAnotherSprint}
          style={{
            flex: 1.4,
            height: 46,
            background: "var(--color-brand-primary)",
            color: "var(--color-text-on-brand)",
            border: "none",
            borderRadius: "var(--radius-sm)",
            fontFamily: "var(--font-family-sans)",
            fontWeight: 600,
            fontSize: 15,
            cursor: "pointer",
          }}
        >
          Run another session
        </button>
      </div>
    </div>
  );
}

function LRRecap({ label, value }) {
  return (
    <div style={{
      display: "flex",
      alignItems: "baseline",
      gap: 8,
      paddingTop: 3,
      borderTop: "1px solid var(--color-border-subtle)",
    }}>
      <span style={{
        fontSize: 10,
        letterSpacing: "0.12em",
        textTransform: "uppercase",
        fontWeight: 700,
        color: "var(--color-text-muted)",
        minWidth: 120,
      }}>{label}</span>
      <span style={{
        fontSize: 12,
        fontWeight: 600,
        color: "var(--color-text-primary)",
        flex: 1,
        fontVariantNumeric: "tabular-nums",
      }}>{value || "—"}</span>
    </div>
  );
}

Object.assign(window, { LeaderReview });
