'use client';

import { useEffect, useMemo, useState } from 'react';
import SportBadge from '@/components/vyndr/SportBadge';
import SectionHead from '@/components/vyndr/SectionHead';
import { playerHref } from '@/lib/playerHref';
import { timeAgo, typeLabel } from '@/lib/newsFormat';

/* ============================================================
   NewsWire (Wave 2B — Offseason Hub). The never-dark LEAGUE WIRE: REAL ESPN
   headlines (`/api/news/:sport`) + REAL injuries (`/api/schedule/:sport/
   injuries`), fed into the retired TerminalTemplates INJURY_WIRE layout.

   HONESTY: everything real or absent. No sample data ever reaches here. The
   whole component SELF-HIDES when both feeds are empty (news items:[] AND no
   injuries) — the offseason hub shows what is genuinely available or nothing.
   Timestamps + statuses are mono (the data-is-mono brand rule).
   ============================================================ */

interface Athlete { name: string; key?: string }
interface NewsItem {
  id: string | number;
  headline: string;
  description?: string;
  published?: string | number;
  type?: string;
  athlete?: Athlete | null;
  team?: string | null;
  href?: string | null;
}

export interface NewsWireProps {
  sport: string;
}

// Injury status → color token. OUT is a genuine availability negative (red);
// GTD/questionable is caution (amber); probable/other reads neutral. Tokens
// only — no raw hex (QA parity rule).
function statusColor(s: string): string {
  const v = String(s || '').toUpperCase();
  if (v === 'OUT') return 'var(--miss)';
  if (v === 'GTD' || v === 'QUESTIONABLE' || v === 'DTD') return 'var(--amber)';
  return 'var(--text-1)';
}

// nameKey ("aaron judge") → display ("Aaron Judge"). Real data, just cased.
function titleCase(key: string): string {
  return String(key || '')
    .split(/\s+/)
    .filter(Boolean)
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

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

export default function NewsWire({ sport }: NewsWireProps) {
  const [items, setItems] = useState<NewsItem[] | null>(null);
  const [injuries, setInjuries] = useState<Array<[string, string]> | null>(null);

  useEffect(() => {
    let cancelled = false;
    setItems(null);
    setInjuries(null);
    // News feed (Wave 2A contract). Self-hide on any failure — never invent.
    fetch(`/api/news/${encodeURIComponent(sport)}`)
      .then((r) => (r.ok ? r.json() : { items: [] }))
      .then((d) => { if (!cancelled) setItems(Array.isArray(d?.items) ? d.items : []); })
      .catch(() => { if (!cancelled) setItems([]); });
    // Injury wire (already-live contract: { byPlayer: { nameKey -> STATUS } }).
    fetch(`/api/schedule/${encodeURIComponent(sport)}/injuries`)
      .then((r) => (r.ok ? r.json() : { byPlayer: {} }))
      .then((d) => {
        if (cancelled) return;
        const bp = d && typeof d.byPlayer === 'object' && d.byPlayer ? d.byPlayer : {};
        setInjuries(Object.entries(bp).map(([k, v]) => [k, String(v)] as [string, string]));
      })
      .catch(() => { if (!cancelled) setInjuries([]); });
    return () => { cancelled = true; };
  }, [sport]);

  // Newest-first (defensive — the backend already sorts, but never trust order).
  const news = useMemo(() => {
    const list = Array.isArray(items) ? [...items] : [];
    return list.sort((a, b) => {
      const ta = a.published ? Date.parse(String(a.published)) : 0;
      const tb = b.published ? Date.parse(String(b.published)) : 0;
      return (Number.isFinite(tb) ? tb : 0) - (Number.isFinite(ta) ? ta : 0);
    });
  }, [items]);

  const inj = injuries || [];

  // SELF-HIDE: both feeds empty (still loading = null on both → also hidden).
  if (news.length === 0 && inj.length === 0) return null;

  return (
    <div style={{ marginTop: 28 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <SectionHead>LEAGUE WIRE · NEWS + INJURIES</SectionHead>
        <SportBadge sport={sport} size="sm" />
      </div>

      {/* INJURY WIRE — real chips (self-hides its own block when empty). */}
      {inj.length > 0 && (
        <div style={{ ...card, marginBottom: 12 }}>
          <div className="label" style={{ marginBottom: 10 }}>INJURY REPORT · {inj.length} FLAGGED</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {inj.map(([key, status]) => (
              <a
                key={key}
                href={playerHref(titleCase(key), sport)}
                className="mono"
                style={{ display: 'inline-flex', alignItems: 'center', gap: 7, textDecoration: 'none', fontSize: 11.5, padding: '4px 9px', borderRadius: 5, border: '1px solid var(--border)', background: 'var(--bg-2, #0d0d14)', color: 'var(--text-1)' }}
              >
                <span style={{ fontWeight: 600, color: '#fff', fontFamily: 'var(--sans)' }}>{titleCase(key)}</span>
                <span style={{ fontWeight: 700, letterSpacing: '0.06em', color: statusColor(status) }}>{String(status).toUpperCase()}</span>
              </a>
            ))}
          </div>
        </div>
      )}

      {/* NEWS HEADLINES — real ESPN feed, newest first (self-hides when empty). */}
      {news.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {news.map((n) => {
            const stamp = timeAgo(n.published);
            const chip = typeLabel(n.type);
            const HeadlineTag = n.href ? 'a' : 'div';
            return (
              <div key={n.id} style={card}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 7, flexWrap: 'wrap' }}>
                  {chip && <span className="mono" style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', padding: '2px 6px', borderRadius: 3, color: 'var(--g-a)', border: '1px solid rgba(0,212,160,.3)' }}>{chip}</span>}
                  {stamp && <span className="mono" style={{ fontSize: 10.5, color: 'var(--text-2)' }}>{stamp}</span>}
                </div>
                <HeadlineTag
                  {...(n.href ? { href: n.href, target: '_blank', rel: 'noopener noreferrer' } : {})}
                  style={{ display: 'block', fontSize: 14, fontWeight: 700, lineHeight: 1.4, color: '#fff', textDecoration: 'none' }}
                >
                  {n.headline}
                </HeadlineTag>
                {n.description && (
                  <p style={{ margin: '6px 0 0', fontSize: 12.5, lineHeight: 1.55, color: 'var(--text-1)' }}>{n.description}</p>
                )}
                {(n.athlete?.name || n.team) && (
                  <div className="mono" style={{ marginTop: 9, display: 'flex', alignItems: 'center', gap: 10, fontSize: 11 }}>
                    {n.athlete?.name && (
                      <a href={playerHref(n.athlete.name, sport)} style={{ color: 'var(--g-a)', textDecoration: 'none', fontWeight: 700 }}>↳ {n.athlete.name}</a>
                    )}
                    {n.team && (
                      <a href={`/team/${encodeURIComponent(n.team)}?sport=${encodeURIComponent(sport)}`} style={{ color: 'var(--text-1)', textDecoration: 'none' }}>{n.team}</a>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
