// RetroDebrief.jsx — locked retro results + journey recap + leaderboard.

const { useState: useStateRD, useMemo: useMemoRD } = React;

function RetroDebrief({ items, votes, journey, nickname, onReplay, onPlanAnother, onRunAnotherSprint }) {
  // Compute the player's score from the journey and submit to the
  // leaderboard once, on first render of this debrief.
  const score = useMemoRD(() => window.lbComputeScore(journey), [journey]);
  const breakdown = useMemoRD(() => window.lbScoreBreakdown(journey), [journey]);
  const submission = useMemoRD(
    () => window.lbSubmit(nickname || "Anonymous", score),
    [nickname, score]
  );
  // Build sorted-with-total per column
  const tally = {};
  window.RETRO_COLUMNS.forEach((col) => {
    const arr = (items[col.id] || []).map((it) => ({
      ...it,
      total: it.baseVotes + (votes[it.id] ? 1 : 0),
      playerVoted: !!votes[it.id],
    }));
    arr.sort((a, b) => b.total - a.total);
    tally[col.id] = arr;
  });

  const actionsCol = window.RETRO_COLUMN_BY_ID.actions;
  const wellCol    = window.RETRO_COLUMN_BY_ID.went_well;
  const notWellCol = window.RETRO_COLUMN_BY_ID.not_well;

  const committedActions  = tally.actions.slice(0, window.RETRO_COMMIT_COUNT);
  const celebrated        = tally.went_well.slice(0, 1);
  const acknowledged      = tally.not_well.slice(0, 1);

  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
      padding: "0 20px 20px",
      gap: 14,
      boxSizing: "border-box",
      overflowY: "auto",
    }}>
      <div className="ds-overline" style={{ color: "var(--color-brand-primary)", marginTop: 6 }}>
        Process review · Filed
      </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",
      }}>
        Filed to the knowledge store.
      </h2>

      {/* Score reveal */}
      <div style={{
        background: "var(--color-surface-default)",
        border: "1.5px solid var(--color-brand-primary)",
        borderRadius: "var(--radius-md)",
        padding: "14px 16px 14px",
        display: "flex",
        flexDirection: "column",
        gap: 10,
        position: "relative",
      }}>
        <div style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "baseline",
          gap: 8,
        }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 1, minWidth: 0 }}>
            <span className="ds-overline" style={{ color: "var(--color-brand-primary)", fontSize: 10 }}>
              Your score
            </span>
            <span style={{
              fontFamily: "var(--font-family-sans)",
              fontSize: 13,
              fontWeight: 700,
              color: "var(--color-text-primary)",
              letterSpacing: "-0.003em",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}>{nickname || "Anonymous"}</span>
          </div>
          <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",
            flexShrink: 0,
          }}>
            RANK #{submission.rank}
          </div>
        </div>
        <div style={{
          fontFamily: "var(--font-family-sans)",
          fontWeight: 700,
          fontSize: 40,
          lineHeight: 1,
          color: "var(--color-brand-primary)",
          letterSpacing: "-0.025em",
          fontVariantNumeric: "tabular-nums",
        }}>${score.toLocaleString()}</div>
        {submission.beatPrevious && (
          <div style={{
            fontSize: 11,
            fontWeight: 700,
            color: "var(--color-success)",
            letterSpacing: "0.04em",
            display: "inline-flex",
            alignItems: "center",
            gap: 4,
          }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="18 15 12 9 6 15" />
            </svg>
            Up ${(score - (submission.previous || 0)).toLocaleString()} from your previous best.
          </div>
        )}
        <div style={{
          display: "flex",
          flexDirection: "column",
          gap: 4,
          paddingTop: 8,
          borderTop: "1px solid var(--color-border-subtle)",
        }}>
          {breakdown.map((row) => (
            <div key={row.label} style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
            }}>
              <span style={{
                fontSize: 10,
                fontWeight: 700,
                letterSpacing: "0.1em",
                textTransform: "uppercase",
                color: "var(--color-text-secondary)",
                minWidth: 80,
              }}>{row.label}</span>
              <span style={{
                flex: 1,
                fontSize: 11,
                color: "var(--color-text-muted)",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}>{row.sub}</span>
              <span style={{
                fontFamily: "var(--font-family-sans)",
                fontWeight: 700,
                fontSize: 12,
                color: row.value > 0
                  ? "var(--color-text-primary)"
                  : row.value < 0
                    ? "var(--color-danger)"
                    : "var(--color-text-muted)",
                fontVariantNumeric: "tabular-nums",
                letterSpacing: "-0.005em",
              }}>
                {row.value > 0 ? `+$${row.value.toLocaleString()}` : row.value < 0 ? `−$${Math.abs(row.value).toLocaleString()}` : "$0"}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Committed actions — hero */}
      <div style={{
        background: actionsCol.bg,
        border: `1px solid ${actionsCol.border}`,
        borderRadius: "var(--radius-md)",
        padding: "12px 14px 14px",
        display: "flex",
        flexDirection: "column",
        gap: 10,
      }}>
        <div style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 8,
        }}>
          <span style={{
            fontSize: 11,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            fontWeight: 700,
            color: actionsCol.fg,
          }}>Start — begin doing</span>
          <span style={{
            fontSize: 10,
            color: "var(--color-text-muted)",
            letterSpacing: "0.06em",
            fontWeight: 600,
          }}>{actionsCol.sub}</span>
        </div>
        {committedActions.map((it, i) => (
          <div key={it.id} style={{
            background: "var(--color-surface-default)",
            border: `1.5px solid ${actionsCol.fg}`,
            borderRadius: "var(--radius-md)",
            padding: "12px 14px",
            position: "relative",
            display: "flex",
            gap: 10,
            alignItems: "flex-start",
          }}>
            <span style={{
              width: 28, height: 28,
              borderRadius: "50%",
              background: actionsCol.fg,
              color: "#fff",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontFamily: "var(--font-family-sans)",
              fontWeight: 700,
              fontSize: 13,
              fontVariantNumeric: "tabular-nums",
              flexShrink: 0,
            }}>{i + 1}</span>
            <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 4 }}>
              <div style={{
                fontFamily: "var(--font-family-sans)",
                fontSize: 13.5,
                lineHeight: "19px",
                color: "var(--color-text-primary)",
                fontWeight: 600,
                letterSpacing: "-0.003em",
              }}>{it.text}</div>
              <div style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                fontSize: 11,
                color: "var(--color-text-secondary)",
              }}>
                <span>{it.author.name}</span>
                <span>·</span>
                <span style={{
                  fontWeight: 700,
                  fontVariantNumeric: "tabular-nums",
                  color: actionsCol.fg,
                }}>{it.total} vote{it.total === 1 ? "" : "s"}</span>
                {it.playerVoted && (
                  <>
                    <span>·</span>
                    <span style={{ fontWeight: 700, color: "var(--color-brand-primary)", letterSpacing: "0.04em" }}>
                      you voted
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Celebrate + Acknowledge — 2 mini cards */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: 8,
      }}>
        <RDCornerCard col={wellCol}    item={celebrated[0]}   verb="Continue" />
        <RDCornerCard col={notWellCol} item={acknowledged[0]} verb="Stop" />
      </div>

      {/* Journey recap */}
      <div style={{
        background: "var(--color-surface-subtle)",
        borderRadius: "var(--radius-md)",
        padding: "12px 14px",
        display: "flex",
        flexDirection: "column",
        gap: 8,
      }}>
        <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-text-muted)" }}>
          The session · scan → review
        </div>
        <RDJourneyRow label="Regime"      value={journey?.okrTag} secondary={journey?.objectiveShort} />
        <RDJourneyRow label="Strategies"  value={`${journey?.epicsCount || 0} staged`} />
        <RDJourneyRow label="Validation"  value={`${journey?.refinedReady || 0} checks cleared`} />
        <RDJourneyRow label="Deploy plan" value={journey?.sprintGoal} />
        <RDJourneyRow label="Queued"      value={`${journey?.plannedCount || 0} strateg${journey?.plannedCount === 1 ? "y" : "ies"} · ${journey?.plannedPoints || 0} R`} />
        <RDJourneyRow label="Closed"      value={`${journey?.shippedCount || 0} of ${journey?.plannedCount || 0}`} accent={journey?.shippedCount >= (journey?.plannedCount || 0) * 0.8} />
        <RDJourneyRow label="P&L booked"  value={journey?.bv != null ? `$${(journey.bv || 0).toLocaleString()} of $${(journey?.maxBV || 0).toLocaleString()}` : "—"} />
        <RDJourneyRow label="Knowledge"   value={`${committedActions.length} insight${committedActions.length === 1 ? "" : "s"} filed`} accent />
      </div>

      {/* Leaderboard */}
      <div style={{
        background: "var(--color-surface-default)",
        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: "baseline",
          justifyContent: "space-between",
          marginBottom: 4,
        }}>
          <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-text-muted)" }}>
            Leaderboard
          </div>
          <span style={{ fontSize: 10, color: "var(--color-text-muted)", fontWeight: 600 }}>
            Best per nickname
          </span>
        </div>
        {submission.board.slice(0, 5).map((entry, i) => (
          <window.LBRow key={entry.id} rank={i + 1} entry={entry} />
        ))}
        {submission.rank > 5 && submission.board[submission.rank - 1] && (
          <>
            <div style={{
              fontSize: 10,
              textAlign: "center",
              color: "var(--color-text-muted)",
              padding: "2px 0",
              letterSpacing: "0.2em",
            }}>• • •</div>
            <window.LBRow rank={submission.rank} entry={submission.board[submission.rank - 1]} />
          </>
        )}
      </div>

      <div style={{
        background: "var(--color-surface-info)",
        borderLeft: "4px solid var(--color-focus-ring)",
        padding: "10px 14px",
        borderRadius: "var(--radius-sm)",
      }}>
        <div className="ds-body-sm" style={{ color: "var(--color-text-primary)", fontSize: 12, lineHeight: "17px" }}>
          That's the loop. The scan set the direction, risk analysis got us ready,
          the plan sized the capital, the desk ran the strategies, the review
          booked the P&L — and the knowledge store sharpens the next goal.
        </div>
      </div>

      <div style={{ marginTop: 6, display: "flex", gap: 10 }}>
        <button
          onClick={onReplay}
          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.6,
            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",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
          }}
        >
          Run another session
          <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>
    </div>
  );
}

function RDCornerCard({ col, item, verb }) {
  if (!item) return (
    <div style={{
      background: col.bg,
      border: `1px solid ${col.border}`,
      borderRadius: "var(--radius-md)",
      padding: "10px 12px",
      minHeight: 84,
      display: "flex",
      flexDirection: "column",
      gap: 4,
      justifyContent: "center",
    }}>
      <div style={{
        fontSize: 9,
        letterSpacing: "0.14em",
        textTransform: "uppercase",
        fontWeight: 700,
        color: col.fg,
      }}>{verb}</div>
      <div style={{
        fontSize: 11,
        color: "var(--color-text-muted)",
      }}>—</div>
    </div>
  );
  return (
    <div style={{
      background: col.bg,
      border: `1px solid ${col.border}`,
      borderRadius: "var(--radius-md)",
      padding: "10px 12px 12px",
      display: "flex",
      flexDirection: "column",
      gap: 5,
    }}>
      <div style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
      }}>
        <span style={{
          fontSize: 9,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          fontWeight: 700,
          color: col.fg,
        }}>{verb}</span>
        <span style={{
          fontSize: 9,
          fontWeight: 700,
          fontVariantNumeric: "tabular-nums",
          color: col.fg,
        }}>{item.total} vote{item.total === 1 ? "" : "s"}</span>
      </div>
      <div style={{
        fontFamily: "var(--font-family-sans)",
        fontSize: 11.5,
        lineHeight: "15px",
        color: "var(--color-text-primary)",
        letterSpacing: "-0.002em",
        fontWeight: 500,
      }}>
        {item.text}
      </div>
      <div style={{
        fontSize: 10,
        color: "var(--color-text-muted)",
        marginTop: 1,
      }}>
        {item.author.name}
        {item.playerVoted && (
          <span style={{
            marginLeft: 5,
            color: "var(--color-brand-primary)",
            fontWeight: 700,
            letterSpacing: "0.04em",
          }}>· you voted</span>
        )}
      </div>
    </div>
  );
}

function RDJourneyRow({ label, value, secondary, accent }) {
  return (
    <div style={{
      display: "flex",
      alignItems: "flex-start",
      gap: 10,
      paddingTop: 4,
      borderTop: "1px solid var(--color-border-subtle)",
    }}>
      <span style={{
        fontSize: 10,
        letterSpacing: "0.14em",
        textTransform: "uppercase",
        fontWeight: 700,
        color: "var(--color-text-muted)",
        minWidth: 80,
        paddingTop: 1,
      }}>{label}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: "var(--font-family-sans)",
          fontSize: 12,
          fontWeight: accent ? 700 : 600,
          color: accent ? "var(--color-brand-primary)" : "var(--color-text-primary)",
          lineHeight: "16px",
        }}>{value || "—"}</div>
        {secondary && (
          <div style={{
            fontSize: 11,
            color: "var(--color-text-secondary)",
            lineHeight: "15px",
            marginTop: 1,
          }}>{secondary}</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { RetroDebrief });
