'use client';

import GradeBadge from '@/components/vyndr/GradeBadge';
import TeamChip from '@/components/vyndr/TeamChip';
import { playerHref } from '@/lib/playerHref';

/**
 * MobileEdgeBoard (Rev 3, mobile screen 01) — Design's FLAT edge-ranked board.
 * All graded props across every game on one ranked list, sorted by edge, with
 * the ranked opacity ramp (1 → .55 down the board), a green inset border on the
 * top reads, matchup chips, and the edge% as the one bold mono hero per row
 * (green +, red −). Fed by slateAdapter.flattenToEdgeBoard — this is pure
 * presentation. Renders on phones (<768px); desktop keeps the game-grouped cards.
 */

export interface EdgeBoardRow {
  rank: number;
  player: string;
  team?: string;
  stat: string;
  line: number | string;
  side: string; // 'O' | 'U'
  grade: string;
  edge: number | null;
  sport: string;
  away: string;
  home: string;
  live?: boolean;
  outcome?: { result?: string } | null;
}

// Design's ranked opacity ramp: top two full, then progressively dim.
function rampOpacity(rank: number): number {
  if (rank <= 2) return 1;
  if (rank === 3) return 1;      // live row reads full in Design
  if (rank === 4) return 0.85;
  if (rank === 5) return 0.7;
  return Math.max(0.5, 0.7 - (rank - 5) * 0.06);
}

// A real prop-market edge (model prob − implied prob) is single-digit, rarely
// past ~15%, never past ~40. Values beyond that are not a market edge — they're
// the pipeline's miscalibrated placeholder (seen live: 60/100/140). Rendering
// "+140%" would fabricate a signal, so we show it absent. Backend fix pending.
const SANE_EDGE_MAX = 40;
function EdgeCell({ edge }: { edge: number | null }) {
  if (edge == null || Math.abs(edge) > SANE_EDGE_MAX) {
    return <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-2)', width: 48, textAlign: 'right' }}>—</span>;
  }
  const pos = edge >= 0;
  return (
    <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: pos ? 'var(--g-a)' : 'var(--miss)', width: 48, textAlign: 'right' }}>
      {pos ? '+' : ''}{edge.toFixed(1)}%
    </span>
  );
}

export default function MobileEdgeBoard({
  rows,
  breadth,
  clv = null,
}: {
  rows: EdgeBoardRow[];
  breadth: { edges: number; games: number };
  clv?: string | null;
}) {
  if (!Array.isArray(rows) || rows.length === 0) return null;
  return (
    <div className="mobile-edge-board">
      {/* Breadth strip — EDGES · AVG CLV · GAMES. CLV honest '—' when absent. */}
      <div className="mono" style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '10px 16px', borderBottom: '1px solid var(--bg-2)', fontSize: 9.5, letterSpacing: '0.08em', color: 'var(--text-2)' }}>
        <span>EDGES <span style={{ color: 'var(--text-0)', fontWeight: 700, fontSize: 11 }}>{breadth.edges}</span></span>
        <span>AVG CLV <span style={{ color: clv ? 'var(--g-a)' : 'var(--text-2)', fontWeight: 700, fontSize: 11 }}>{clv || '—'}</span></span>
        <span style={{ marginLeft: 'auto' }}>{breadth.games} GAMES</span>
      </div>

      {/* EDGE BOARD header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px 8px' }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.24em', color: 'var(--text-0)', fontWeight: 700 }}>EDGE BOARD</span>
        <span className="mono" style={{ fontSize: 8.5, letterSpacing: '0.14em', color: 'var(--text-2)' }}>EDGE ▼</span>
      </div>

      {/* Ranked rows */}
      {rows.map((r) => {
        const top = r.rank === 1;
        const inset = r.rank === 1 ? 'inset 2px 0 0 rgba(0,212,160,.55)' : r.rank <= 3 ? 'inset 2px 0 0 rgba(0,212,160,.4)' : 'none';
        const sideCh = String(r.side || 'O').toUpperCase().startsWith('U') ? 'u' : 'o';
        return (
          <a
            key={`${r.player}-${r.stat}-${r.line}-${r.rank}`}
            href={playerHref(r.player, r.sport)}
            style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px',
              borderTop: '1px solid var(--hairline)', boxShadow: inset,
              opacity: rampOpacity(r.rank), color: 'inherit', textDecoration: 'none',
            }}
          >
            <span className="mono" style={{ fontSize: 10, fontWeight: top ? 700 : 600, width: 16, color: top ? 'var(--g-a)' : 'var(--text-2)' }}>
              {String(r.rank).padStart(2, '0')}
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: r.rank <= 4 ? 700 : 600 }}>
                {r.player} <span style={{ color: 'var(--text-1)', fontWeight: 500 }}>{sideCh}{r.line} {r.stat}</span>
              </div>
              <div className="mono" style={{ fontSize: 8, letterSpacing: '0.1em', color: r.live ? 'var(--g-a)' : 'var(--text-2)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap', overflow: 'hidden' }}>
                {r.live && <span className="live-dot" style={{ background: 'var(--g-a)', width: 5, height: 5 }} />}
                {String(r.sport || '').toUpperCase()} ·
                <TeamChip team={r.away} sport={r.sport} size={10} style={{ fontSize: 8 }} /> @
                <TeamChip team={r.home} sport={r.sport} size={10} style={{ fontSize: 8 }} />
              </div>
            </div>
            <GradeBadge grade={r.grade} />
            <EdgeCell edge={r.edge} />
          </a>
        );
      })}
    </div>
  );
}
