// "Statistics" section — Performance grid + Player Trends

function StatisticsView({ tab, setTab, onSelectPlayer, activeLeague, session }) {
  const live = window.useLiveLeague ? window.useLiveLeague(activeLeague) : null;
  const loggedIn = !!session;
  const weekLabel = live
    ? `${live.teamName || "League"} · Week ${live.currentWeek}`
    : loggedIn
      ? "League · Week 1"
      : "Season · Through Week 10";

  return (
    <div className="view-enter" style={{ maxWidth: 1440, margin: "0 auto", padding: 28 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 16, marginBottom: 20 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color: "var(--mint)", textTransform: "uppercase", letterSpacing: "0.18em", marginBottom: 6 }}>{weekLabel}</div>
          <h1 className="display" style={{ margin: 0, fontSize: 36, color: "var(--mint-soft)" }}>Statistics</h1>
          <p style={{ marginTop: 6, color: "var(--slate)", fontSize: 13 }}>
            {live
              ? "Projected scoring from your drafted roster. Actuals fill after weeks post."
              : loggedIn
                ? "Select a drafted league to load team and league scoring."
                : "Season-long performance against projection and league"}
          </p>
        </div>
        <TabBar tabs={[
          { id: "performance", label: "Performance" },
          { id: "trends",      label: "Player Trends" },
        ]} value={tab} onChange={setTab} />
      </div>

      {tab === "performance" && <PerformanceGrid live={live} loggedIn={loggedIn} />}
      {tab === "trends"      && <PlayerTrendsView onSelectPlayer={onSelectPlayer} live={live} />}
    </div>
  );
}

// ============================================================
// Performance grid (Image 8) — toggleable team / league
// ============================================================
function PerformanceGrid({ live, loggedIn }) {
  const [scope, setScope] = React.useState("team");
  const colors = {
    QB: "#F2C94C", RB: "#95F9AE", WR: "#7BD9F4", TE: "#D9A6F4",
    FLEX: "#D9FFE4", DST: "#FF9E5E", K: "#A6B7AC",
  };
  const slots = { QB: 1, RB: 2, WR: 2, TE: 1, FLEX: 1, DST: 1, K: 1 };

  function projPts(players, pos) {
    const list = players || [];
    const filtered = pos === "FLEX"
      ? list.filter((p) => ["RB", "WR", "TE"].includes(p.pos))
      : list.filter((p) => p.pos === pos);
    return Math.round(filtered.reduce((sum, p) => sum + (p.ros || (p.proj || 0) * 17), 0));
  }

  const useLive = !!live;
  const liveTeam = useLive ? ["QB", "RB", "WR", "TE", "FLEX", "DST", "K"].map((pos) => {
    const d = live.positionPerformance?.[pos] || {};
    const weekly = Number(d.actual) || 0;
    const expected = Number(d.expected) || 0;
    return {
      pos,
      pts: Math.round(weekly * 17),
      proj: Math.round(expected * 17),
      color: colors[pos],
      slot: slots[pos],
    };
  }) : null;
  const liveLeague = useLive ? ["QB", "RB", "WR", "TE", "FLEX", "DST", "K"].map((pos) => {
    const d = live.positionPerformance?.[pos] || {};
    const weekly = Number(d.actual) || 0;
    const expected = Number(d.expected) || 0;
    return {
      pos,
      pts: Math.round(weekly * 17),
      proj: Math.round(expected * 17 * 0.92),
      color: colors[pos],
      slot: slots[pos],
    };
  }) : null;

  const emptyPos = ["QB", "RB", "WR", "TE", "FLEX", "DST", "K"].map((pos) => ({
    pos, pts: 0, proj: 0, color: colors[pos], slot: slots[pos],
  }));
  const teamData = liveTeam || (loggedIn ? emptyPos : [
    { pos: "QB",   pts: 248,  proj: 225, color: "#F2C94C", slot: 1 },
    { pos: "RB",   pts: 312,  proj: 320, color: "#95F9AE", slot: 2 },
    { pos: "WR",   pts: 388,  proj: 360, color: "#7BD9F4", slot: 2 },
    { pos: "TE",   pts: 152,  proj: 165, color: "#D9A6F4", slot: 1 },
    { pos: "FLEX", pts: 198,  proj: 220, color: "#D9FFE4", slot: 1 },
    { pos: "DST",  pts: 122,  proj: 130, color: "#FF9E5E", slot: 1 },
    { pos: "K",    pts: 134,  proj: 130, color: "#A6B7AC", slot: 1 },
  ]);

  const leagueData = liveLeague || (loggedIn ? emptyPos : [
    { pos: "QB",   pts: 248,  proj: 230, color: "#F2C94C", slot: 1 },
    { pos: "RB",   pts: 312,  proj: 320, color: "#95F9AE", slot: 2 },
    { pos: "WR",   pts: 388,  proj: 362, color: "#7BD9F4", slot: 2 },
    { pos: "TE",   pts: 152,  proj: 160, color: "#D9A6F4", slot: 1 },
    { pos: "FLEX", pts: 198,  proj: 218, color: "#D9FFE4", slot: 1 },
    { pos: "DST",  pts: 122,  proj: 118, color: "#FF9E5E", slot: 1 },
    { pos: "K",    pts: 134,  proj: 128, color: "#A6B7AC", slot: 1 },
  ]);

  const data = scope === "team" ? teamData : leagueData;
  const compareLabel = scope === "team" ? "vs projected" : "vs league avg";

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <TabBar tabs={[
          { id: "team",   label: "vs Projection" },
          { id: "league", label: "vs League" },
        ]} value={scope} onChange={setScope} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        {data.map(d => {
          const diff = d.proj ? ((d.pts - d.proj) / d.proj) * 100 : 0;
          const isUp = diff >= 0;
          const color = isUp ? "var(--mint)" : "var(--red)";
          return (
            <div key={d.pos} style={{
              padding: 20,
              borderRadius: 12, border: "1px solid var(--green-600)", background: "var(--green-800)",
              position: "relative", overflow: "hidden"
            }}>
              {/* color rail */}
              <div style={{ position: "absolute", left: 0, top: 0, height: "100%", width: 3, background: d.color, opacity: 0.6 }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div>
                  <span className="mono" style={{ fontSize: 10, color: "var(--slate)", textTransform: "uppercase", letterSpacing: "0.14em" }}>{d.pos}</span>
                  <span className="mono" style={{ marginLeft: 6, fontSize: 9, color: "var(--slate-dim)", padding: "1px 4px", border: "1px solid var(--green-600)", borderRadius: 3 }}>{d.slot}× slot</span>
                </div>
                <span className="mono" style={{ fontSize: 12, fontWeight: 600, color }}>
                          {isUp ? "▲" : "▼"} {Math.abs(diff).toFixed(1)}%
                </span>
              </div>

              <div style={{ marginTop: 14, display: "flex", alignItems: "baseline", gap: 6 }}>
                <span className="num" style={{ fontSize: 36, color: "var(--mint-soft)" }}>{d.pts}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--slate-dim)" }}>pts</span>
              </div>

              <div className="mono" style={{ marginTop: 6, fontSize: 11, color: "var(--slate)", letterSpacing: "0.04em" }}>
                {compareLabel}: <span style={{ color: "var(--mint-soft)" }}>{d.proj}</span>
              </div>

              <div style={{ marginTop: 14, height: 6, background: "var(--green-600)", borderRadius: 3, position: "relative", overflow: "hidden" }}>
                <div style={{
                  position: "absolute", left: 0, top: 0, height: "100%",
                  width: `${Math.min(100, (d.pts / Math.max(1, d.pts, d.proj)) * 100)}%`,
                  background: d.color, borderRadius: 3
                }} />
                <div style={{
                  position: "absolute", top: -2, height: 10, width: 2,
                  left: `${(d.proj / Math.max(1, d.pts, d.proj)) * 100}%`,
                  background: "var(--mint-soft)"
                }} title="Projected"/>
              </div>
            </div>
          );
        })}
      </div>

      {/* Total at bottom */}
      <div style={{ marginTop: 14 }} className="card">
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1fr 1fr", gap: 0, padding: "20px 24px" }}>
          <div>
            <div className="mono" style={{ fontSize: 11, color: "var(--mint)", letterSpacing: "0.14em", textTransform: "uppercase" }}>Season Total</div>
            <div className="num" style={{ marginTop: 6, fontSize: 36, color: "var(--mint)" }}>{data.reduce((s, d) => s + d.pts, 0)}</div>
            <div className="mono" style={{ marginTop: 4, fontSize: 11, color: "var(--slate)" }}>{compareLabel}: {data.reduce((s, d) => s + d.proj, 0)}</div>
          </div>
          <SmallStat label="Pts / Wk avg" value={useLive ? String((live.headline?.projectedTotal || 0).toFixed(1)) : "127.7"} delta={useLive ? "Projected" : "+2.4%"} />
          <SmallStat label="Boom weeks"   value={useLive ? "0 / 0" : "4 / 10"} delta={useLive ? "Preseason" : "40% rate"} />
          <SmallStat label="Best wk"      value={useLive ? String((live.headline?.projectedTotal || 0).toFixed(1)) : "156.7"} delta={useLive ? "Proj" : "W5"} />
          <SmallStat label="Worst wk"     value={useLive ? String(((live.headline?.projectedTotal || 0) * 0.55).toFixed(1)) : "96.1"}  delta={useLive ? "Floor" : "W3"} />
        </div>
      </div>
    </div>
  );
}

function SmallStat({ label, value, delta }) {
  return (
    <div style={{ paddingLeft: 24, borderLeft: "1px solid var(--green-600)" }}>
      <div className="mono" style={{ fontSize: 10, color: "var(--slate)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{label}</div>
      <div className="num" style={{ marginTop: 6, fontSize: 22, color: "var(--mint-soft)" }}>{value}</div>
      <div className="mono" style={{ marginTop: 4, fontSize: 11, color: "var(--slate-dim)" }}>{delta}</div>
    </div>
  );
}

// ============================================================
// Player Trends (Image 9) — weekly bars (ceiling/floor) + actual line
// ============================================================
function PlayerTrendsView({ onSelectPlayer, live }) {
  const rosterPool = (live?.roster && live.roster.length) ? live.roster : null;
  const pool = rosterPool
    || ((window.DRAFT_PLAYERS && window.DRAFT_PLAYERS.length) ? window.DRAFT_PLAYERS : (window.PLAYERS || []));
  const [search, setSearch] = React.useState("");
  const [pickId, setPickId] = React.useState(pool[0]?.id || "jchase");
  React.useEffect(() => {
    if (!pool.length) return;
    setPickId((current) => {
      if (pool.some((p) => p.id === current)) return current;
      const seed = (window.PLAYERS || []).find((p) => p.id === current);
      const hit = seed && pool.find((p) => p.name === seed.name && p.pos === seed.pos);
      return hit?.id || pool[0].id;
    });
  }, [pool.length]);
  const list = pool.filter((p) => !search || `${p.name} ${p.pos} ${p.team}`.toLowerCase().includes(search.toLowerCase()));
  const player = pool.find((p) => p.id === pickId) || list[0] || pool[0];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 16 }}>
      {/* Player picker */}
      <div className="card" style={{ padding: 18 }}>
        <div style={{ marginBottom: 12 }}>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search full player pool"
            style={{
              width: "100%", background: "var(--green-900)", border: "1px solid var(--green-600)",
              borderRadius: 8, color: "var(--mint-soft)", fontFamily: "Sora", fontSize: 13,
              padding: "9px 12px", outline: "none",
            }} />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 540, overflowY: "auto", paddingRight: 4 }}>
          {list.map(p => {
            const active = p.id === pickId;
            return (
              <button key={p.id} onClick={() => setPickId(p.id)} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
                padding: "10px 12px", borderRadius: 8,
                background: active ? "rgba(149,249,174,0.06)" : "transparent",
                border: active ? "1px solid rgba(149,249,174,0.4)" : "1px solid var(--green-600)",
                cursor: "pointer", textAlign: "left",
                transition: "all 0.12s"
              }}>
                <PlayerCell player={p} mini />
                <span className="num" style={{ fontSize: 13, color: "var(--mint)" }}>{(p.proj || 0).toFixed(1)}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Trend chart */}
      <div className="card" style={{ padding: 22 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14, flexWrap: "wrap", gap: 12 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--mint)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 4 }}>Player trend</div>
            <h2 className="display" style={{ margin: 0, fontSize: 26, color: "var(--mint-soft)" }}>{player ? player.name : "Select a player"}</h2>
            <div style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 10 }}>
              {player ? <PosPill pos={player.pos} /> : null}
              {player ? <TeamChip team={player.team} /> : null}
              <span className="mono" style={{ fontSize: 11, color: "var(--slate)" }}>{player ? `POS RK #${player.rank || "—"}` : ""}</span>
            </div>
          </div>
          <button className="btn outline" disabled={!player} onClick={() => player && onSelectPlayer(player)}>Open profile →</button>
        </div>

        {player ? <CeilingFloorChart player={player} /> : <div style={{ padding: 32, color: "var(--slate)" }}>Search the pool to open a trend chart.</div>}

        <div style={{ marginTop: 16, display: "flex", gap: 24, flexWrap: "wrap" }}>
          <Legend color="rgba(149,249,174,0.25)" label="Floor → Ceiling band" />
          <Legend color="#95F9AE" label="Actual / Projection" />
          <Legend color="#D9FFE4" label="Projection (future)" dashed />
        </div>
      </div>
    </div>
  );
}

function CeilingFloorChart({ player }) {
  if (!player) return <div style={{ padding: 24, color: "var(--slate)" }}>Select a player.</div>;
  const season = Number(window.TAPE_SEASON) === 2024 ? 2024 : 2025;
  const scoring = window.ACTIVE_DRAFT_SCORING || "ppr";
  const [tapeLog, setTapeLog] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    fetch(`/api/nfl/player-tape?name=${encodeURIComponent(player.name)}&pos=${encodeURIComponent(player.pos || "")}&season=${season}`, { cache: "no-store" })
      .then((r) => r.json())
      .then((payload) => {
        if (cancelled) return;
        const byeWeek = Number(player.byeWeek || player.bye) || null;
        const weeks = (payload.weeks || []).map((row) => {
          const proj = scoring === "std" ? row.projStd : scoring === "half" ? row.projHalf : row.projPpr;
          const actual = scoring === "std" ? row.actualStd : scoring === "half" ? row.actualHalf : row.actualPpr;
          const isBye = byeWeek && Number(row.week) === byeWeek;
          const projN = !isBye && proj != null && Number.isFinite(Number(proj)) ? Number(proj) : null;
          const actualN = !isBye && actual != null && Number.isFinite(Number(actual)) ? Number(actual) : null;
          return {
            wk: Number(row.week),
            bye: !!isBye,
            proj: projN,
            actual: actualN,
            ceiling: !isBye && row.ceiling != null ? Number(row.ceiling) : (projN != null ? +(projN * 1.35).toFixed(2) : null),
            floor: !isBye && row.floor != null ? Number(row.floor) : (projN != null ? +(projN * 0.55).toFixed(2) : null),
          };
        });
        setTapeLog(weeks);
      })
      .catch(() => { if (!cancelled) setTapeLog([]); });
    return () => { cancelled = true; };
  }, [player.name, player.pos, player.id, player.byeWeek, player.bye, season, scoring]);

  const fallback = typeof window.getGameLog === "function" ? window.getGameLog(player.id) : [];
  const log = (tapeLog && tapeLog.length) ? tapeLog : fallback;
  const weeks = (log || []).filter((g) => !g.bye);
  if (!weeks.length || weeks.every((g) => g.actual == null && g.proj == null)) {
    return <div style={{ padding: 24, color: "var(--slate)" }}>No {season} weekly scores for this player.</div>;
  }

  const w = 700, h = 280, padL = 36, padR = 14, padT = 16, padB = 28;
  const vals = weeks.flatMap((g) => [g.actual, g.proj, g.ceiling, g.floor].filter((v) => v != null && Number.isFinite(v)));
  const max = Math.max(...vals, 30) + 4;
  const min = 0;
  const range = max - min;
  const stepX = weeks.length > 1 ? (w - padL - padR) / (weeks.length - 1) : 0;

  function xFor(i) { return padL + i * stepX; }
  function yFor(v) { return h - padB - ((v - min) / range) * (h - padT - padB); }

  const bars = weeks.map((g, i) => ({
    x: xFor(i),
    week: g.wk,
    floor: g.floor,
    ceiling: g.ceiling,
    value: g.actual != null ? g.actual : g.proj,
    actual: g.actual,
    proj: g.proj,
    isFuture: g.actual == null && g.proj != null,
  }));

  const bandPts = bars.filter((b) => b.floor != null && b.ceiling != null);
  const bandPath = bandPts.length > 1
    ? [
      ...bandPts.map((b, i) => `${i === 0 ? "M" : "L"}${b.x},${yFor(b.ceiling)}`),
      ...bandPts.slice().reverse().map((b) => `L${b.x},${yFor(b.floor)}`),
      "Z",
    ].join(" ")
    : "";
  const actualBars = bars.filter((b) => b.actual != null);
  const actualPath = actualBars.map((b, i) => `${i === 0 ? "M" : "L"}${b.x},${yFor(b.actual)}`).join(" ");
  const projBars = bars.filter((b) => b.proj != null);
  const projPath = projBars.map((b, i) => `${i === 0 ? "M" : "L"}${b.x},${yFor(b.proj)}`).join(" ");

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: "block", overflow: "visible" }}>
      <defs>
        <linearGradient id="cfBand" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#95F9AE" stopOpacity="0.35" />
          <stop offset="100%" stopColor="#95F9AE" stopOpacity="0.06" />
        </linearGradient>
      </defs>

      {[0, 0.25, 0.5, 0.75, 1].map((t) => {
        const v = min + (1 - t) * range;
        const y = padT + t * (h - padT - padB);
        return (
          <g key={t}>
            <line x1={padL} y1={y} x2={w - padR} y2={y} stroke="#2A4A37" strokeDasharray="2,3" />
            <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="9" fill="#6b7d72" fontFamily="JetBrains Mono">{v.toFixed(0)}</text>
          </g>
        );
      })}

      {bandPath ? <path d={bandPath} fill="url(#cfBand)" stroke="none" /> : null}
      {projPath ? <path d={projPath} fill="none" stroke="#D9FFE4" strokeWidth="1.5" strokeDasharray="4,3" opacity="0.85" /> : null}
      {actualPath ? <path d={actualPath} fill="none" stroke="#95F9AE" strokeWidth="2.5" /> : null}

      {bars.map((b, i) => (
        b.value == null ? null : (
          <circle key={i} cx={b.x} cy={yFor(b.value)} r="3.5"
            fill={b.isFuture ? "var(--black)" : "#95F9AE"}
            stroke={b.isFuture ? "#D9FFE4" : "#050807"}
            strokeWidth="1.5" />
        )
      ))}

      {bars.map((b, i) => (
        <text key={`w${i}`} x={b.x} y={h - 8} textAnchor="middle" fontSize="10" fill="#A6B7AC" fontFamily="JetBrains Mono">W{b.week}</text>
      ))}
    </svg>
  );
}

Object.assign(window, { StatisticsView });
