// Expanded row detail drawer
const { useMemo: useMemoExp } = React;

function StatBar({ label, away, home, better, palette, awayColor, homeColor }) {
  const isNum = typeof away === "number" && typeof home === "number";
  let awayPct = 50, homePct = 50;
  if (isNum) {
    const total = Math.abs(away) + Math.abs(home) || 1;
    awayPct = (Math.abs(away) / total) * 100;
    homePct = 100 - awayPct;
  }
  const awayIsBetter = better === "away";
  const homeIsBetter = better === "home";
  return (
    <div style={{ display: "grid", gridTemplateColumns: "60px 1fr 60px 1fr 60px", alignItems: "center", gap: 8, fontSize: 11 }}>
      <div style={{ color: awayIsBetter ? palette.up : palette.text, textAlign: "right", fontWeight: awayIsBetter ? 600 : 400, fontVariantNumeric: "tabular-nums" }}>{away}</div>
      <div style={{ height: 6, background: palette.panel2, display: "flex", justifyContent: "flex-end", borderRadius: 1, overflow: "hidden" }}>
        <div style={{ width: `${awayPct}%`, background: awayIsBetter ? palette.up : palette.dim, opacity: awayIsBetter ? 0.9 : 0.4 }} />
      </div>
      <div style={{ color: palette.dim, textAlign: "center", fontSize: 10, letterSpacing: 0.5 }}>{label}</div>
      <div style={{ height: 6, background: palette.panel2, display: "flex", borderRadius: 1, overflow: "hidden" }}>
        <div style={{ width: `${homePct}%`, background: homeIsBetter ? palette.up : palette.dim, opacity: homeIsBetter ? 0.9 : 0.4 }} />
      </div>
      <div style={{ color: homeIsBetter ? palette.up : palette.text, textAlign: "left", fontWeight: homeIsBetter ? 600 : 400, fontVariantNumeric: "tabular-nums" }}>{home}</div>
    </div>
  );
}

function Panel({ title, palette, children, flex, minWidth }) {
  return (
    <div style={{
      background: palette.panel, border: `1px solid ${palette.border}`,
      padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8,
      flex: flex || "1 1 auto", minWidth: minWidth || 0
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: `1px solid ${palette.border}`, paddingBottom: 6 }}>
        <div style={{ color: palette.accent, fontSize: 10, letterSpacing: 1.5, fontWeight: 600 }}>{title}</div>
      </div>
      {children}
    </div>
  );
}

// Stat comparison
function StatCompare({ game, palette }) {
  return (
    <Panel title="TEAM COMPARISON" palette={palette} flex="1 1 420px" minWidth={380}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: palette.dim, padding: "0 0 4px" }}>
        <div style={{ color: game.away.color === "#FFCD00" ? palette.text : palette.text, fontWeight: 600 }}>◆ {game.away.abbr}</div>
        <div>OFFENSE</div>
        <div style={{ color: palette.text, fontWeight: 600 }}>{game.home.abbr} ◆</div>
      </div>
      {game.stats.off.map(s => <StatBar key={s.label} {...s} palette={palette} />)}
      <div style={{ color: palette.dim, fontSize: 10, padding: "6px 0 0", borderTop: `1px dashed ${palette.border}`, marginTop: 4, textAlign: "center", letterSpacing: 1 }}>DEFENSE</div>
      {game.stats.def.map(s => <StatBar key={s.label} {...s} palette={palette} />)}
    </Panel>
  );
}

// Advanced metrics
function AdvancedPanel({ game, palette }) {
  const a = game.advanced.away, h = game.advanced.home;
  const rows = [
    { label: "SP+",   a: a.sp,  h: h.sp,  suffix: "" },
    { label: "FPI",   a: a.fpi, h: h.fpi, suffix: "" },
    { label: "FEI",   a: a.fei, h: h.fei, suffix: "" },
    { label: "OFF",   a: a.off, h: h.off, suffix: "" },
    { label: "DEF",   a: a.def, h: h.def, suffix: "" }
  ];
  return (
    <Panel title="ADVANCED" palette={palette} flex="0 1 220px">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 40px 1fr", fontSize: 11, gap: "4px 8px", alignItems: "center" }}>
        <div style={{ color: palette.text, fontWeight: 600, textAlign: "right" }}>{game.away.abbr}</div>
        <div />
        <div style={{ color: palette.text, fontWeight: 600 }}>{game.home.abbr}</div>
        {rows.map(r => {
          const aBet = r.a > r.h;
          return (
            <React.Fragment key={r.label}>
              <div style={{ color: aBet ? palette.up : palette.text, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{typeof r.a === "number" ? r.a.toFixed(r.label === "FEI" ? 2 : 1) : r.a}</div>
              <div style={{ color: palette.dim, fontSize: 9, textAlign: "center", letterSpacing: 1 }}>{r.label}</div>
              <div style={{ color: !aBet ? palette.up : palette.text, textAlign: "left", fontVariantNumeric: "tabular-nums" }}>{typeof r.h === "number" ? r.h.toFixed(r.label === "FEI" ? 2 : 1) : r.h}</div>
            </React.Fragment>
          );
        })}
      </div>
    </Panel>
  );
}

// Line movement
function LineMovement({ game, palette }) {
  const data = game.spreadHistory;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const W = 220, H = 60;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * W;
    const y = H - ((v - min) / range) * (H - 10) - 5;
    return { x, y, v };
  });
  const poly = pts.map(p => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");
  return (
    <Panel title="LINE MOVEMENT" palette={palette} flex="0 1 260px">
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: palette.dim }}>
        <span>OPEN <span style={{ color: palette.text }}>{fmtSpread(data[0])}</span></span>
        <span>NOW <span style={{ color: palette.accent }}>{fmtSpread(data[data.length - 1])}</span></span>
      </div>
      <svg width={W} height={H} style={{ display: "block" }}>
        <line x1="0" y1={H - 5} x2={W} y2={H - 5} stroke={palette.border} />
        <polyline points={poly} fill="none" stroke={palette.accent} strokeWidth="1.5" />
        {pts.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r="2" fill={palette.accent} />)}
      </svg>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9, color: palette.dimmer, letterSpacing: 1 }}>
        <span>MON</span><span>TUE</span><span>WED</span><span>THU</span><span>FRI</span><span>NOW</span>
      </div>
    </Panel>
  );
}

// Public vs sharp
function MoneyPanel({ game, palette }) {
  const { public: pub, sharpMoney: shp } = game;
  const Bar = ({ title, left, right, palette }) => (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: palette.dim, marginBottom: 2 }}>
        <span style={{ color: palette.text }}>{title}</span>
        <span>{game.away.abbr} {left}% / {right}% {game.home.abbr}</span>
      </div>
      <div style={{ height: 8, display: "flex", background: palette.panel2, border: `1px solid ${palette.border}` }}>
        <div style={{ width: `${left}%`, background: palette.accent2, opacity: 0.8 }} />
        <div style={{ width: `${right}%`, background: palette.warn, opacity: 0.8 }} />
      </div>
    </div>
  );
  const divergence = Math.abs(pub.away - shp.away);
  return (
    <Panel title="PUBLIC × SHARP" palette={palette} flex="0 1 260px">
      <Bar title="PUBLIC BETS" left={pub.away} right={pub.home} palette={palette} />
      <Bar title="SHARP $" left={shp.away} right={shp.home} palette={palette} />
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 4, borderTop: `1px dashed ${palette.border}`, fontSize: 10, color: palette.dim }}>
        <span>DIVERGENCE</span>
        <span style={{ color: divergence > 20 ? palette.warn : palette.dim, fontWeight: 600 }}>{divergence}% {divergence > 20 ? "◆ RLM" : ""}</span>
      </div>
    </Panel>
  );
}

// Model edge
function ModelPanel({ game, palette }) {
  const diff = Math.abs(game.modelLine - game.spread.current);
  const modelFavorsAway = game.modelLine < 0;
  const dir = game.edge > 0 ? "up" : game.edge < 0 ? "down" : "neutral";
  return (
    <Panel title="MODEL × MARKET" palette={palette} flex="0 1 240px">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, fontSize: 11 }}>
        <div style={{ padding: 8, background: palette.panel2, border: `1px solid ${palette.border}` }}>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>MARKET</div>
          <div style={{ color: palette.text, fontSize: 16, fontWeight: 600 }}>{game.spread.favorite} {fmtSpread(game.spread.current)}</div>
        </div>
        <div style={{ padding: 8, background: palette.panel2, border: `1px solid ${palette.border}` }}>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>MODEL</div>
          <div style={{ color: palette.accent, fontSize: 16, fontWeight: 600 }}>{game.spread.favorite} {fmtSpread(game.modelLine)}</div>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderTop: `1px dashed ${palette.border}`, fontSize: 11 }}>
        <span style={{ color: palette.dim }}>EDGE</span>
        <span style={{ color: dir === "up" ? palette.up : dir === "down" ? palette.down : palette.dim, fontWeight: 700 }}>
          {fmtEdge(game.edge)} pts {dir === "up" ? "◢" : dir === "down" ? "◣" : "—"}
        </span>
      </div>
      <div style={{ fontSize: 10, color: palette.dim, lineHeight: 1.5 }}>
        {dir === "up"
          ? <>Model sees value on <span style={{ color: palette.up }}>{modelFavorsAway ? game.away.abbr : game.home.abbr} {fmtSpread(game.spread.current)}</span>.</>
          : dir === "down"
            ? <>Model fades the favorite. Lean <span style={{ color: palette.down }}>{modelFavorsAway ? game.home.abbr : game.away.abbr} {fmtSpread(-game.spread.current)}</span>.</>
            : <>Model matches market. No edge.</>}
      </div>
    </Panel>
  );
}

// Situational
function SituationalPanel({ game, palette }) {
  const items = [
    { label: "REST DIFF",    v: game.situational.restDiff, fmt: v => `${v > 0 ? "+" : ""}${v}d`, hot: game.situational.restDiff !== 0 },
    { label: "TRAVEL",       v: game.situational.travelMiles, fmt: v => `${v.toLocaleString()}mi`, hot: game.situational.travelMiles > 1000 },
    { label: "REVENGE",      v: game.situational.revenge, fmt: v => v ? "YES" : "NO", hot: game.situational.revenge },
    { label: "SHORT WK",     v: game.situational.shortWeek, fmt: v => v ? "YES" : "NO", hot: game.situational.shortWeek },
    { label: "LOOKAHEAD",    v: game.situational.lookahead, fmt: v => v ? "YES" : "NO", hot: game.situational.lookahead }
  ];
  return (
    <Panel title="SITUATIONAL" palette={palette} flex="0 1 200px">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 12px", fontSize: 10 }}>
        {items.map(it => (
          <div key={it.label} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span style={{ color: palette.dim, letterSpacing: 0.5 }}>{it.label}</span>
            <span style={{ color: it.hot ? palette.warn : palette.text, fontWeight: 600 }}>{it.fmt(it.v)}</span>
          </div>
        ))}
      </div>
    </Panel>
  );
}

// Weather
function WeatherPanel({ game, palette }) {
  const w = game.weather;
  const concern = w.condition !== "CLEAR" || w.wind > 15 || w.precip > 20 || w.temp < 35;
  return (
    <Panel title="WEATHER" palette={palette} flex="0 1 180px">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 8px", fontSize: 11 }}>
        <div>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>COND</div>
          <div style={{ color: concern ? palette.warn : palette.text, fontWeight: 600 }}>{w.condition}</div>
        </div>
        <div>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>TEMP</div>
          <div style={{ color: w.temp < 35 ? palette.warn : palette.text, fontWeight: 600 }}>{w.temp}°F</div>
        </div>
        <div>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>WIND</div>
          <div style={{ color: w.wind > 15 ? palette.warn : palette.text, fontWeight: 600 }}>{w.wind}mph</div>
        </div>
        <div>
          <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1 }}>PRECIP</div>
          <div style={{ color: w.precip > 20 ? palette.warn : palette.text, fontWeight: 600 }}>{w.precip}%</div>
        </div>
      </div>
    </Panel>
  );
}

// Injuries
function InjuryPanel({ game, palette }) {
  const render = (list, abbr) => (
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1, marginBottom: 4 }}>{abbr}</div>
      {list.length === 0
        ? <div style={{ color: palette.dimmer, fontSize: 10 }}>— Clean —</div>
        : list.map((i, idx) => (
            <div key={idx} style={{ display: "flex", justifyContent: "space-between", fontSize: 10, marginBottom: 3 }}>
              <span style={{ color: palette.text }}>
                <span style={{ color: palette.dim, width: 26, display: "inline-block" }}>{i.pos}</span>
                {i.name}
              </span>
              <span style={{
                color: i.status === "D" ? palette.down : i.status === "Q" ? palette.warn : palette.up,
                fontWeight: 700
              }}>{i.status}</span>
            </div>
          ))}
    </div>
  );
  return (
    <Panel title="INJURY REPORT" palette={palette} flex="0 1 280px">
      <div style={{ display: "flex", gap: 14 }}>
        {render(game.injuries.away, game.away.abbr)}
        <div style={{ width: 1, background: palette.border }} />
        {render(game.injuries.home, game.home.abbr)}
      </div>
    </Panel>
  );
}

// H2H
function H2HPanel({ game, palette }) {
  return (
    <Panel title="H2H LAST 5" palette={palette} flex="1 1 280px">
      <div style={{ display: "grid", gridTemplateColumns: "32px 1fr 70px 50px", fontSize: 10, gap: "3px 8px" }}>
        {game.h2h.map((h, i) => (
          <React.Fragment key={i}>
            <div style={{ color: palette.dim }}>{h.year}</div>
            <div style={{ color: palette.text }}>{h.score}</div>
            <div style={{ color: palette.dim }}>{h.ats}</div>
            <div style={{
              color: h.cover === "away" ? palette.accent2 : h.cover === "home" ? palette.warn : palette.dimmer,
              fontWeight: 600, letterSpacing: 0.5
            }}>
              {h.cover === "away" ? `${game.away.abbr} ✓` : h.cover === "home" ? `${game.home.abbr} ✓` : "—"}
            </div>
          </React.Fragment>
        ))}
      </div>
    </Panel>
  );
}

// ATS
function ATSPanel({ game, palette }) {
  const rows = ["overall", "home", "away", "fav", "dog"];
  const labels = { overall: "OVERALL", home: "HOME", away: "ROAD", fav: "AS FAV", dog: "AS DOG" };
  return (
    <Panel title="ATS RECORD" palette={palette} flex="0 1 200px">
      <div style={{ display: "grid", gridTemplateColumns: "60px 1fr 1fr", fontSize: 11, gap: "3px 8px", alignItems: "center" }}>
        <div />
        <div style={{ color: palette.text, fontWeight: 600, textAlign: "center", fontSize: 10 }}>{game.away.abbr}</div>
        <div style={{ color: palette.text, fontWeight: 600, textAlign: "center", fontSize: 10 }}>{game.home.abbr}</div>
        {rows.map(r => (
          <React.Fragment key={r}>
            <div style={{ color: palette.dim, fontSize: 10, letterSpacing: 0.5 }}>{labels[r]}</div>
            <div style={{ color: palette.text, textAlign: "center", fontVariantNumeric: "tabular-nums" }}>{game.ats.away[r]}</div>
            <div style={{ color: palette.text, textAlign: "center", fontVariantNumeric: "tabular-nums" }}>{game.ats.home[r]}</div>
          </React.Fragment>
        ))}
      </div>
    </Panel>
  );
}

// Recent form
function FormPanel({ game, palette }) {
  const row = (list, abbr) => (
    <div>
      <div style={{ color: palette.dim, fontSize: 9, letterSpacing: 1, marginBottom: 4 }}>{abbr} LAST 5</div>
      <div style={{ display: "flex", gap: 3 }}>
        {list.map((g, i) => (
          <div key={i} title={`vs ${g.o}: ${g.s}`} style={{
            flex: 1, padding: "4px 2px", textAlign: "center",
            background: g.r === "W" ? `${palette.up}20` : `${palette.down}20`,
            border: `1px solid ${g.r === "W" ? palette.up : palette.down}55`,
            fontSize: 10
          }}>
            <div style={{ color: g.r === "W" ? palette.up : palette.down, fontWeight: 700 }}>{g.r}</div>
            <div style={{ color: palette.dim, fontSize: 8 }}>{g.o}</div>
          </div>
        ))}
      </div>
    </div>
  );
  return (
    <Panel title="RECENT FORM" palette={palette} flex="1 1 280px">
      {row(game.form.away, game.away.abbr)}
      {row(game.form.home, game.home.abbr)}
    </Panel>
  );
}

// Key matchups
function MatchupsPanel({ game, palette }) {
  const sev = {
    strong: { color: palette.up, dot: "●●●" },
    mod:    { color: palette.warn, dot: "●●○" },
    mild:   { color: palette.dim, dot: "●○○" },
    none:   { color: palette.dimmer, dot: "○○○" }
  };
  return (
    <Panel title="KEY MATCHUPS" palette={palette} flex="1 1 360px">
      {game.matchups.map((m, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 60px 40px", gap: 8, alignItems: "center", padding: "4px 0", borderBottom: i < game.matchups.length - 1 ? `1px dashed ${palette.border}` : "none" }}>
          <div>
            <div style={{ color: palette.text, fontSize: 11, fontWeight: 500 }}>{m.title}</div>
            <div style={{ color: palette.dim, fontSize: 10 }}>{m.note}</div>
          </div>
          <div style={{
            color: m.edge === "EVEN" || m.edge === "OVER" ? palette.accent2 : palette.accent,
            fontSize: 11, fontWeight: 700, textAlign: "right"
          }}>{m.edge}</div>
          <div style={{ color: sev[m.severity].color, fontSize: 10, textAlign: "right", fontFamily: "monospace" }}>
            {sev[m.severity].dot}
          </div>
        </div>
      ))}
    </Panel>
  );
}

// Full expanded drawer
function ExpandedRow({ game, palette }) {
  return (
    <div style={{
      background: palette.bg,
      borderTop: `1px solid ${palette.accent}55`,
      borderBottom: `1px solid ${palette.border}`,
      padding: "12px 16px", display: "flex", flexDirection: "column", gap: 10
    }}>
      {/* Header strip */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 10, color: palette.dim, letterSpacing: 1 }}>
        <div style={{ display: "flex", gap: 12 }}>
          <span>VENUE <span style={{ color: palette.text }}>{game.venue}</span></span>
          <span>·</span>
          <span>CONF <span style={{ color: conferenceColor(game.home.conf) }}>{game.away.conf}/{game.home.conf}</span></span>
          <span>·</span>
          <span>ID <span style={{ color: palette.text }}>{game.id}</span></span>
        </div>
        <div style={{ color: palette.accent, fontSize: 10, letterSpacing: 2 }}>▼ EXPANDED DETAIL</div>
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        <ModelPanel game={game} palette={palette} />
        <LineMovement game={game} palette={palette} />
        <MoneyPanel game={game} palette={palette} />
        <AdvancedPanel game={game} palette={palette} />
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        <StatCompare game={game} palette={palette} />
        <MatchupsPanel game={game} palette={palette} />
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        <FormPanel game={game} palette={palette} />
        <H2HPanel game={game} palette={palette} />
        <ATSPanel game={game} palette={palette} />
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        <InjuryPanel game={game} palette={palette} />
        <SituationalPanel game={game} palette={palette} />
        <WeatherPanel game={game} palette={palette} />
      </div>
    </div>
  );
}

Object.assign(window, {
  StatBar, Panel, StatCompare, AdvancedPanel, LineMovement, MoneyPanel,
  ModelPanel, SituationalPanel, WeatherPanel, InjuryPanel, H2HPanel,
  ATSPanel, FormPanel, MatchupsPanel, ExpandedRow
});
