'use client';

import { useEffect, useState } from 'react';
import SportBadge from '@/components/vyndr/SportBadge';
import SectionHead from '@/components/vyndr/SectionHead';
import { moveColor, moveLabel } from '@/lib/futuresMove';

/* ============================================================
   FuturesBoard (Wave 2B — Offseason Hub). The never-dark FUTURES board: REAL
   championship / win-total / award markets from `/api/futures/:sport`.

   HONESTY (Wave 3 line): futures are TRACKED, NOT GRADED — season-long
   grading is a different model that does not exist yet. So this board SHOWS
   prices + movement and carries an explicit "TRACKED · NOT GRADED" label. It
   NEVER renders a grade on a future, and a price MOVE is shown ONLY when the
   backend supplies one (never fabricated). Movement colors follow the
   contract (shortening→green / drifting→amber / flat→dim) and NEVER red.

   SELF-HIDES when there are no markets (markets:[]). Prices are mono +
   tabular (data-is-mono brand rule).
   ============================================================ */

interface Selection {
  name: string;
  price: number | string;
  prevPrice?: number | string;
  move?: 'shortening' | 'drifting' | 'flat';
}
interface FuturesMarket {
  key: string;
  title: string;
  selections: Selection[];
}

export interface FuturesBoardProps {
  sport: string;
}

const card: React.CSSProperties = { background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 10, padding: 16 };

// American-odds display: a signed integer keeps its sign; anything else prints
// as-is (absent beats a fabricated/mis-converted number).
function fmtPrice(price: number | string): string {
  if (price == null || price === '') return '—';
  if (typeof price === 'number' && Number.isFinite(price)) {
    return price > 0 ? `+${price}` : String(price);
  }
  const s = String(price);
  return /^-?\d+$/.test(s) && Number(s) > 0 ? `+${s}` : s;
}

export default function FuturesBoard({ sport }: FuturesBoardProps) {
  const [markets, setMarkets] = useState<FuturesMarket[] | null>(null);

  useEffect(() => {
    let cancelled = false;
    setMarkets(null);
    fetch(`/api/futures/${encodeURIComponent(sport)}`)
      .then((r) => (r.ok ? r.json() : { markets: [] }))
      .then((d) => { if (!cancelled) setMarkets(Array.isArray(d?.markets) ? d.markets : []); })
      .catch(() => { if (!cancelled) setMarkets([]); });
    return () => { cancelled = true; };
  }, [sport]);

  const list = markets || [];
  // SELF-HIDE: no markets (empty feed or still loading).
  if (list.length === 0) return null;

  return (
    <div style={{ marginTop: 28 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, flexWrap: 'wrap' }}>
        <SectionHead>FUTURES BOARD</SectionHead>
        <SportBadge sport={sport} size="sm" />
        {/* The honesty line — futures are shown/tracked, not model-graded. */}
        <span className="mono" style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', padding: '2px 7px', borderRadius: 3, color: 'var(--text-2)', border: '1px solid var(--border)' }}>
          TRACKED · NOT GRADED
        </span>
      </div>
      <p className="mono" style={{ margin: '0 0 14px', fontSize: 11, color: 'var(--text-2)' }}>
        Live book prices, tracked over time. VYNDR does not grade futures — season-long grading is a separate model.
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 12 }}>
        {list.map((m) => (
          <div key={m.key} style={card}>
            <div className="label" style={{ marginBottom: 11 }}>{m.title}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {(Array.isArray(m.selections) ? m.selections : []).map((sel, i) => {
                const label = moveLabel(sel.move);
                return (
                  <div key={`${sel.name}-${i}`} style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                    <span style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sel.name}</span>
                    {/* Movement — ONLY when the backend supplied a `move`. */}
                    {label && (
                      <span className="mono" style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.05em', color: moveColor(sel.move) }}>{label}</span>
                    )}
                    <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums', minWidth: 54, textAlign: 'right' }}>{fmtPrice(sel.price)}</span>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
