// ═══════════════ AWARDS PAGE (LIVE + carousel clips + voter) ═══════════════
// - Player & team awards: lit /public/awards-clips?award_id=<id> et /public/config
// - Clips: prévisualisation avec carousel auto-slide
// - Voter: POST /vote-award (à ajouter côté worker)

const AWARDS_DEF = {
  players: [
    { id: 'mvp',        title: 'Meilleur joueur', sub: 'MVP du split' },
    { id: 'rookie',     title: 'Rookie du split', sub: 'Première saison CZF' },
    { id: 'otp',        title: 'Picks exotiques / OTP', sub: 'Le plus original' },
    { id: 'alchimiste', title: "L'alchimiste", sub: 'Transmute n\'importe quel champ en kill' },
    { id: 'duel',       title: 'Meilleur duelliste', sub: 'Le roi du 1v1' },
    { id: 'highlight',  title: 'Highlight du split', sub: 'Le clutch de l\'année' },
  ],
  clips: [
    { id: 'best-play', title: 'Le plus beau play', sub: 'Pentakill, outplay, gros 1v3…' },
    { id: 'funniest',  title: 'Moment le plus drôle', sub: 'Le clip qui a fait marrer le chat' },
    { id: 'wtf',       title: 'WTF moment', sub: 'Le moment incompréhensible' },
    { id: 'wombo',     title: 'Wombo combo', sub: "L'engage parfait" },
  ],
  teams: [
    { id: 'best-team',  title: 'La meilleure équipe', sub: 'Performance d\'ensemble' },
    { id: 'best-run',   title: 'La meilleure run', sub: 'L\'aventure marquante' },
    { id: 'comms',      title: 'Meilleure communication', sub: 'Voice & shot-calling' },
    { id: 'drafts',     title: 'Drafts originales', sub: 'Picks/bans inattendus' },
    { id: 'upset',      title: "L'upset du split", sub: 'La plus grosse surprise' },
    { id: 'coach',      title: 'Coach du split', sub: 'Le meilleur encadrement' },
  ],
};

const AwardsPage = () => {
  return (
    <div className="page-frame grain" data-screen-label="Awards">
      <CZFHeader active="awards" />
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 50% 30% at 50% 8%, rgba(212,168,75,.18), transparent 70%)',
      }} />
      <main style={{ padding: '2.5rem 2.5rem 3rem', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: '2rem' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: '.6rem', color: 'var(--gold)' }}>Vote communautaire</div>
            <h1 className="display" style={{ fontSize: '4.2rem', position: 'relative', display: 'inline-block' }}>
              CZF <span style={{ color: 'var(--gold)' }}>AWARDS</span>
              <svg viewBox="0 0 400 24" style={{ position: 'absolute', left: 0, right: 0, bottom: -10, width: '100%', height: 18 }}>
                <path d="M 5 14 Q 100 6 200 10 T 395 12" stroke="var(--gold)" strokeWidth="4" fill="none" strokeLinecap="round" opacity=".85" />
              </svg>
            </h1>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.9rem', color: 'var(--cream-2)', maxWidth: 580, marginTop: '1.2rem' }}>
              {AWARDS_DEF.players.length + AWARDS_DEF.clips.length + AWARDS_DEF.teams.length} trophées · 3 catégories. Les gagnants seront annoncés à la finale.
            </div>
          </div>
        </div>

        <CategoryHeader n="01" title="Joueurs" sub={`${AWARDS_DEF.players.length} trophées · individuels`} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1rem', marginBottom: '2.5rem' }}>
          {AWARDS_DEF.players.map(a => <SimpleAwardCard key={a.id} award={a} kind="player" />)}
        </div>

        <CategoryHeader n="02" title="Clips" sub={`${AWARDS_DEF.clips.length} trophées · vote sur les clips`} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '1rem', marginBottom: '2.5rem' }}>
          {AWARDS_DEF.clips.map(a => <ClipsAwardCard key={a.id} award={a} />)}
        </div>

        <CategoryHeader n="03" title="Équipes" sub={`${AWARDS_DEF.teams.length} trophées · collectifs`} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1rem' }}>
          {AWARDS_DEF.teams.map(a => <SimpleAwardCard key={a.id} award={a} kind="team" />)}
        </div>
      </main>
    </div>
  );
};

const CategoryHeader = ({ n, title, sub }) => (
  <div style={{ display: 'flex', alignItems: 'baseline', gap: '1rem', marginBottom: '1.25rem', position: 'relative' }}>
    <div style={{ fontFamily: 'var(--fd)', fontSize: '2.6rem', color: 'var(--gold-deep)', letterSpacing: '.04em', lineHeight: 1 }}>{n}</div>
    <div style={{ flex: 1 }}>
      <h2 style={{ fontFamily: 'var(--fd)', fontSize: '2rem', color: 'var(--bone)', letterSpacing: '.06em', lineHeight: 1 }}>{title.toUpperCase()}</h2>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--gold)', marginTop: 3 }}>{sub}</div>
    </div>
    <div style={{ flex: 1, height: 1, background: 'linear-gradient(90deg, var(--gold-deep), transparent)' }} />
  </div>
);

// ── Simple award (player/team) — empty state if no nominees ──
const SimpleAwardCard = ({ award, kind }) => {
  const { data: nominees } = useApi(`/public/awards-nominees?award_id=${award.id}`, []);
  const list = Array.isArray(nominees) ? nominees : [];
  const leader = list[0] || null;
  const totalVotes = list.reduce((acc, n) => acc + (n.votes || 0), 0);
  const [voted, setVoted] = React.useState(() => {
    try { return localStorage.getItem(`czf_award_${award.id}`); } catch { return null; }
  });
  const [voting, setVoting] = React.useState(false);

  const vote = async (nomineeId) => {
    if (voting || voted) return;
    setVoting(true);
    try {
      let sid = localStorage.getItem('czf_session') || ('czf-' + Math.random().toString(36).slice(2));
      localStorage.setItem('czf_session', sid);
      await postApi('/vote-award', { award_id: award.id, nominee_id: nomineeId, session_id: sid });
      localStorage.setItem(`czf_award_${award.id}`, nomineeId);
      setVoted(nomineeId);
    } catch (e) { alert('Erreur : ' + e.message); }
    setVoting(false);
  };

  return (
    <div className="card-paper grain" style={{ padding: '1.1rem 1.2rem 1rem', position: 'relative', overflow: 'hidden' }}>
      <svg viewBox="0 0 200 200" style={{ position: 'absolute', top: -20, right: -30, width: 130, height: 130, opacity: .25, pointerEvents: 'none' }}>
        <path d="M 40 30 Q 100 80 80 140 T 140 200" stroke="#D4A84B" strokeWidth="32" fill="none" strokeLinecap="round" />
      </svg>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--gold-deep)' }}>
        <Icon.Trophy style={{ width: 11, height: 11, verticalAlign: '-2px', marginRight: 4 }} />Trophée
      </div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.3rem', color: 'var(--paper-ink)', letterSpacing: '.04em', lineHeight: 1.05, marginTop: 4 }}>{award.title.toUpperCase()}</div>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--paper-mut)', letterSpacing: '.02em', marginTop: 4, lineHeight: 1.4 }}>{award.sub}</div>

      {leader ? (
        <>
          <div style={{
            marginTop: '.85rem', padding: '.6rem .75rem',
            background: 'rgba(0,0,0,.06)', borderRadius: 3,
            display: 'flex', alignItems: 'center', gap: '.65rem',
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: kind === 'team' ? 3 : '50%',
              background: 'var(--paper-ink)', color: 'var(--gold)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--fd)', fontSize: '1rem',
            }}>{(leader.name || '?')[0].toUpperCase()}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>En tête</div>
              <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', color: 'var(--paper-ink)', letterSpacing: '.03em', lineHeight: 1, marginTop: 1 }}>{(leader.name || '').toUpperCase()}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--fd)', fontSize: '1.2rem', color: 'var(--paper-ink)', lineHeight: 1 }}>
                {totalVotes > 0 ? `${Math.round((leader.votes || 0) / totalVotes * 100)}%` : '—'}
              </div>
              <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>{leader.votes || 0} votes</div>
            </div>
          </div>
        </>
      ) : (
        <div style={{
          marginTop: '.85rem', padding: '.85rem .75rem',
          background: 'rgba(0,0,0,.04)', borderRadius: 3,
          fontFamily: 'var(--fc)', fontSize: '.78rem', color: 'var(--paper-mut)',
          textAlign: 'center', letterSpacing: '.02em',
        }}>Pas encore de nominé</div>
      )}

      <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem', marginTop: '.85rem' }}>
        <span style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', letterSpacing: '.08em', color: 'var(--paper-mut)' }}>{list.length} nominé{list.length > 1 ? 's' : ''}</span>
        <div style={{ marginLeft: 'auto' }}>
          {voted ? (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: '.35rem',
              fontFamily: 'var(--fc)', fontSize: '.7rem', fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
              padding: '.4rem .85rem', borderRadius: 3,
              background: 'rgba(74,222,128,.18)', color: '#16803c', border: '1px solid #16803c',
            }}>★ Voté</span>
          ) : leader ? (
            <button onClick={() => vote(leader.id)} disabled={voting} style={{
              display: 'inline-flex', alignItems: 'center', gap: '.35rem',
              fontFamily: 'var(--fc)', fontSize: '.7rem', fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
              padding: '.4rem .9rem', borderRadius: 3, cursor: voting ? 'wait' : 'pointer',
              background: 'var(--paper-ink)', color: 'var(--paper)', border: 'none',
            }}>{voting ? 'Envoi…' : 'Voter'} <Icon.ChevronR style={{ width: 10, height: 10 }} /></button>
          ) : null}
        </div>
      </div>
    </div>
  );
};

// ── CLIPS CARD with carousel + autoplay slide + voter ──
const ClipsAwardCard = ({ award }) => {
  const { data: clips } = useApi(`/public/awards-clips?award_id=${award.id}`, []);
  const list = Array.isArray(clips) ? clips : [];
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  // Auto-advance every 7 seconds
  React.useEffect(() => {
    if (paused || list.length <= 1) return;
    const t = setInterval(() => setIdx(i => (i + 1) % list.length), 7000);
    return () => clearInterval(t);
  }, [paused, list.length]);

  const [voted, setVoted] = React.useState(() => { try { return localStorage.getItem(`czf_clip_${award.id}`); } catch { return null; } });
  const [voting, setVoting] = React.useState(false);

  const vote = async (clipId) => {
    if (voting || voted) return;
    setVoting(true);
    try {
      let sid = localStorage.getItem('czf_session') || ('czf-' + Math.random().toString(36).slice(2));
      localStorage.setItem('czf_session', sid);
      await postApi('/vote-award', { award_id: award.id, nominee_id: clipId, session_id: sid });
      localStorage.setItem(`czf_clip_${award.id}`, clipId);
      setVoted(clipId);
    } catch (e) { alert('Erreur : ' + e.message); }
    setVoting(false);
  };

  const current = list[idx];

  return (
    <div style={{
      background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 4,
      overflow: 'hidden', position: 'relative',
    }} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      {/* Top banner */}
      <div style={{ padding: '.85rem 1rem .65rem', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--gold)' }}>
            <Icon.Trophy style={{ width: 11, height: 11, verticalAlign: '-2px', marginRight: 4 }} /> Trophée
          </div>
          <div style={{ fontFamily: 'var(--fd)', fontSize: '1.2rem', color: 'var(--bone)', letterSpacing: '.04em', marginTop: 4 }}>{award.title.toUpperCase()}</div>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--muted)', letterSpacing: '.02em', marginTop: 2 }}>{award.sub}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', color: 'var(--muted)', letterSpacing: '.14em', textTransform: 'uppercase' }}>{list.length} clip{list.length > 1 ? 's' : ''}</div>
          {list.length > 0 && <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--gold)', letterSpacing: '.06em', marginTop: 2 }}>{idx + 1} / {list.length}</div>}
        </div>
      </div>

      {/* Clip preview */}
      {list.length === 0 ? (
        <div style={{
          height: 240, background: 'linear-gradient(180deg, var(--char-3), var(--char))',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '.5rem',
          borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
        }}>
          <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', color: 'var(--muted)', letterSpacing: '.05em' }}>AUCUN CLIP SOUMIS</div>
          <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--muted-2)', letterSpacing: '.06em' }}>Les admins peuvent en ajouter via la page Admin</div>
        </div>
      ) : (
        <ClipPreview clip={current} />
      )}

      {/* Bottom bar */}
      {list.length > 0 && (
        <div style={{
          padding: '.75rem 1rem', display: 'flex', alignItems: 'center', gap: '.6rem',
          background: 'rgba(0,0,0,.25)',
        }}>
          {list.length > 1 && (
            <>
              <button onClick={() => { setPaused(true); setIdx((idx - 1 + list.length) % list.length); }} style={navBtnStyle}>‹</button>
              <button onClick={() => { setPaused(true); setIdx((idx + 1) % list.length); }} style={navBtnStyle}>›</button>
            </>
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.8rem', fontWeight: 700, color: 'var(--bone)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{current?.title || '—'}</div>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', color: 'var(--muted)' }}>par {current?.contributor || 'Anonyme'} · {current?.votes || 0} votes</div>
          </div>
          {voted === current?.id ? (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: '.35rem',
              fontFamily: 'var(--fc)', fontSize: '.65rem', fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
              padding: '.32rem .65rem', borderRadius: 3,
              background: 'rgba(74,222,128,.18)', color: 'var(--ok)', border: '1px solid var(--ok)',
            }}>★ Voté</span>
          ) : voted ? (
            <span style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--muted)', letterSpacing: '.08em' }}>Vote enregistré</span>
          ) : (
            <button onClick={() => current && vote(current.id)} disabled={voting} className="btn btn-gold" style={{ padding: '.32rem .75rem', fontSize: '.65rem' }}>
              {voting ? 'Envoi…' : 'Voter pour ce clip'} <Icon.ChevronR style={{ width: 10, height: 10 }} />
            </button>
          )}
        </div>
      )}
    </div>
  );
};

const navBtnStyle = {
  width: 28, height: 28, borderRadius: '50%',
  background: 'rgba(0,0,0,.4)', border: '1px solid var(--border-2)',
  color: 'var(--bone)', fontFamily: 'var(--fd)', fontSize: '1rem', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

// ── Single clip preview — embeds Twitch/YouTube/MP4 ──
const ClipPreview = ({ clip }) => {
  if (!clip || !clip.video_url) {
    return <div style={{ height: 240, background: 'var(--char-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)' }}>—</div>;
  }
  const url = clip.video_url;
  // Twitch clip
  const twitchClipMatch = url.match(/clips\.twitch\.tv\/([\w-]+)/) || url.match(/twitch\.tv\/\w+\/clip\/([\w-]+)/);
  if (twitchClipMatch) {
    const parent = location.hostname || 'localhost';
    return (
      <iframe
        src={`https://clips.twitch.tv/embed?clip=${twitchClipMatch[1]}&parent=${parent}&autoplay=false`}
        style={{ width: '100%', height: 280, border: 'none', display: 'block' }}
        allowFullScreen
      />
    );
  }
  // YouTube
  const ytMatch = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|shorts\/|embed\/))([\w-]+)/);
  if (ytMatch) {
    return (
      <iframe
        src={`https://www.youtube.com/embed/${ytMatch[1]}`}
        style={{ width: '100%', height: 280, border: 'none', display: 'block' }}
        allow="encrypted-media; picture-in-picture"
        allowFullScreen
      />
    );
  }
  // Generic mp4
  if (/\.(mp4|webm|ogv)$/i.test(url)) {
    return (
      <video src={url} controls style={{ width: '100%', height: 280, display: 'block', background: '#000' }} />
    );
  }
  // Fallback : thumbnail + link
  return (
    <div style={{
      height: 240, position: 'relative',
      background: clip.thumbnail
        ? `url(${clip.thumbnail}) center/cover`
        : 'repeating-linear-gradient(135deg, rgba(212,168,75,.08) 0px, rgba(212,168,75,.08) 12px, transparent 12px, transparent 24px), linear-gradient(180deg, var(--char-3), var(--char))',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <a href={url} target="_blank" rel="noopener" style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '.5rem',
        textDecoration: 'none', color: 'var(--bone)',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          background: 'rgba(212,168,75,.2)', border: '1.5px solid var(--gold)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ width: 0, height: 0, borderLeft: '16px solid var(--gold)', borderTop: '9px solid transparent', borderBottom: '9px solid transparent', marginLeft: 4 }} />
        </div>
        <span style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', letterSpacing: '.14em', textTransform: 'uppercase' }}>Voir le clip</span>
      </a>
    </div>
  );
};

Object.assign(window, { AwardsPage });
