// Detail overlays: MatchDetail + NewsDetail
// MatchDetail consume /api/match?id=NNN para datos reales (eventos, alineaciones, stats)

const MATCH_API_BASE = window.REALE_API_BASE
  ?? ((location.hostname === 'localhost' && location.port === '5174')
        ? 'http://localhost:3001'
        : '');

function useMatchDetail(matchId) {
  const [state, setState] = React.useState({ status: 'idle', data: null, error: null });

  React.useEffect(() => {
    if (!matchId) return;
    // Extraer numero del id. Los fixtures vienen como "F1158944", los resultados como "R1159025"
    // y los partidos del prototipo viejo como "L1", "C1", etc (sin numero parseable).
    const numId = String(matchId).replace(/^[A-Za-z]+/, '');
    if (!/^\d+$/.test(numId)) {
      setState({ status: 'idle', data: null, error: null });
      return;
    }
    let cancelled = false;
    setState({ status: 'loading', data: null, error: null });
    fetch(`${MATCH_API_BASE}/api/match?id=${numId}`)
      .then((r) => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then((data) => {
        if (!cancelled) {
          if (data?.error) setState({ status: 'error', data: null, error: data.detail || data.error });
          else setState({ status: 'ready', data, error: null });
        }
      })
      .catch((err) => { if (!cancelled) setState({ status: 'error', data: null, error: String(err.message) }); });
    return () => { cancelled = true; };
  }, [matchId]);

  return state;
}

function MatchDetail({ match, onClose }) {
  const [tab, setTab] = React.useState('info');
  const home = window.TEAMS[match.home];
  const away = window.TEAMS[match.away];
  const hasScore = 'hs' in match;
  const detail = useMatchDetail(match.id);

  // Identificar que team del API corresponde a home/away (por nombre)
  const homeTeamId = detail.data?.lineups?.find((l) => sameName(l.teamName, home?.name))?.teamId;
  const awayTeamId = detail.data?.lineups?.find((l) => sameName(l.teamName, away?.name))?.teamId;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: '#F2F2F7', display: 'flex', flexDirection: 'column',
      overflowY: 'auto',
    }}>
      {/* header */}
      <div style={{
        background: 'linear-gradient(180deg, #0D2E6B 0%, #0A2457 100%)',
        color: '#fff', padding: '54px 16px 16px', position: 'relative',
      }}>
        <button
          type="button"
          onClick={onClose}
          style={{
            position: 'absolute', top: 52, left: 14,
            appearance: 'none', border: 'none',
            background: 'rgba(255,255,255,0.12)', color: '#fff',
            width: 34, height: 34, borderRadius: 999,
            fontSize: 18, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >‹</button>
        <div style={{ textAlign: 'center', fontSize: 11, fontWeight: 700, color: '#F5B01E', letterSpacing: 1.2, textTransform: 'uppercase', marginTop: 4 }}>
          {match.comp}
        </div>
        <div style={{ textAlign: 'center', fontSize: 10.5, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>
          {match.phase}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 8, marginTop: 14 }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <Crest team={match.home} size={64} />
            <div style={{ fontSize: 11, fontWeight: 800, textAlign: 'center', letterSpacing: 0.3, textTransform: 'uppercase' }}>
              {home?.name}
            </div>
          </div>
          <div style={{ fontFamily: '"Archivo Black", system-ui', fontSize: hasScore ? 34 : 24, fontWeight: 900, color: '#F5B01E', letterSpacing: 2, textAlign: 'center' }}>
            {hasScore ? `${match.hs} - ${match.as}` : 'VS'}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <Crest team={match.away} size={64} />
            <div style={{ fontSize: 11, fontWeight: 800, textAlign: 'center', letterSpacing: 0.3, textTransform: 'uppercase' }}>
              {away?.name}
            </div>
          </div>
        </div>
        <div style={{ textAlign: 'center', marginTop: 14, fontSize: 12, fontWeight: 600 }}>
          {match.date}{match.time ? ` · ${match.time} hs` : ''}
        </div>
        <div style={{ textAlign: 'center', fontSize: 11, color: 'rgba(255,255,255,0.65)', marginTop: 2 }}>
          {match.venue}
        </div>
      </div>

      {/* tabs */}
      <div style={{ display: 'flex', gap: 4, padding: '12px 16px 0', borderBottom: '1px solid rgba(0,0,0,0.06)' }}>
        {[
          { k: 'info', l: 'Info' },
          { k: 'eventos', l: 'Eventos' },
          { k: 'alineacion', l: 'Alineación' },
          { k: 'stats', l: 'Stats' },
        ].map(t => (
          <button
            key={t.k}
            type="button"
            onClick={() => setTab(t.k)}
            style={{
              appearance: 'none', border: 'none', background: 'transparent',
              padding: '10px 12px', fontFamily: 'inherit',
              fontSize: 12, fontWeight: 700,
              color: tab === t.k ? '#0A2B63' : 'rgba(0,0,0,0.5)',
              borderBottom: tab === t.k ? '2px solid #F5B01E' : '2px solid transparent',
              letterSpacing: 0.3, textTransform: 'uppercase', cursor: 'pointer',
            }}
          >{t.l}</button>
        ))}
      </div>

      {/* loading / error */}
      {detail.status === 'loading' && (
        <div style={{ padding: 30, textAlign: 'center', color: 'rgba(0,0,0,0.5)', fontSize: 12 }}>
          Cargando datos del partido...
        </div>
      )}
      {detail.status === 'error' && (
        <div style={{ padding: 16, textAlign: 'center', color: '#8B0A1A', fontSize: 12 }}>
          No se pudieron cargar los datos del partido. {detail.error}
        </div>
      )}

      {/* tab content */}
      {tab === 'info' && (
        <div style={{ padding: '14px 16px' }}>
          <InfoTab match={match} home={home} away={away} hasScore={hasScore} detail={detail.data} />
        </div>
      )}

      {tab === 'eventos' && (
        <div style={{ padding: '14px 16px' }}>
          <EventsTab events={detail.data?.events || []} homeTeamId={homeTeamId} />
        </div>
      )}

      {tab === 'alineacion' && (
        <div style={{ padding: '14px 16px' }}>
          <LineupTab lineups={detail.data?.lineups || []} homeTeamId={homeTeamId} awayTeamId={awayTeamId} />
        </div>
      )}

      {tab === 'stats' && (
        <div style={{ padding: '14px 16px' }}>
          <StatsTab statsByTeam={detail.data?.statsByTeam || {}} homeTeamId={homeTeamId} awayTeamId={awayTeamId} />
        </div>
      )}
    </div>
  );
}

function sameName(a, b) {
  if (!a || !b) return false;
  const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
  return norm(a) === norm(b) || norm(a).includes(norm(b)) || norm(b).includes(norm(a));
}

// --- Tab: Info (arbitro + status + previa corta) ---
function InfoTab({ match, home, away, hasScore, detail }) {
  return (
    <>
      <div style={{ background: '#fff', borderRadius: 10, padding: 14, fontSize: 12.5, color: '#222', lineHeight: 1.55 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#0A2B63', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 6 }}>Previa</div>
        {hasScore
          ? `Final ${match.hs}-${match.as}. Partido disputado en ${match.venue}.`
          : `${home?.name} recibe a ${away?.name}. Se espera una Bombonera colmada y un recibimiento histórico. Dale Boca, la mitad más uno está con vos.`}
      </div>
      {detail?.referee && (
        <div style={{ marginTop: 12, background: '#fff', borderRadius: 10, padding: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#0A2B63', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 8 }}>Árbitro</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#222' }}>{detail.referee}</div>
        </div>
      )}
      {detail?.status && (
        <div style={{ marginTop: 12, background: '#fff', borderRadius: 10, padding: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#0A2B63', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 8 }}>Estado</div>
          <div style={{ fontSize: 13, color: '#222' }}>{detail.status}</div>
        </div>
      )}
    </>
  );
}

// --- Tab: Eventos (timeline goles, tarjetas, cambios) ---
function EventsTab({ events, homeTeamId }) {
  if (!events.length) {
    return <div style={{ textAlign: 'center', padding: 24, color: 'rgba(0,0,0,0.5)', fontSize: 12 }}>Sin eventos registrados.</div>;
  }
  const iconFor = (type, detail) => {
    if (type === 'Goal') return '⚽';
    if (type === 'Card') return detail?.includes('Yellow') ? '🟨' : '🟥';
    if (type === 'subst') return '🔄';
    if (type === 'Var') return '📺';
    return '·';
  };
  return (
    <div style={{ background: '#fff', borderRadius: 10, padding: 0, overflow: 'hidden' }}>
      {events.map((e, i) => {
        const isHome = e.teamId === homeTeamId;
        return (
          <div
            key={i}
            style={{
              display: 'grid',
              gridTemplateColumns: '40px 28px 1fr',
              alignItems: 'center',
              padding: '10px 14px',
              borderBottom: i < events.length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none',
              fontSize: 12.5,
            }}
          >
            <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(0,0,0,0.55)', fontVariantNumeric: 'tabular-nums' }}>
              {e.minute}'{e.extra ? `+${e.extra}` : ''}
            </div>
            <div style={{ fontSize: 14, textAlign: 'center' }}>{iconFor(e.type, e.detail)}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: isHome ? '#0A2B63' : '#222' }}>{e.player}</div>
              <div style={{ fontSize: 10.5, color: 'rgba(0,0,0,0.55)' }}>
                {e.detail}{e.assist ? ` · asist. ${e.assist}` : ''} · {e.teamName}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// --- Tab: Alineacion (XI titular de cada equipo, con cancha simple) ---
function LineupTab({ lineups, homeTeamId, awayTeamId }) {
  const homeLine = lineups.find((l) => l.teamId === homeTeamId) || lineups[0];
  const awayLine = lineups.find((l) => l.teamId === awayTeamId) || lineups[1];

  if (!homeLine && !awayLine) {
    return <div style={{ textAlign: 'center', padding: 24, color: 'rgba(0,0,0,0.5)', fontSize: 12 }}>Alineaciones no disponibles para este partido.</div>;
  }

  return (
    <>
      {[homeLine, awayLine].filter(Boolean).map((l, idx) => (
        <div key={idx} style={{ marginBottom: 14, background: '#fff', borderRadius: 10, padding: '12px 14px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#0A2B63' }}>{l.teamName}</div>
            <div style={{ fontSize: 10.5, color: 'rgba(0,0,0,0.55)' }}>Formación {l.formation || '-'}</div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 10px' }}>
            {l.startXI.map((p, i) => (
              <div key={i} style={{ fontSize: 12, padding: '4px 0', color: '#222', display: 'flex', gap: 6 }}>
                <span style={{ fontSize: 10.5, color: 'rgba(0,0,0,0.5)', minWidth: 18, fontVariantNumeric: 'tabular-nums' }}>
                  {p.number ?? ''}
                </span>
                <span>{p.name}</span>
                <span style={{ fontSize: 10, color: 'rgba(0,0,0,0.4)', marginLeft: 'auto' }}>{p.pos}</span>
              </div>
            ))}
          </div>
          {l.coach && (
            <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.55)', marginTop: 10, paddingTop: 8, borderTop: '1px dashed rgba(0,0,0,0.1)' }}>
              DT: <span style={{ color: '#222', fontWeight: 600 }}>{l.coach}</span>
            </div>
          )}
        </div>
      ))}
    </>
  );
}

// --- Tab: Stats (barras comparativas) ---
function StatsTab({ statsByTeam, homeTeamId, awayTeamId }) {
  const homeStats = statsByTeam[homeTeamId]?.stats || {};
  const awayStats = statsByTeam[awayTeamId]?.stats || {};

  const rows = [
    { l: 'Posesión', key: 'Ball Possession', percent: true },
    { l: 'Tiros al arco', key: 'Shots on Goal' },
    { l: 'Tiros totales', key: 'Total Shots' },
    { l: 'Córners', key: 'Corner Kicks' },
    { l: 'Faltas', key: 'Fouls' },
    { l: 'Amarillas', key: 'Yellow Cards' },
    { l: 'Rojas', key: 'Red Cards' },
    { l: 'Pases', key: 'Total passes' },
    { l: 'Precisión pases', key: 'Passes %', percent: true },
  ];

  const visible = rows.filter(({ key }) => homeStats[key] != null || awayStats[key] != null);

  if (!visible.length) {
    return <div style={{ textAlign: 'center', padding: 24, color: 'rgba(0,0,0,0.5)', fontSize: 12 }}>Estadísticas no disponibles para este partido.</div>;
  }

  const num = (v) => {
    if (v == null) return 0;
    const s = String(v).replace('%', '').trim();
    const n = parseFloat(s);
    return Number.isFinite(n) ? n : 0;
  };
  const fmt = (v, percent) => {
    if (v == null) return '-';
    return percent && !String(v).includes('%') ? `${v}%` : String(v);
  };

  return (
    <>
      {visible.map((s, i) => {
        const h = num(homeStats[s.key]);
        const a = num(awayStats[s.key]);
        const tot = h + a;
        const hp = tot > 0 ? (h / tot) * 100 : 50;
        return (
          <div key={i} style={{ marginBottom: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, fontWeight: 700, color: '#111', marginBottom: 4 }}>
              <span>{fmt(homeStats[s.key], s.percent)}</span>
              <span style={{ color: 'rgba(0,0,0,0.5)', fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase', fontSize: 10.5 }}>{s.l}</span>
              <span>{fmt(awayStats[s.key], s.percent)}</span>
            </div>
            <div style={{ height: 5, borderRadius: 999, background: 'rgba(0,0,0,0.08)', overflow: 'hidden', display: 'flex' }}>
              <div style={{ width: `${hp}%`, background: '#0A2B63' }} />
              <div style={{ width: `${100 - hp}%`, background: '#F5B01E' }} />
            </div>
          </div>
        );
      })}
    </>
  );
}

function NewsDetail({ item, onClose }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: '#fff', display: 'flex', flexDirection: 'column',
      overflowY: 'auto',
    }}>
      <div style={{
        height: 220,
        background: 'linear-gradient(135deg, #0D2E6B 0%, #13357A 60%, #0A2457 100%)',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(45deg, rgba(245,176,30,0.08) 0 8px, transparent 8px 16px)',
        }} />
        <button
          type="button"
          onClick={onClose}
          style={{
            position: 'absolute', top: 52, left: 14,
            appearance: 'none', border: 'none',
            background: 'rgba(255,255,255,0.18)', color: '#fff',
            width: 34, height: 34, borderRadius: 999,
            fontSize: 18, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            backdropFilter: 'blur(10px)',
          }}
        >‹</button>
        <div style={{
          position: 'absolute', bottom: 14, left: 16,
          fontSize: 10, fontWeight: 900, color: '#F5B01E',
          letterSpacing: 1.4, textTransform: 'uppercase',
          background: 'rgba(10,36,87,0.7)', padding: '4px 8px', borderRadius: 3,
        }}>{item.tag}</div>
      </div>
      <div style={{ padding: '18px 18px 40px' }}>
        <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.45)', fontWeight: 600, marginBottom: 6 }}>
          {item.time}
        </div>
        <h1 style={{
          fontSize: 22, fontWeight: 800, color: '#0A1F47',
          margin: '0 0 12px', letterSpacing: -0.4, lineHeight: 1.2,
          textWrap: 'pretty',
        }}>
          {item.title}
        </h1>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'rgba(0,0,0,0.7)', lineHeight: 1.45, marginBottom: 16, textWrap: 'pretty' }}>
          {item.excerpt}
        </div>
        {item.body.map((p, i) => (
          <p key={i} style={{ fontSize: 13.5, lineHeight: 1.55, color: '#222', margin: '0 0 12px', textWrap: 'pretty' }}>
            {p}
          </p>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { MatchDetail, NewsDetail });
