function MetricCell({ label, value, suffix = "" }) {
  const unavailable = value === "unavailable" || value == null || value === "";
  return (
    <div style={{ padding: "12px 14px", borderRadius: 10, border: "1px solid var(--green-600)", background: "rgba(5,8,7,0.35)" }}>
      <div className="mono" style={{ fontSize: 10, color: "var(--slate)", textTransform: "uppercase", letterSpacing: "0.08em" }}>{label}</div>
      <div className="num" style={{ marginTop: 6, fontSize: 20, color: unavailable ? "var(--slate-dim)" : "var(--mint-soft)" }}>
        {unavailable ? "Unavailable" : `${value}${suffix}`}
      </div>
    </div>
  );
}

function ProfileSection({ eyebrow, title, children }) {
  return (
    <div className="card" style={{ padding: 24 }}>
      <SectionTitle eyebrow={eyebrow}>{title}</SectionTitle>
      {children}
    </div>
  );
}

function RecordGrid({ record }) {
  const entries = Object.entries(record || {});
  if (!entries.length) {
    return <div className="mono" style={{ color: "var(--slate-dim)", fontSize: 12 }}>No metrics available for this section.</div>;
  }
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10 }}>
      {entries.map(([label, value]) => (
        <MetricCell key={label} label={label.replace(/([A-Z])/g, " $1").replace(/^./, s => s.toUpperCase())} value={value} />
      ))}
    </div>
  );
}

function PlayerDetailView({ player, onBack }) {
  const { TEAMS } = window;
  if (!player) {
    return (
      <div className="view-enter" style={{ maxWidth: 720, margin: "0 auto", padding: "64px 24px" }}>
        <div className="card" style={{ padding: 28 }}>
          <div className="mono" style={{ color: "var(--gold)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase" }}>Player unavailable</div>
          <h1 className="display" style={{ margin: "10px 0 8px", color: "var(--mint-soft)", fontSize: 28 }}>This player could not be loaded</h1>
          <p style={{ margin: 0, color: "var(--slate)", lineHeight: 1.6 }}>Return to the previous screen and select the player again.</p>
          <button onClick={onBack} className="btn ghost" style={{ marginTop: 18 }}>Back</button>
        </div>
      </div>
    );
  }

  const resolved = (window.resolveCanonicalPlayer && window.resolveCanonicalPlayer(player)) || player;
  const profile = resolved.profile || window.PLAYER_PROFILES?.[resolved.id] || {
    name: resolved.name,
    pos: resolved.pos,
    team: resolved.team,
    projection: {
      impactRank: resolved.rank || 0,
      valueGrade: "—",
      sosRank: 0,
      ceiling: (resolved.proj || 0) * 17,
      floor: 0,
      boomPct: 0,
      bustPct: 0,
    },
    scoring: {
      ppr: { weekly: resolved.proj || 0, season: resolved.ros || 0 },
      halfPpr: { weekly: resolved.proj || 0, season: resolved.ros || 0 },
      standard: { weekly: resolved.proj || 0, season: resolved.ros || 0 },
    },
    historical: { seasons: [], gameLogs: [] },
    workload: {},
    efficiency: {},
    drivers: [],
    advanced: {},
    risk: resolved.risk || "med",
  };
  const team = TEAMS[resolved.team] || { color: "#2A4A37", name: resolved.team };
  const weekly = (format) => Number(profile.scoring?.[format]?.weekly ?? resolved.proj ?? 0) || 0;
  const seasonPts = (format) => Number(profile.scoring?.[format]?.season ?? resolved.ros ?? 0) || 0;
  const scoring = {
    standard: { weekly: weekly("standard"), season: seasonPts("standard") },
    halfPpr: { weekly: weekly("halfPpr"), season: seasonPts("halfPpr") },
    ppr: { weekly: weekly("ppr"), season: seasonPts("ppr") },
  };
  const histSeasons = (profile.historical?.seasons || []).length
    ? profile.historical.seasons
    : [2022, 2023, 2024, 2025].map((year) => ({
      year, gamesPlayed: 0, fantasyPoints: 0, pointsPerGame: 0, targets: 0, receptions: 0, carries: 0,
    }));

  return (
    <div className="view-enter" style={{ maxWidth: 1280, margin: "0 auto", padding: "24px 32px 48px" }}>
      <button onClick={onBack} style={{
        background: "transparent", border: "none", color: "var(--slate)",
        cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
        fontSize: 13, padding: 0, marginBottom: 20
      }}>
        <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><window.IconChevron size={14} /></span>
        Back to rankings
      </button>

      <div className="card" style={{
        position: "relative", overflow: "hidden",
        background: `linear-gradient(135deg, ${team.color}30, var(--green-800) 50%, var(--green-900))`,
        padding: 32, marginBottom: 20,
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 24 }}>
          <div style={{ display: "flex", gap: 24, alignItems: "center" }}>
            <div style={{
              width: 92, height: 92, borderRadius: 16,
              background: `linear-gradient(135deg, ${team.color}, var(--green-900))`,
              display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: "Space Grotesk", fontWeight: 700, fontSize: 36, color: "white",
              border: "1px solid var(--green-600)",
            }}>{resolved.pos}</div>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <PosPill pos={resolved.pos} />
                <TeamChip team={resolved.team} size="md" />
                <RiskDot risk={profile?.risk || resolved.risk} />
              </div>
              <h1 className="display" style={{ margin: 0, fontSize: 44, color: "var(--mint-soft)", lineHeight: 1 }}>{resolved.name}</h1>
              <div style={{ marginTop: 10, color: "var(--slate)", fontSize: 14 }}>
                {`949 rank #${profile.projection?.impactRank || resolved.rank || 0} · Value ${profile.projection?.valueGrade || "—"} · SOS ${profile.projection?.sosRank || 0}/32`}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gap: 16 }}>
        <ProfileSection eyebrow="Projection Summary" title="2026 scoring impact">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", gap: 10 }}>
            <MetricCell label="PPR weekly" value={scoring.ppr.weekly.toFixed(1)} />
            <MetricCell label="Half PPR weekly" value={scoring.halfPpr.weekly.toFixed(1)} />
            <MetricCell label="Standard weekly" value={scoring.standard.weekly.toFixed(1)} />
            <MetricCell label="Season PPR" value={scoring.ppr.season.toFixed(0)} />
            <MetricCell label="Ceiling" value={((profile.projection?.ceiling || (resolved.proj || 0) * 17) / 17).toFixed(1)} />
            <MetricCell label="Floor" value={((profile.projection?.floor || 0) / 17).toFixed(1)} />
            <MetricCell label="Boom %" value={profile?.projection.boomPct ?? resolved.boom ?? 0} suffix="%" />
            <MetricCell label="Bust %" value={profile?.projection.bustPct ?? resolved.bust ?? 0} suffix="%" />
            <MetricCell label="Exceeded weeks" value={profile?.historical?.weeklyOutcomes?.boomWeeks ?? resolved.weeklyConsistency?.boomWeeks ?? 0} />
            <MetricCell label="Hit weeks" value={profile?.historical?.weeklyOutcomes?.expectedWeeks ?? resolved.weeklyConsistency?.hitWeeks ?? 0} />
            <MetricCell label="Below weeks" value={profile?.historical?.weeklyOutcomes?.bustWeeks ?? resolved.weeklyConsistency?.bustWeeks ?? 0} />
          </div>
        </ProfileSection>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <ProfileSection eyebrow="Role + Usage" title="Workload">
            <RecordGrid record={profile?.workload} />
          </ProfileSection>
          <ProfileSection eyebrow="Efficiency" title="Rate stats">
            <RecordGrid record={profile?.efficiency} />
          </ProfileSection>
        </div>

        <ProfileSection eyebrow="Scoring Format Impact" title="Format sensitivity">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 10 }}>
            <MetricCell label="Standard season" value={scoring.standard.season.toFixed(1)} />
            <MetricCell label="Half PPR season" value={scoring.halfPpr.season.toFixed(1)} />
            <MetricCell label="PPR season" value={scoring.ppr.season.toFixed(1)} />
          </div>
        </ProfileSection>

        <ProfileSection eyebrow="Projection Drivers" title="Why this projection">
          {(profile?.drivers || []).length ? (
            <div style={{ display: "grid", gap: 10 }}>
              {profile.drivers.map((driver) => (
                <div key={driver.label} style={{ padding: 14, borderRadius: 10, border: "1px solid var(--green-600)", background: "var(--green-900)" }}>
                  <div className="mono" style={{ fontSize: 10, color: driver.tone === "good" ? "var(--mint)" : driver.tone === "bad" ? "var(--red)" : "var(--gold)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{driver.label}</div>
                  <div style={{ marginTop: 6, color: "var(--mint-soft)", fontSize: 13, lineHeight: 1.5 }}>{driver.text}</div>
                </div>
              ))}
            </div>
          ) : (
            <div className="mono" style={{ color: "var(--slate-dim)", fontSize: 12 }}>Unavailable</div>
          )}
        </ProfileSection>

        <ProfileSection eyebrow="Advanced Model" title="Historical vs projected context">
          <RecordGrid record={profile?.advanced} />
          {profile?.historical?.seasons?.length ? (
            <div style={{ marginTop: 16 }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--slate)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>Historical seasons</div>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "JetBrains Mono", fontVariantNumeric: "tabular-nums" }}>
                  <thead>
                    <tr style={{ fontSize: 10, color: "var(--slate)", textTransform: "uppercase", letterSpacing: "0.08em" }}>
                      <th style={{ textAlign: "left", padding: "8px 10px" }}>Year</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>GP</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>Pts</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>PPG</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>Tgt</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>Rec</th>
                      <th style={{ textAlign: "right", padding: "8px 10px" }}>Car</th>
                    </tr>
                  </thead>
                  <tbody>
                    {histSeasons.slice().sort((a, b) => a.year - b.year).map((season) => (
                      <tr key={season.year} style={{ borderTop: "1px solid var(--green-600)" }}>
                        <td style={{ padding: "8px 10px", color: "var(--mint-soft)" }}>{season.year}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--mint-soft)" }}>{season.gamesPlayed}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--mint)" }}>{season.fantasyPoints.toFixed(1)}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--mint-soft)" }}>{season.pointsPerGame.toFixed(1)}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--slate)" }}>{season.targets != null ? season.targets : "—"}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--slate)" }}>{season.receptions != null ? season.receptions : "—"}</td>
                        <td style={{ padding: "8px 10px", textAlign: "right", color: "var(--slate)" }}>{season.carries != null ? season.carries : "—"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : null}
          {profile?.historical?.gameLogs?.length ? (
            <div style={{ marginTop: 18 }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--slate)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>
                Weekly logs · {Math.max(...profile.historical.gameLogs.map((g) => g.season))}
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {profile.historical.gameLogs
                  .filter((g) => g.season === Math.max(...profile.historical.gameLogs.map((row) => row.season)))
                  .sort((a, b) => a.week - b.week)
                  .map((g) => (
                    <div key={`${g.season}-${g.week}`} style={{
                      minWidth: 64, padding: "8px 8px", borderRadius: 8,
                      border: "1px solid var(--green-600)", background: "var(--green-900)", textAlign: "center",
                    }}>
                      <div className="mono" style={{ fontSize: 9, color: "var(--slate)" }}>W{g.week}</div>
                      <div className="num" style={{ fontSize: 14, color: "var(--mint-soft)" }}>{Number(g.fantasyPoints || 0).toFixed(1)}</div>
                      {g.expectedPoints != null && (
                        <div className="mono" style={{ fontSize: 8, color: "var(--slate-dim)" }}>p {Number(g.expectedPoints).toFixed(1)}</div>
                      )}
                    </div>
                  ))}
              </div>
            </div>
          ) : null}
        </ProfileSection>
      </div>
    </div>
  );
}
