// Main prototype for FBS Advisor terminal
const { useState, useMemo, useEffect, useRef } = React;

const { TV_NETWORKS: _TVN, CONFERENCES: _CONFS, WINDOWS: _WINS } = window.FBS_DATA;

// ---------------- Tweaks / palette ----------------
const PALETTES = {
  neon: {
    name: "NEON",
    bg: "#0A0A0A", panel: "#111114", panel2: "#16161A", border: "#22252B",
    text: "#E6E8EA", dim: "#7A8089", dimmer: "#4A5059",
    accent: "#FFB020", accent2: "#00E0FF",
    up: "#00FF88", down: "#FF3355", neutral: "#7A8089", warn: "#FFB020"
  },
  classic: {
    name: "CLASSIC",
    bg: "#050300", panel: "#0C0A05", panel2: "#141008", border: "#2A230F",
    text: "#FFB347", dim: "#8A6E2E", dimmer: "#4E3E18",
    accent: "#FFD166", accent2: "#FF8A3C",
    up: "#66FF66", down: "#FF5050", neutral: "#8A6E2E", warn: "#FFCC33"
  },
  muted: {
    name: "MUTED",
    bg: "#0E0F11", panel: "#15171A", panel2: "#1B1E22", border: "#262A30",
    text: "#D8DCDF", dim: "#7A828B", dimmer: "#454B53",
    accent: "#C8AA6E", accent2: "#7CA8D4",
    up: "#8FBF8F", down: "#C77878", neutral: "#7A828B", warn: "#C8AA6E"
  }
};

const DENSITIES = {
  tight:   { row: 30, pad: "4px 10px", font: 12 },
  regular: { row: 36, pad: "6px 12px", font: 13 },
  comfy:   { row: 42, pad: "8px 14px", font: 13 }
};

// ---------------- Helpers ----------------
const fmtSpread = (v) => (v > 0 ? "+" : "") + v.toFixed(1);
const fmtML = (v) => (v > 0 ? "+" : "") + v;
const fmtEdge = (v) => (v > 0 ? "+" : "") + v.toFixed(1);

const conferenceColor = (c) => ({ SEC: "#FFB020", B1G: "#00E0FF", ACC: "#FF3355", B12: "#A855F7", IND: "#7A8089" }[c] || "#7A8089");

const gradeColor = (g, p) => {
  if (g === "A") return p.up;
  if (g === "B") return p.accent2;
  if (g === "C") return p.warn;
  if (g === "D") return p.dim;
  return p.down;
};

// ---------------- Signal Dots ----------------
function SignalDots({ game, palette }) {
  const s = game.signals;
  const dots = [
    { key: "SHP", active: !!s.sharp, tone: s.sharp === "away" ? "away" : s.sharp === "home" ? "home" : null, tip: s.sharp ? `Sharp money ${s.sharp === "away" ? game.away.abbr : game.home.abbr}` : "No sharp indicator" },
    { key: "RLM", active: s.rlm, tone: s.rlm ? "warn" : null, tip: s.rlm ? "Reverse line movement" : "No RLM" },
    { key: "WX",  active: s.weather === "concern", tone: s.weather === "concern" ? "down" : null, tip: s.weather === "concern" ? "Weather concern" : "Weather clear" },
    { key: "RST", active: s.rest !== 0, tone: s.rest > 0 ? "up" : s.rest < 0 ? "down" : null, tip: s.rest !== 0 ? `Rest ${s.rest > 0 ? "+" : ""}${s.rest}d` : "Even rest" },
    { key: "EDG", active: s.edgeGrade === "strong" || s.edgeGrade === "mild-fade", tone: s.edgeGrade === "strong" ? "up" : s.edgeGrade === "mild-fade" ? "down" : null, tip: `Model edge: ${s.edgeGrade}` }
  ];
  const color = (t) => {
    if (!t) return palette.dimmer;
    if (t === "away") return palette.accent2;
    if (t === "home") return palette.warn;
    if (t === "up") return palette.up;
    if (t === "down") return palette.down;
    if (t === "warn") return palette.warn;
    return palette.dim;
  };
  return (
    <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
      {dots.map(d => (
        <div key={d.key} title={d.tip} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2, cursor: "help" }}>
          <div style={{
            width: 7, height: 7, borderRadius: "50%",
            background: color(d.tone),
            boxShadow: d.active ? `0 0 6px ${color(d.tone)}` : "none",
            opacity: d.active ? 1 : 0.35
          }} />
          <div style={{ fontSize: 8, color: d.active ? color(d.tone) : palette.dimmer, letterSpacing: 0.5, fontWeight: 600 }}>{d.key}</div>
        </div>
      ))}
    </div>
  );
}

// ---------------- Sparkline ----------------
function Sparkline({ data, palette, w = 80, h = 20, color }) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * h;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  const last = data[data.length - 1], first = data[0];
  const c = color || (last < first ? palette.down : last > first ? palette.up : palette.dim);
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      <polyline points={pts} fill="none" stroke={c} strokeWidth="1.25" />
      <circle cx={w} cy={h - ((last - min) / range) * h} r="2" fill={c} />
    </svg>
  );
}

// ---------------- Spread cell with movement ----------------
function SpreadCell({ game, palette }) {
  const { open, current, favorite, movement } = game.spread;
  const arrow = movement === "up" ? "▲" : movement === "down" ? "▼" : "—";
  const arrowColor = movement === "up" ? palette.up : movement === "down" ? palette.down : palette.dim;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{ color: palette.dim, fontSize: 10 }}>{favorite}</div>
      <div style={{ color: palette.text, fontWeight: 600 }}>{fmtSpread(current)}</div>
      <div style={{ color: arrowColor, fontSize: 9 }}>{arrow}</div>
      <div style={{ color: palette.dimmer, fontSize: 10 }}>{fmtSpread(open)}</div>
      <Sparkline data={game.spreadHistory} palette={palette} w={44} h={14} />
    </div>
  );
}

// ---------------- Totals cell ----------------
function TotalCell({ game, palette }) {
  const { open, current, movement } = game.total;
  const arrow = movement === "up" ? "▲" : movement === "down" ? "▼" : "—";
  const arrowColor = movement === "up" ? palette.up : movement === "down" ? palette.down : palette.dim;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <div style={{ color: palette.text, fontWeight: 600 }}>{current.toFixed(1)}</div>
      <div style={{ color: arrowColor, fontSize: 9 }}>{arrow}</div>
      <div style={{ color: palette.dimmer, fontSize: 10 }}>{open.toFixed(1)}</div>
    </div>
  );
}

// ---------------- Team Chip ----------------
function TeamChip({ team, side, palette }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
      <div style={{
        width: 14, height: 14, borderRadius: 2, background: team.color,
        border: `1px solid ${palette.border}`, flexShrink: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 8, color: "#fff", fontWeight: 700, letterSpacing: -0.3
      }}>
        {team.abbr.slice(0, 2)}
      </div>
      <div style={{ color: palette.dimmer, fontSize: 10, width: 18, textAlign: "right" }}>
        {team.rank ? team.rank : ""}
      </div>
      <div style={{ color: palette.text, fontWeight: 600, fontSize: 13 }}>{team.abbr}</div>
      <div style={{ color: palette.dim, fontSize: 10 }}>{team.record}</div>
    </div>
  );
}

// ---------------- Matchup cell ----------------
function MatchupCell({ game, palette }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
      <TeamChip team={game.away} side="away" palette={palette} />
      <div style={{ color: palette.dimmer, fontSize: 10 }}>@</div>
      <TeamChip team={game.home} side="home" palette={palette} />
    </div>
  );
}

Object.assign(window, { PALETTES, DENSITIES, fmtSpread, fmtML, fmtEdge, conferenceColor, gradeColor, SignalDots, Sparkline, SpreadCell, TotalCell, MatchupCell, TeamChip });
