// Main app for Golaço — football stats prototype
const { useState, useMemo, useEffect } = React;

// ---------- DATA ----------
// sid = ID numérico no 365scores → usado para buscar o escudo em imagescache.365scores.com
const TEAMS = {
  // Brasileirão
  FLA: { name: "Flamengo",      short: "FLA", color: "#d92626", city: "Rio de Janeiro",      sid: 1973  },
  PAL: { name: "Palmeiras",     short: "PAL", color: "#2e7d3a", city: "São Paulo",            sid: 1966  },
  COR: { name: "Corinthians",   short: "COR", color: "#1a1a1a", city: "São Paulo",            sid: 1974  },
  SAO: { name: "São Paulo",     short: "SAO", color: "#c43030", city: "São Paulo",            sid: 1967  },
  FLU: { name: "Fluminense",    short: "FLU", color: "#7a1530", city: "Rio de Janeiro",      sid: 1980  },
  BOT: { name: "Botafogo",      short: "BOT", color: "#222222", city: "Rio de Janeiro",      sid: 1977  },
  VAS: { name: "Vasco",         short: "VAS", color: "#1a1a1a", city: "Rio de Janeiro",      sid: 1978  },
  CRU: { name: "Cruzeiro",      short: "CRU", color: "#1d3d8a", city: "Belo Horizonte",      sid: 1972  },
  CAM: { name: "Atlético-MG",   short: "CAM", color: "#1a1a1a", city: "Belo Horizonte",      sid: 1971  },
  INT: { name: "Internacional", short: "INT", color: "#c12828", city: "Porto Alegre",        sid: 1992  },
  GRE: { name: "Grêmio",        short: "GRE", color: "#1c4a8a", city: "Porto Alegre",        sid: 1991  },
  BAH: { name: "Bahia",         short: "BAH", color: "#1d56a3", city: "Salvador",            sid: 2004  },
  FOR: { name: "Fortaleza",     short: "FOR", color: "#1d3d8a", city: "Fortaleza",           sid: 14364 },
  CEA: { name: "Ceará",         short: "CEA", color: "#1a1a1a", city: "Fortaleza",           sid: 2014  },
  CAP: { name: "Athletico-PR",  short: "CAP", color: "#c43030", city: "Curitiba",            sid: 1996  },
  RBB: { name: "Bragantino",    short: "RBB", color: "#d6d6d6", city: "Bragança Paulista",   sid: 14303 },
  VIT: { name: "Vitória",       short: "VIT", color: "#1a1a1a", city: "Salvador",            sid: 1999  },
  JUV: { name: "Juventude",     short: "JUV", color: "#2a7a3a", city: "Caxias do Sul",       sid: 2017  },
  MIR: { name: "Mirassol",      short: "MIR", color: "#d4b830", city: "Mirassol",            sid: 14748 },
  SPT: { name: "Sport",         short: "SPT", color: "#c43030", city: "Recife",              sid: 2011  },
  // Libertadores / Sul-Americana
  RIV: { name: "River Plate",   short: "RIV", color: "#c43030", city: "Buenos Aires",        sid: 1949  },
  BOC: { name: "Boca Juniors",  short: "BOC", color: "#1c4a8a", city: "Buenos Aires",        sid: 1947  },
  NAC: { name: "Nacional",      short: "NAC", color: "#1a1a1a", city: "Montevidéu",          sid: 2143  },
  PEN: { name: "Peñarol",       short: "PEN", color: "#d4b830", city: "Montevidéu",          sid: 2144  },
  OLI: { name: "Olimpia",       short: "OLI", color: "#d6d6d6", city: "Assunção",            sid: 2153  },
  COL: { name: "Colo-Colo",     short: "COL", color: "#1a1a1a", city: "Santiago",            sid: 2047  },
  IDV: { name: "Ind. del Valle",short: "IDV", color: "#1a1a1a", city: "Quito",               sid: 16284 },
  LDU: { name: "LDU Quito",     short: "LDU", color: "#1c4a8a", city: "Quito",               sid: 2059  },
  ATN: { name: "At. Nacional",  short: "ATN", color: "#2e7d3a", city: "Medellín",            sid: 2080  },
  MIL: { name: "Millonarios",   short: "MIL", color: "#1c4a8a", city: "Bogotá",              sid: 2082  },
  ALI: { name: "Alianza Lima",  short: "ALI", color: "#1c4a8a", city: "Lima",                sid: 2111  },
  CER: { name: "Cerro Porteño", short: "CER", color: "#c43030", city: "Assunção",            sid: 2152  },
};

// id, comp, status, minute, home, away, hScore, aScore, date, stage, stadium
const MATCHES = [
  // ---- AO VIVO ----
  { id: "m1", comp: "BR", status: "live", minute: "67'", home: "FLA", away: "PAL", hScore: 2, aScore: 1, date: "Hoje", stage: "Rodada 12", stadium: "Maracanã", possessionH: 58, shotsH: 11, shotsA: 7 },
  { id: "m2", comp: "BR", status: "live", minute: "23'", home: "COR", away: "SAO", hScore: 0, aScore: 0, date: "Hoje", stage: "Rodada 12", stadium: "Neo Química Arena", possessionH: 47, shotsH: 3, shotsA: 5 },
  { id: "m3", comp: "LIB", status: "live", minute: "82'", home: "RIV", away: "FLU", hScore: 1, aScore: 2, date: "Hoje", stage: "Oitavas — Ida", stadium: "Monumental", possessionH: 62, shotsH: 14, shotsA: 9 },
  { id: "m4", comp: "SUL", status: "live", minute: "INTERVALO", home: "RBB", away: "ATN", hScore: 1, aScore: 1, date: "Hoje", stage: "Oitavas — Volta", stadium: "Cícero de Souza Marques", possessionH: 51, shotsH: 6, shotsA: 6 },

  // ---- HOJE / PRÓXIMOS ----
  { id: "m5", comp: "BR", status: "scheduled", time: "21:30", home: "BOT", away: "CRU", date: "Hoje", stage: "Rodada 12", stadium: "Nilton Santos" },
  { id: "m6", comp: "BR", status: "scheduled", time: "16:00", home: "GRE", away: "INT", date: "Amanhã", stage: "Rodada 12", stadium: "Arena do Grêmio" },
  { id: "m7", comp: "BR", status: "scheduled", time: "18:30", home: "BAH", away: "FOR", date: "Amanhã", stage: "Rodada 12", stadium: "Fonte Nova" },
  { id: "m8", comp: "BR", status: "scheduled", time: "20:00", home: "CAM", away: "VAS", date: "Sábado", stage: "Rodada 13", stadium: "Arena MRV" },
  { id: "m9", comp: "BR", status: "scheduled", time: "16:00", home: "CEA", away: "MIR", date: "Sábado", stage: "Rodada 13", stadium: "Castelão" },
  { id: "m10", comp: "LIB", status: "scheduled", time: "21:30", home: "BOC", away: "PAL", date: "Quinta", stage: "Oitavas — Ida", stadium: "La Bombonera" },
  { id: "m11", comp: "LIB", status: "scheduled", time: "19:00", home: "IDV", away: "FLA", date: "Quarta", stage: "Oitavas — Volta", stadium: "Banco Guayaquil" },
  { id: "m12", comp: "LIB", status: "scheduled", time: "21:30", home: "NAC", away: "BOT", date: "Quinta", stage: "Oitavas — Ida", stadium: "Centenário" },
  { id: "m13", comp: "SUL", status: "scheduled", time: "19:00", home: "VIT", away: "CER", date: "Quarta", stage: "Oitavas — Ida", stadium: "Barradão" },
  { id: "m14", comp: "SUL", status: "scheduled", time: "21:30", home: "CAP", away: "MIL", date: "Quinta", stage: "Oitavas — Volta", stadium: "Ligga Arena" },
  { id: "m15", comp: "SUL", status: "scheduled", time: "19:00", home: "JUV", away: "ALI", date: "Quarta", stage: "Oitavas — Ida", stadium: "Alfredo Jaconi" },

  // ---- ENCERRADOS ----
  { id: "m16", comp: "BR", status: "finished", home: "FLA", away: "INT", hScore: 3, aScore: 0, date: "Domingo", stage: "Rodada 11", stadium: "Maracanã" },
  { id: "m17", comp: "BR", status: "finished", home: "PAL", away: "BOT", hScore: 1, aScore: 1, date: "Domingo", stage: "Rodada 11", stadium: "Allianz Parque" },
  { id: "m18", comp: "BR", status: "finished", home: "SAO", away: "CAM", hScore: 2, aScore: 2, date: "Sábado", stage: "Rodada 11", stadium: "MorumBis" },
  { id: "m19", comp: "BR", status: "finished", home: "CRU", away: "GRE", hScore: 0, aScore: 1, date: "Sábado", stage: "Rodada 11", stadium: "Mineirão" },
  { id: "m20", comp: "BR", status: "finished", home: "FOR", away: "VAS", hScore: 2, aScore: 0, date: "Sábado", stage: "Rodada 11", stadium: "Castelão" },
  { id: "m21", comp: "BR", status: "finished", home: "RBB", away: "JUV", hScore: 3, aScore: 2, date: "Sexta", stage: "Rodada 11", stadium: "Cícero de Souza Marques" },
  { id: "m22", comp: "LIB", status: "finished", home: "PEN", away: "SAO", hScore: 0, aScore: 1, date: "Semana passada", stage: "Fase de grupos", stadium: "Campeón del Siglo" },
  { id: "m23", comp: "LIB", status: "finished", home: "CAM", away: "COL", hScore: 4, aScore: 0, date: "Semana passada", stage: "Fase de grupos", stadium: "Arena MRV" },
  { id: "m24", comp: "LIB", status: "finished", home: "LDU", away: "INT", hScore: 1, aScore: 2, date: "Semana passada", stage: "Fase de grupos", stadium: "Casa Blanca" },
  { id: "m25", comp: "SUL", status: "finished", home: "OLI", away: "BAH", hScore: 1, aScore: 3, date: "Semana passada", stage: "Fase de grupos", stadium: "Defensores del Chaco" },
  { id: "m26", comp: "SUL", status: "finished", home: "CEA", away: "ALI", hScore: 2, aScore: 1, date: "Semana passada", stage: "Fase de grupos", stadium: "Castelão" },
  { id: "m27", comp: "SUL", status: "finished", home: "SPT", away: "MIL", hScore: 0, aScore: 0, date: "Semana passada", stage: "Fase de grupos", stadium: "Ilha do Retiro" },
];

const COMPS = {
  ALL: { id: "ALL", name: "Tudo", full: "Todos os campeonatos", logo: "★" },
  BR:  { id: "BR",  name: "Brasileirão", full: "Campeonato Brasileiro — Série A", logo: "BR" },
  LIB: { id: "LIB", name: "Libertadores", full: "CONMEBOL Libertadores", logo: "L" },
  SUL: { id: "SUL", name: "Sul-Americana", full: "CONMEBOL Sul-Americana", logo: "S" },
};

// Fake league standings for Brasileirão
const TABLE_BR = [
  { t: "FLA", p: 27, j: 11, v: 8, e: 3, d: 0, gp: 22, gc: 6 },
  { t: "PAL", p: 24, j: 11, v: 7, e: 3, d: 1, gp: 19, gc: 8 },
  { t: "BOT", p: 22, j: 11, v: 6, e: 4, d: 1, gp: 17, gc: 9 },
  { t: "CRU", p: 21, j: 11, v: 6, e: 3, d: 2, gp: 15, gc: 8 },
  { t: "FLU", p: 19, j: 11, v: 5, e: 4, d: 2, gp: 14, gc: 11 },
  { t: "SAO", p: 18, j: 11, v: 5, e: 3, d: 3, gp: 13, gc: 12 },
  { t: "BAH", p: 17, j: 11, v: 5, e: 2, d: 4, gp: 12, gc: 11 },
  { t: "RBB", p: 16, j: 11, v: 4, e: 4, d: 3, gp: 13, gc: 12 },
  { t: "INT", p: 15, j: 11, v: 4, e: 3, d: 4, gp: 11, gc: 11 },
  { t: "CAM", p: 14, j: 11, v: 4, e: 2, d: 5, gp: 13, gc: 14 },
  { t: "GRE", p: 13, j: 11, v: 3, e: 4, d: 4, gp: 10, gc: 12 },
  { t: "FOR", p: 13, j: 11, v: 3, e: 4, d: 4, gp: 9, gc: 11 },
  { t: "COR", p: 12, j: 11, v: 3, e: 3, d: 5, gp: 9, gc: 13 },
  { t: "JUV", p: 11, j: 11, v: 3, e: 2, d: 6, gp: 10, gc: 15 },
  { t: "VAS", p: 10, j: 11, v: 2, e: 4, d: 5, gp: 8, gc: 13 },
  { t: "CAP", p: 10, j: 11, v: 2, e: 4, d: 5, gp: 8, gc: 14 },
  { t: "CEA", p: 9, j: 11, v: 2, e: 3, d: 6, gp: 7, gc: 13 },
  { t: "MIR", p: 8, j: 11, v: 2, e: 2, d: 7, gp: 7, gc: 16 },
  { t: "VIT", p: 7, j: 11, v: 1, e: 4, d: 6, gp: 6, gc: 14 },
  { t: "SPT", p: 5, j: 11, v: 1, e: 2, d: 8, gp: 5, gc: 18 },
];

// ---------- HELPERS ----------
const TeamLogo = ({ id, size = 32 }) => {
  const t = TEAMS[id];
  if (!t) return null;
  const [failed, setFailed] = useState(false);

  // URL do escudo via 365scores image cache.
  // O parâmetro d_Competitors:default1.png serve um escudo genérico
  // como fallback do próprio Cloudinary se o ID não existir.
  const shieldUrl = t.sid
    ? `https://imagescache.365scores.com/image/upload/w_${size * 2},h_${size * 2},c_limit,f_webp,q_90,d_Competitors:default1.png/Competitors/${t.sid}`
    : null;

  if (shieldUrl && !failed) {
    return (
      <img
        className="team-shield"
        src={shieldUrl}
        alt={t.name}
        title={t.name}
        width={size}
        height={size}
        onError={() => setFailed(true)}
        loading="lazy"
      />
    );
  }

  // Fallback: círculo colorido com sigla (comportamento original)
  return (
    <div
      className="team-logo"
      style={{ width: size, height: size, background: t.color, fontSize: size * 0.38 }}
      title={t.name}
    >
      {t.short}
    </div>
  );
};

const CompBadge = ({ comp }) => {
  const c = COMPS[comp];
  const colors = {
    BR: "var(--accent)",
    LIB: "#e8c648",
    SUL: "#e87a48",
  };
  return (
    <span className="comp-badge" style={{ "--bg": colors[comp] || "#888" }}>
      <span className="comp-dot" style={{ background: colors[comp] || "#888" }}></span>
      {c?.name}
    </span>
  );
};

// ---------- MATCH CARD ----------
const MatchCard = ({ match, followed, onToggleFollow, compact = false, onOpen }) => {
  const home = TEAMS[match.home];
  const away = TEAMS[match.away];
  const isLive = match.status === "live";
  const isFinished = match.status === "finished";

  return (
    <article
      className={`match-card ${isLive ? "is-live" : ""} ${compact ? "is-compact" : ""}`}
      onClick={() => onOpen && onOpen(match)}
    >
      <header className="match-meta">
        <CompBadge comp={match.comp} />
        <span className="match-stage">{match.stage}</span>
        <button
          className={`follow-btn ${followed ? "is-on" : ""}`}
          onClick={(e) => { e.stopPropagation(); onToggleFollow(match.id); }}
          aria-label={followed ? "Deixar de acompanhar" : "Acompanhar jogo"}
          title={followed ? "Deixar de acompanhar" : "Acompanhar jogo"}
        >
          {followed ? (
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 2 14.5 8.5 21 9.3l-5 4.5 1.5 7L12 17.3 6.5 20.8 8 13.8l-5-4.5 6.5-.8L12 2Z"/></svg>
          ) : (
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 3 14.3 8.6l6 .6-4.6 4.1 1.4 5.9L12 16.2 6.9 19.2l1.4-5.9L3.7 9.2l6-.6L12 3Z"/></svg>
          )}
        </button>
      </header>

      <div className="match-body">
        <div className="team-row">
          <TeamLogo id={match.home} size={36} />
          <span className="team-name">{home?.name}</span>
          <span className="team-score">{isLive || isFinished ? match.hScore : ""}</span>
        </div>
        <div className="team-row">
          <TeamLogo id={match.away} size={36} />
          <span className="team-name">{away?.name}</span>
          <span className="team-score">{isLive || isFinished ? match.aScore : ""}</span>
        </div>
      </div>

      <footer className="match-foot">
        {isLive && (
          <span className="live-pill">
            <span className="live-dot"></span>
            AO VIVO · {match.minute}
          </span>
        )}
        {match.status === "scheduled" && (
          <span className="time-pill">{match.date} · {match.time}</span>
        )}
        {isFinished && (
          <span className="time-pill finished">Encerrado · {match.date}</span>
        )}
        <span className="match-stadium">{match.stadium}</span>
      </footer>
    </article>
  );
};

// ---------- FOLLOWED STRIP (pinned at top of main page) ----------
const FollowedStrip = ({ matches, followed, onToggleFollow, onOpen }) => {
  const list = matches.filter(m => followed.includes(m.id));
  if (!list.length) {
    return (
      <section className="followed-empty">
        <div>
          <h3>Acompanhando</h3>
          <p>Toque na <span className="inline-star">★</span> de qualquer jogo para fixá-lo aqui — placar ao vivo, próximo apito ou resultado final em destaque.</p>
        </div>
      </section>
    );
  }
  return (
    <section className="followed-strip">
      <div className="followed-head">
        <h3>Acompanhando <span className="count">{list.length}</span></h3>
        <span className="hint">Atualizando ao vivo</span>
      </div>
      <div className="followed-grid">
        {list.map(m => (
          <FollowedCard
            key={m.id}
            match={m}
            onUnfollow={() => onToggleFollow(m.id)}
            onOpen={() => onOpen(m)}
          />
        ))}
      </div>
    </section>
  );
};

const FollowedCard = ({ match, onUnfollow, onOpen }) => {
  const home = TEAMS[match.home];
  const away = TEAMS[match.away];
  const isLive = match.status === "live";
  const isFinished = match.status === "finished";

  return (
    <div className={`followed-card ${isLive ? "is-live" : ""}`} onClick={onOpen}>
      <div className="followed-top">
        <CompBadge comp={match.comp} />
        {isLive && (
          <span className="live-pill compact">
            <span className="live-dot"></span>{match.minute}
          </span>
        )}
        {match.status === "scheduled" && (
          <span className="time-pill compact">{match.date} · {match.time}</span>
        )}
        {isFinished && (
          <span className="time-pill compact finished">Final</span>
        )}
        <button
          className="unfollow"
          onClick={(e) => { e.stopPropagation(); onUnfollow(); }}
          title="Remover dos acompanhados"
        >×</button>
      </div>
      <div className="followed-score">
        <div className="fteam">
          <TeamLogo id={match.home} size={42} />
          <span>{home?.short}</span>
        </div>
        <div className="fscore">
          {isLive || isFinished ? (
            <><span className={isLive ? "pulse" : ""}>{match.hScore}</span><i>—</i><span className={isLive ? "pulse" : ""}>{match.aScore}</span></>
          ) : (
            <span className="vs">vs</span>
          )}
        </div>
        <div className="fteam">
          <TeamLogo id={match.away} size={42} />
          <span>{away?.short}</span>
        </div>
      </div>
      {isLive && (
        <div className="mini-stats">
          <div><b>{match.possessionH}%</b><span>posse</span></div>
          <div><b>{match.shotsH}–{match.shotsA}</b><span>chutes</span></div>
          <div><b>{match.minute.replace("'", "")}</b><span>minuto</span></div>
        </div>
      )}
    </div>
  );
};

// ---------- MATCH DETAILS DRAWER ----------
const MatchDrawer = ({ match, onClose, followed, onToggleFollow }) => {
  if (!match) return null;
  const home = TEAMS[match.home];
  const away = TEAMS[match.away];
  const isLive = match.status === "live";
  const isFinished = match.status === "finished";
  const isFollowed = followed.includes(match.id);

  // fake event timeline
  const events = [
    { min: "12'", t: "⚽ Gol", side: "home", text: `${home.name} — Pedro` },
    { min: "27'", t: "🟨 Cartão", side: "away", text: `${away.name} — Ricardo` },
    { min: "44'", t: "⚽ Gol", side: "away", text: `${away.name} — Estêvão` },
    { min: "58'", t: "🔄 Substituição", side: "home", text: `${home.name} — Sai Arrascaeta, entra Cebolinha` },
    { min: "67'", t: "⚽ Gol", side: "home", text: `${home.name} — Bruno Henrique` },
  ];

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <aside className="drawer" onClick={(e) => e.stopPropagation()}>
        <header className="drawer-head">
          <button className="close-btn" onClick={onClose} aria-label="Fechar">×</button>
          <CompBadge comp={match.comp} />
          <span className="drawer-stage">{match.stage} · {match.stadium}</span>
        </header>

        <div className="drawer-score">
          <div className="dteam">
            <TeamLogo id={match.home} size={72} />
            <h2>{home.name}</h2>
            <span>{home.city}</span>
          </div>
          <div className="dscore">
            {isLive || isFinished ? (
              <>
                <div className="dnumbers"><span>{match.hScore}</span><i>—</i><span>{match.aScore}</span></div>
                {isLive && <span className="live-pill"><span className="live-dot"></span>AO VIVO · {match.minute}</span>}
                {isFinished && <span className="time-pill finished">Encerrado</span>}
              </>
            ) : (
              <>
                <div className="dnumbers"><span className="vs">vs</span></div>
                <span className="time-pill">{match.date} · {match.time}</span>
              </>
            )}
          </div>
          <div className="dteam">
            <TeamLogo id={match.away} size={72} />
            <h2>{away.name}</h2>
            <span>{away.city}</span>
          </div>
        </div>

        <button
          className={`big-follow ${isFollowed ? "is-on" : ""}`}
          onClick={() => onToggleFollow(match.id)}
        >
          {isFollowed ? "★ Acompanhando — fixado no topo" : "☆ Acompanhar este jogo"}
        </button>

        {(isLive || isFinished) && (
          <section className="drawer-section">
            <h4>Estatísticas</h4>
            <StatBar label="Posse de bola" h={match.possessionH || 54} a={100 - (match.possessionH || 54)} unit="%" />
            <StatBar label="Finalizações" h={match.shotsH || 9} a={match.shotsA || 6} />
            <StatBar label="Escanteios" h={6} a={3} />
            <StatBar label="Faltas" h={9} a={11} />
            <StatBar label="Passes certos" h={412} a={358} />
          </section>
        )}

        {(isLive || isFinished) && (
          <section className="drawer-section">
            <h4>Lances</h4>
            <ul className="timeline">
              {events.map((ev, i) => (
                <li key={i} className={`tl-item tl-${ev.side}`}>
                  <span className="tl-min">{ev.min}</span>
                  <span className="tl-text">{ev.t} · {ev.text}</span>
                </li>
              ))}
            </ul>
          </section>
        )}

        {match.status === "scheduled" && (
          <section className="drawer-section">
            <h4>Histórico recente entre os times</h4>
            <ul className="h2h">
              <li><span>2024</span><b>{home.short} 2 — 1 {away.short}</b><i>Brasileirão</i></li>
              <li><span>2024</span><b>{home.short} 0 — 0 {away.short}</b><i>Copa do Brasil</i></li>
              <li><span>2023</span><b>{home.short} 1 — 3 {away.short}</b><i>Brasileirão</i></li>
            </ul>
          </section>
        )}
      </aside>
    </div>
  );
};

const StatBar = ({ label, h, a, unit = "" }) => {
  const total = h + a || 1;
  const hp = (h / total) * 100;
  return (
    <div className="stat-bar">
      <div className="stat-row">
        <span>{h}{unit}</span><span className="stat-label">{label}</span><span>{a}{unit}</span>
      </div>
      <div className="stat-track">
        <div className="stat-fill h" style={{ width: `${hp}%` }}></div>
        <div className="stat-fill a" style={{ width: `${100 - hp}%` }}></div>
      </div>
    </div>
  );
};

// ---------- TABLE ----------
const TableView = () => {
  return (
    <section className="table-wrap">
      <div className="table-head">
        <h3>Classificação — Brasileirão Série A</h3>
        <span className="hint">Rodada 11 · atualizado há 4min</span>
      </div>
      <table className="standings">
        <thead>
          <tr>
            <th>#</th><th>Time</th>
            <th>P</th><th>J</th><th>V</th><th>E</th><th>D</th><th>GP</th><th>GC</th><th>SG</th>
          </tr>
        </thead>
        <tbody>
          {TABLE_BR.map((r, i) => {
            const t = TEAMS[r.t];
            const zone =
              i < 4 ? "lib" :
              i < 6 ? "pre" :
              i < 12 ? "sul" :
              i >= 16 ? "rel" : "";
            return (
              <tr key={r.t} className={`zone-${zone}`}>
                <td className="pos"><span className={`zone-mark zone-${zone}`}></span>{i + 1}</td>
                <td className="team-cell">
                  <TeamLogo id={r.t} size={22} />
                  <span>{t.name}</span>
                </td>
                <td className="pts">{r.p}</td>
                <td>{r.j}</td><td>{r.v}</td><td>{r.e}</td><td>{r.d}</td>
                <td>{r.gp}</td><td>{r.gc}</td><td>{r.gp - r.gc}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div className="zone-legend">
        <span><span className="zone-mark zone-lib"></span>Libertadores</span>
        <span><span className="zone-mark zone-pre"></span>Pré-Libertadores</span>
        <span><span className="zone-mark zone-sul"></span>Sul-Americana</span>
        <span><span className="zone-mark zone-rel"></span>Rebaixamento</span>
      </div>
    </section>
  );
};

// ---------- BRACKET (Libertadores / Sul-Americana stub) ----------
const BracketView = ({ comp }) => {
  const pairs = comp === "LIB"
    ? [
      ["FLA", "IDV"], ["PAL", "BOC"], ["BOT", "NAC"], ["FLU", "RIV"],
      ["INT", "LDU"], ["SAO", "PEN"], ["CAM", "COL"], ["CRU", "ATN"],
    ]
    : [
      ["RBB", "ATN"], ["VIT", "CER"], ["CAP", "MIL"], ["JUV", "ALI"],
      ["BAH", "OLI"], ["CEA", "ALI"], ["SPT", "MIL"], ["FOR", "OLI"],
    ];
  return (
    <section className="bracket">
      <div className="table-head">
        <h3>Chaveamento — Oitavas de Final</h3>
        <span className="hint">{comp === "LIB" ? "CONMEBOL Libertadores" : "CONMEBOL Sul-Americana"}</span>
      </div>
      <div className="bracket-grid">
        {pairs.map((p, i) => (
          <div key={i} className="bracket-cell">
            <div className="bteam"><TeamLogo id={p[0]} size={22} /><span>{TEAMS[p[0]].name}</span></div>
            <div className="bteam"><TeamLogo id={p[1]} size={22} /><span>{TEAMS[p[1]].name}</span></div>
          </div>
        ))}
      </div>
    </section>
  );
};

// ---------- APP ----------
const App = () => {
  const [tab, setTab] = useState("ALL");          // ALL | BR | LIB | SUL
  const [view, setView] = useState("matches");    // matches | table | bracket
  const [statusFilter, setStatusFilter] = useState("all"); // all | live | scheduled | finished
  const [search, setSearch] = useState("");
  const [followed, setFollowed] = useState(["m1", "m11"]);
  const [openMatch, setOpenMatch] = useState(null);

  // Persist follows
  useEffect(() => {
    try {
      const saved = localStorage.getItem("golaco.followed");
      if (saved) setFollowed(JSON.parse(saved));
    } catch {}
  }, []);
  useEffect(() => {
    try { localStorage.setItem("golaco.followed", JSON.stringify(followed)); } catch {}
  }, [followed]);

  const toggleFollow = (id) => {
    setFollowed(f => f.includes(id) ? f.filter(x => x !== id) : [...f, id]);
  };

  const filtered = useMemo(() => {
    return MATCHES.filter(m => {
      if (tab !== "ALL" && m.comp !== tab) return false;
      if (statusFilter !== "all" && m.status !== statusFilter) return false;
      if (search.trim()) {
        const q = search.toLowerCase();
        const home = TEAMS[m.home]?.name.toLowerCase() || "";
        const away = TEAMS[m.away]?.name.toLowerCase() || "";
        if (!home.includes(q) && !away.includes(q) && !m.stadium.toLowerCase().includes(q)) return false;
      }
      return true;
    });
  }, [tab, statusFilter, search]);

  const liveMatches = filtered.filter(m => m.status === "live");
  const scheduledMatches = filtered.filter(m => m.status === "scheduled");
  const finishedMatches = filtered.filter(m => m.status === "finished");

  return (
    <div className="app">
      {/* Top Bar */}
      <header className="topbar">
        <div className="brand">
          <div className="brand-mark">
            <span></span><span></span><span></span>
          </div>
          <div className="brand-text">
            <h1>Golaço</h1>
            <span>Resultados · ao vivo</span>
          </div>
        </div>
        <div className="search">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
          <input
            placeholder="Buscar time, estádio…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
          {search && <button className="search-clear" onClick={() => setSearch("")}>×</button>}
        </div>
        <div className="topbar-right">
          <div className="now-pill">
            <span className="live-dot"></span>
            <b>{MATCHES.filter(m => m.status === "live").length}</b> jogos ao vivo
          </div>
        </div>
      </header>

      {/* Competition Tabs */}
      <nav className="tabs">
        {Object.values(COMPS).map(c => (
          <button
            key={c.id}
            className={`tab ${tab === c.id ? "is-active" : ""}`}
            onClick={() => { setTab(c.id); if (c.id === "ALL") setView("matches"); }}
          >
            <span className={`tab-logo tab-${c.id}`}>{c.logo}</span>
            <span className="tab-name">{c.name}</span>
            <span className="tab-count">
              {c.id === "ALL" ? MATCHES.length : MATCHES.filter(m => m.comp === c.id).length}
            </span>
          </button>
        ))}
      </nav>

      {/* Sub-views per comp */}
      {tab !== "ALL" && (
        <div className="subviews">
          <button className={view === "matches" ? "is-active" : ""} onClick={() => setView("matches")}>Jogos</button>
          {tab === "BR" && (
            <button className={view === "table" ? "is-active" : ""} onClick={() => setView("table")}>Classificação</button>
          )}
          {(tab === "LIB" || tab === "SUL") && (
            <button className={view === "bracket" ? "is-active" : ""} onClick={() => setView("bracket")}>Chaveamento</button>
          )}
        </div>
      )}

      {/* Filter row (only on matches view) */}
      {view === "matches" && (
        <div className="filters">
          <div className="filter-pills">
            {[
              { id: "all", label: "Todos", n: filtered.length },
              { id: "live", label: "Ao vivo", n: liveMatches.length },
              { id: "scheduled", label: "Próximos", n: scheduledMatches.length },
              { id: "finished", label: "Encerrados", n: finishedMatches.length },
            ].map(p => (
              <button
                key={p.id}
                className={`pill ${statusFilter === p.id ? "is-active" : ""} ${p.id === "live" ? "is-live" : ""}`}
                onClick={() => setStatusFilter(p.id)}
              >
                {p.id === "live" && <span className="live-dot"></span>}
                {p.label}
                <span className="pill-count">{p.n}</span>
              </button>
            ))}
          </div>
          <div className="filter-meta">
            <span className="hint">{filtered.length} jogos · {COMPS[tab].full}</span>
          </div>
        </div>
      )}

      {/* Followed strip — always visible at top of matches view */}
      {view === "matches" && (
        <FollowedStrip
          matches={MATCHES}
          followed={followed}
          onToggleFollow={toggleFollow}
          onOpen={(m) => setOpenMatch(m)}
        />
      )}

      {/* Main content */}
      {view === "matches" && (
        <main className="main">
          {(statusFilter === "all" || statusFilter === "live") && liveMatches.length > 0 && (
            <Section title="Ao vivo" sub={`${liveMatches.length} em andamento`} accent="live">
              {liveMatches.map(m => (
                <MatchCard key={m.id} match={m} followed={followed.includes(m.id)} onToggleFollow={toggleFollow} onOpen={setOpenMatch} />
              ))}
            </Section>
          )}
          {(statusFilter === "all" || statusFilter === "scheduled") && scheduledMatches.length > 0 && (
            <Section title="Próximos jogos" sub="Agenda dos times brasileiros">
              {scheduledMatches.map(m => (
                <MatchCard key={m.id} match={m} followed={followed.includes(m.id)} onToggleFollow={toggleFollow} onOpen={setOpenMatch} />
              ))}
            </Section>
          )}
          {(statusFilter === "all" || statusFilter === "finished") && finishedMatches.length > 0 && (
            <Section title="Resultados" sub="Últimas rodadas">
              {finishedMatches.map(m => (
                <MatchCard key={m.id} match={m} followed={followed.includes(m.id)} onToggleFollow={toggleFollow} onOpen={setOpenMatch} />
              ))}
            </Section>
          )}
          {filtered.length === 0 && (
            <div className="empty">
              <h3>Nenhum jogo encontrado</h3>
              <p>Tente limpar os filtros ou trocar de aba.</p>
            </div>
          )}
        </main>
      )}

      {view === "table" && tab === "BR" && <TableView />}
      {view === "bracket" && (tab === "LIB" || tab === "SUL") && <BracketView comp={tab} />}

      {/* Drawer */}
      {openMatch && (
        <MatchDrawer
          match={openMatch}
          onClose={() => setOpenMatch(null)}
          followed={followed}
          onToggleFollow={toggleFollow}
        />
      )}
    </div>
  );
};

const Section = ({ title, sub, accent, children }) => (
  <section className={`section ${accent ? `section-${accent}` : ""}`}>
    <header className="section-head">
      <h2>{title}</h2>
      <span className="section-sub">{sub}</span>
    </header>
    <div className="card-grid">{children}</div>
  </section>
);

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
