// Highlights.jsx — Community clip board.
// Henter fra Supabase `highlights`-tabellen med YouTube-embed støtte.
// Stemming lagres i localStorage (ingen auth-krav).
//
// Supabase `highlights`-tabell (opprett ved behov):
//   CREATE TABLE highlights (
//     id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
//     created_at timestamp DEFAULT now(),
//     title text NOT NULL,
//     submitter text,                  -- Discord-navn / Activision ID
//     team_tag text,
//     team_name text,
//     category text DEFAULT 'HIGHLIGHT', -- HIGHLIGHT | CLUTCH | MONTAGE | FUNNY
//     youtube_id text,                 -- YouTube video ID (uten URL)
//     duration text,                   -- f.eks. "0:47"
//     kills int DEFAULT 0,
//     votes int DEFAULT 0,
//     views int DEFAULT 0,
//     featured boolean DEFAULT false,
//     tournament_id uuid REFERENCES tournaments(id)
//   );

// ── YouTube-embed (iframe) ────────────────────────────────────────────────────
function YTEmbed({ youtubeId, title, style = {} }) {
  if (!youtubeId) return null;
  return (
    <iframe
      width="100%"
      height="100%"
      src={`https://www.youtube.com/embed/${youtubeId}?rel=0&modestbranding=1`}
      title={title || "Highlight"}
      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      allowFullScreen
      style={{ border: "none", display: "block", ...style }}
    />
  );
}

// ── Placeholder (ingen video) ─────────────────────────────────────────────────
function VideoPlaceholder({ accent, kills, duration, badge }) {
  return (
    <div className="stream-mock" style={{ width: "100%", height: "100%" }}>
      <div className="stream-mock-scan" />
      <div className="stream-mock-corners"><span/><span/><span/><span/></div>
      {kills > 0 && (
        <div className="hl-hero-kills" style={{ color: accent }}>
          <span className="hl-kills-num">{kills}</span>
          <span className="hl-kills-label">KILLS</span>
        </div>
      )}
      {duration && <div className="hl-hero-dur">{duration}</div>}
      {badge && <div className="hl-hero-badge" style={{ borderColor: accent, color: accent }}>{badge}</div>}
    </div>
  );
}

// ── Tom-tilstand ──────────────────────────────────────────────────────────────
function HighlightsEmpty({ accent }) {
  return (
    <div className="panel" style={{ padding: "60px 40px", textAlign: "center" }}>
      <div style={{ fontSize: 48, marginBottom: 16 }}>🎬</div>
      <div style={{ fontSize: 20, fontWeight: 900, color: "var(--text)", marginBottom: 8 }}>
        INGEN KLIPP ENNÅ
      </div>
      <div style={{ color: "var(--text-dim)", marginBottom: 16 }}>
        Vær den første til å laste opp et klipp! Lag sender inn sine beste øyeblikk.
      </div>
      <div style={{ fontSize: 13, color: "var(--text-faint)", fontFamily: "var(--font-mono)" }}>
        Legges inn i Supabase <code>highlights</code>-tabellen med youtube_id
      </div>
    </div>
  );
}

// ── Clip-kort ─────────────────────────────────────────────────────────────────
function ClipCard({ c, accent, voted, onVote, rankBadge }) {
  return (
    <div className="clip-card">
      <div className="clip-thumb">
        {c.youtube_id
          ? <YTEmbed youtubeId={c.youtube_id} title={c.title} style={{ height: "100%", minHeight: 120 }} />
          : (
            <div className="stream-mock" style={{ height: 120 }}>
              <div className="stream-mock-scan" />
              <div className="stream-mock-corners"><span/><span/><span/><span/></div>
              <div className="clip-play" style={{ borderColor: accent, color: accent }}>▶</div>
              {c.duration && <div className="clip-duration">{c.duration}</div>}
              {rankBadge && (
                <div className="clip-rank-badge" style={{
                  background: rankBadge === "#1" ? accent : "var(--bg-2)",
                  color: rankBadge === "#1" ? "#0a0a0a" : accent,
                  borderColor: accent,
                }}>{rankBadge}</div>
              )}
            </div>
          )
        }
      </div>
      <div className="clip-body">
        <div className="clip-cat">{c.category} · {c.duration || "—"}</div>
        <div className="clip-title">{c.title}</div>
        <div className="clip-team">
          {c.team_tag && <div className="team-tag" style={{ borderColor: accent, color: accent }}>{c.team_tag}</div>}
          <span>{c.submitter || "Ukjent"}</span>
        </div>
      </div>
      <div className="clip-foot">
        <button
          className={`vote-btn ${voted ? "voted" : ""}`}
          style={voted ? { borderColor: accent, color: accent } : null}
          onClick={() => onVote(c.id)}
        >
          <span>▲</span>
          <b>{((c.votes || 0) + (voted ? 1 : 0)).toLocaleString()}</b>
        </button>
        {c.views > 0 && <span className="clip-meta-stat">VIEWS {c.views.toLocaleString()}</span>}
      </div>
    </div>
  );
}

// ── Hoved-komponent ───────────────────────────────────────────────────────────
const HighlightsScreen = ({ tweaks, tab: routeTab }) => {
  const accent = tweaks?.accent || "#ff6b35";

  const [listTab, setListTab] = React.useState("TRENDING");
  const [clips, setClips]     = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [voted, setVoted]     = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("wzn_votes") || "{}"); }
    catch { return {}; }
  });

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true);

    const fetchClips = async () => {
      if (window.db) {
        try {
          const { data } = await window.db
            .from("highlights")
            .select("*")
            .order("created_at", { ascending: false })
            .limit(50);
          if (!cancelled && data) setClips(data);
        } catch (e) {
          console.warn("Highlights fetch feil:", e.message);
        }
      }
      if (!cancelled) setLoading(false);
    };

    fetchClips();
    return () => { cancelled = true; };
  }, []);

  const toggleVote = (id) => setVoted(v => {
    const next = { ...v, [id]: !v[id] };
    try { localStorage.setItem("wzn_votes", JSON.stringify(next)); } catch {}
    return next;
  });

  const featured = clips.find(c => c.featured) || clips[0];
  const rest     = clips.filter(c => c.id !== featured?.id);

  const filtered = (() => {
    if (listTab === "TRENDING") return rest;
    if (listTab === "NEW")  return [...rest].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    if (listTab === "TOP")  return [...rest].sort((a, b) => (b.votes || 0) - (a.votes || 0));
    return rest.filter(c => voted[c.id]);
  })();

  // Sub-route: voting
  if (routeTab === "voting") {
    return <VotingScreen clips={clips.length >= 2 ? clips : []} accent={accent} />;
  }
  // Sub-route: archive
  if (routeTab === "arkiv") {
    return <ArkivScreen clips={clips} accent={accent} voted={voted} onVote={toggleVote} />;
  }

  return (
    <div className="highlights-screen">
      <SectionHeader
        code="07"
        title="HIGHLIGHTS · COMMUNITY"
        subtitle="Klipp lastet opp av lag · stem på de beste"
        accent={accent}
        right={
          <button className="cta cta-primary small" style={{ background: accent, borderColor: accent }}>
            <span>LAST OPP KLIPP</span> <span>↑</span>
          </button>
        }
      />

      {loading && (
        <div className="panel" style={{ padding: 40, textAlign: "center", color: "var(--text-dim)" }}>
          LASTER KLIPP…
        </div>
      )}

      {!loading && clips.length === 0 && <HighlightsEmpty accent={accent} />}

      {!loading && clips.length > 0 && featured && (
        <>
          {/* ── FEATURED HERO ── */}
          <div className="hl-hero panel">
            <div className="hl-hero-video">
              {featured.youtube_id
                ? <YTEmbed youtubeId={featured.youtube_id} title={featured.title} style={{ borderRadius: 2 }} />
                : <VideoPlaceholder accent={accent} kills={featured.kills} duration={featured.duration} badge="UKENS KLIPP" />
              }
            </div>

            <div className="hl-hero-meta">
              <div className="hl-hero-eyebrow">
                <span className="hl-pulse" style={{ color: accent }}>●</span>
                <span style={{ color: accent }}>FEATURED</span>
                {featured.views > 0 && <>
                  <span className="hl-sep">·</span>
                  <span>{featured.views.toLocaleString()} VIEWS</span>
                </>}
              </div>

              <h2 className="hl-hero-title">{featured.title}</h2>

              <div className="hl-hero-player">
                {featured.team_tag && (
                  <div className="team-tag" style={{ borderColor: accent, color: accent }}>{featured.team_tag}</div>
                )}
                <span className="hl-hero-playername">{featured.submitter || "Ukjent"}</span>
                <span className="hl-hero-cat" style={{ borderColor: accent }}>{featured.category}</span>
              </div>

              <div className="hl-hero-stats">
                {featured.views > 0 && (
                  <div className="hl-stat"><span>VIEWS</span><b>{featured.views.toLocaleString()}</b></div>
                )}
                {featured.kills > 0 && (
                  <div className="hl-stat"><span>KILLS</span><b>{featured.kills}</b></div>
                )}
                <div className="hl-stat">
                  <span>LASTET OPP</span>
                  <b>{featured.created_at ? new Date(featured.created_at).toLocaleDateString("no-NO", { day: "numeric", month: "short" }) : "—"}</b>
                </div>
              </div>

              <div className="hl-hero-actions">
                <button
                  className={`hl-vote-hero ${voted[featured.id] ? "voted" : ""}`}
                  style={voted[featured.id] ? { borderColor: accent, color: accent, background: `${accent}18` } : {}}
                  onClick={() => toggleVote(featured.id)}
                >
                  <span className="hl-vote-arrow">▲</span>
                  <span className="hl-vote-count">{((featured.votes || 0) + (voted[featured.id] ? 1 : 0)).toLocaleString()}</span>
                  <span className="hl-vote-lbl">{voted[featured.id] ? "STEMT" : "STEM OPP"}</span>
                </button>
                <button className="hl-ghost-btn">DEL ↗</button>
              </div>
            </div>
          </div>

          {/* ── CLIP GRID ── */}
          {rest.length > 0 && (
            <div className="panel">
              <div className="hl-grid-head">
                <div className="tabs">
                  {[
                    { id: "TRENDING", code: "01", label: "TRENDING" },
                    { id: "NEW",      code: "02", label: "NYESTE" },
                    { id: "TOP",      code: "03", label: "TOPP" },
                    { id: "MINE",     code: "04", label: "MINE STEMMER" },
                  ].map(t => (
                    <button
                      key={t.id}
                      className={`tab ${listTab === t.id ? "active" : ""}`}
                      onClick={() => setListTab(t.id)}
                    >
                      <span className="tab-code">{t.code}</span>{t.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="clip-grid">
                {filtered.length === 0 ? (
                  <div style={{ gridColumn: "1/-1", padding: "32px 0", color: "var(--text-dim)", textAlign: "center" }}>
                    {listTab === "MINE" ? "Du har ikke stemt på noen klipp ennå." : "Ingen klipp å vise."}
                  </div>
                ) : (
                  filtered.map((c, idx) => (
                    <ClipCard
                      key={c.id}
                      c={c}
                      accent={accent}
                      voted={!!voted[c.id]}
                      onVote={toggleVote}
                      rankBadge={listTab === "TOP" && idx < 3 ? `#${idx + 1}` : null}
                    />
                  ))
                )}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

// ── Head-to-head VOTING screen ────────────────────────────────────────────────
const VotingScreen = ({ clips, accent }) => {
  const [round, setRound]   = React.useState(0);
  const [choice, setChoice] = React.useState(null);
  const [scores, setScores] = React.useState({});

  // Lag par fra clips
  const pairs = [];
  for (let i = 0; i + 1 < clips.length && pairs.length < 3; i += 2) {
    pairs.push([clips[i], clips[i + 1]]);
  }

  if (pairs.length < 1) {
    return (
      <div className="highlights-screen">
        <SectionHeader code="VOT" title="CLIP VOTING" subtitle="Trenger minst 2 klipp" accent={accent} />
        <div className="panel" style={{ padding: 40, textAlign: "center", color: "var(--text-dim)" }}>
          Ikke nok klipp for voting ennå.
        </div>
      </div>
    );
  }

  const pair    = pairs[Math.min(round, pairs.length - 1)];
  const hasVoted = choice !== null;
  const done    = round >= pairs.length - 1 && hasVoted;

  const handleVote = (side) => {
    if (hasVoted) return;
    setChoice(side);
    setScores(s => ({ ...s, [round]: side }));
  };

  const nextRound = () => { setChoice(null); setRound(r => r + 1); };

  return (
    <div className="highlights-screen">
      <SectionHeader
        code="VOT"
        title="CLIP VOTING"
        subtitle={`Runde ${round + 1} av ${pairs.length} · Velg det beste klippet`}
        accent={accent}
      />

      <div className="voting-progress panel">
        <div className="vp-bar">
          {pairs.map((_, i) => (
            <div key={i} className={`vp-seg ${i < round ? "done" : i === round ? "active" : ""}`}
              style={i <= round ? { background: i === round ? accent : `${accent}60` } : {}} />
          ))}
        </div>
      </div>

      <div className={`voting-arena ${hasVoted ? "voted" : ""}`}>
        {["A", "B"].map((side, si) => {
          const c = pair[si];
          return (
            <div key={side}
              className={`va-clip ${choice === side ? "winner" : choice && choice !== side ? "loser" : ""}`}
              onClick={() => handleVote(side)}
            >
              <div className="va-thumb">
                {c.youtube_id
                  ? <YTEmbed youtubeId={c.youtube_id} title={c.title} style={{ height: 180 }} />
                  : (
                    <div className="stream-mock va-mock">
                      <div className="stream-mock-scan" />
                      <div className="stream-mock-corners"><span/><span/><span/><span/></div>
                      <div className="va-play" style={{ borderColor: accent, color: accent }}>▶</div>
                      {hasVoted && (
                        <div className="va-pct-overlay" style={choice === side ? { background: `${accent}28`, borderColor: accent } : {}}>
                          <span className="va-pct" style={choice === side ? { color: accent } : {}}>{side === "A" ? 62 : 38}%</span>
                          {choice === side && <span className="va-winner-tag" style={{ color: accent }}>VINNER ✓</span>}
                        </div>
                      )}
                    </div>
                  )
                }
              </div>
              <div className="va-meta">
                {c.team_tag && <div className="va-tag" style={{ borderColor: accent, color: accent }}>{c.team_tag}</div>}
                <div className="va-title">{c.title}</div>
                <div className="va-cat">{c.category} · {c.duration || "—"}</div>
              </div>
              {!hasVoted && <div className="va-cta" style={{ borderColor: accent, color: accent }}>STEM PÅ DETTE ▲</div>}
            </div>
          );
        })}

        <div className="va-vs">
          <div className="va-vs-line" />
          <div className="va-vs-text" style={{ borderColor: accent, color: accent }}>VS</div>
          <div className="va-vs-line" />
        </div>
      </div>

      {hasVoted && !done && (
        <div style={{ textAlign: "center", marginTop: 20 }}>
          <button className="cta cta-primary" style={{ background: accent, borderColor: accent }} onClick={nextRound}>
            <span>NESTE MATCHUP</span><span>▶</span>
          </button>
        </div>
      )}

      {done && (
        <div className="va-done panel">
          <div className="va-done-title" style={{ color: accent }}>VOTING FULLFØRT</div>
          <div className="va-done-sub">Resultater oppdateres etter stemmefristen. Takk for deltakelsen!</div>
        </div>
      )}
    </div>
  );
};

// ── Archive screen ────────────────────────────────────────────────────────────
const ArkivScreen = ({ clips, accent, voted, onVote }) => (
  <div className="highlights-screen">
    <SectionHeader code="ARK" title="KLIPP-ARKIV" subtitle="Alle innsendte klipp · sortert etter sesong" accent={accent} />
    <div className="panel">
      {clips.length === 0 ? (
        <div style={{ padding: "40px 0", textAlign: "center", color: "var(--text-dim)" }}>Ingen arkiverte klipp ennå.</div>
      ) : (
        <div className="clip-grid">
          {clips.map((c) => (
            <ClipCard key={c.id} c={c} accent={accent} voted={!!voted[c.id]} onVote={onVote} />
          ))}
        </div>
      )}
    </div>
  </div>
);

Object.assign(window, { HighlightsScreen });
