/* ============================================================
   app.jsx — root, live polling (55s sync), nav, customize
   panel, Kick hover-preview. Mounts on #app.
   ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;

function hexA(hex, a) { hex = hex.replace('#', ''); if (hex.length === 3) hex = hex.split('').map(c => c + c).join(''); const n = parseInt(hex, 16); return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`; }
function shade(hex, p) { hex = hex.replace('#', ''); if (hex.length === 3) hex = hex.split('').map(c => c + c).join(''); const n = parseInt(hex, 16); let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255; const a = Math.round(2.55 * p); r = Math.max(0, Math.min(255, r + a)); g = Math.max(0, Math.min(255, g + a)); b = Math.max(0, Math.min(255, b + a)); return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }

function applyAccent(hex) {
  const r = document.documentElement;
  r.style.setProperty('--ac', hex);
  r.style.setProperty('--ac-2', shade(hex, -26));
  r.style.setProperty('--ac-hi', shade(hex, 32));
  r.style.setProperty('--ac-soft', hexA(hex, .13));
  r.style.setProperty('--line', hexA(hex, .14));
  r.style.setProperty('--line-2', hexA(hex, .28));
  r.style.setProperty('--glow', `0 0 60px ${hexA(hex, .28)}`);
  r.style.setProperty('--gold-grad', `linear-gradient(135deg, ${shade(hex, 32)}, ${hex} 44%, ${shade(hex, -26)})`);
  r.style.setProperty('--fire-grad', `linear-gradient(140deg, ${shade(hex, 34)} 2%, ${hex} 36%, #ff7a1a 78%, ${shade(hex, -22)})`);
}

const ACCENTS = ['#f5b13d', '#ffb020', '#ff7a1a', '#e7c873'];
const SYNC = 55; // seconds between live syncs

function App() {
  const [tw, setTw] = useState(window.TWEAKS_DEFAULT);
  const [panel, setPanel] = useState(false);
  const [liveData, setLiveData] = useState(null);
  const [refreshing, setRefreshing] = useState(false);
  const [nextIn, setNextIn] = useState(SYNC);
  const isLive = !!(liveData && liveData.isLive);
  const set = (k, v) => setTw(p => ({ ...p, [k]: v }));

  const refreshLive = useCallback(async () => {
    setRefreshing(true);
    try {
      const r = await fetch('/api/live', { cache: 'no-store' });
      if (r.ok) { const d = await r.json(); if (d && typeof d.isLive === 'boolean') setLiveData(d); }
      else { setLiveData(prev => prev || { isLive: false, kick: { live: false }, _fallback: true }); }
    } catch (_) {
      // API unreachable (e.g. static preview) — settle into a clean offline state
      setLiveData(prev => prev || { isLive: false, kick: { live: false }, _fallback: true });
    }
    setRefreshing(false);
    setNextIn(SYNC);
  }, []);

  // apply tweaks to the document
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-fx', tw.fx);
    r.setAttribute('lang', tw.lang);
    r.setAttribute('dir', tw.lang === 'ar' ? 'rtl' : 'ltr');
    applyAccent(tw.accent);
    window.__sfx?.(tw.sound);
  }, [tw]);

  // initial sync + 1s countdown that re-syncs at zero
  useEffect(() => { refreshLive(); }, [refreshLive]);
  useEffect(() => {
    const id = setInterval(() => {
      setNextIn(n => { if (n <= 1) { refreshLive(); return SYNC; } return n - 1; });
    }, 1000);
    return () => clearInterval(id);
  }, [refreshLive]);

  // (re)run reveal after render / language flips
  useEffect(() => { const id = setTimeout(() => window.__reveal?.(), 90); return () => clearTimeout(id); }, [tw.lang, liveData]);

  const t = I18N[tw.lang] || I18N.en;
  return (
    <LangContext.Provider value={{ lang: tw.lang, t }}>
      <Nav isLive={isLive} lang={tw.lang} setLang={v => set('lang', v)} onCustomize={() => setPanel(o => !o)} />
      <Hero isLive={isLive} />
      <LiveNow data={liveData} refreshing={refreshing} onRefresh={refreshLive} nextIn={nextIn} />
      <Stats />
      <Channels />
      <About />
      <Gallery />
      <Community />
      <Footer />
      <CustomizePanel tw={tw} set={set} open={panel} onClose={() => setPanel(false)} />
      <KickPreview />
    </LangContext.Provider>
  );
}

function Nav({ isLive, lang, setLang, onCustomize }) {
  const { t } = React.useContext(LangContext);
  const [sc, setSc] = useState(false);
  useEffect(() => { const f = () => setSc(window.scrollY > 16); f(); addEventListener('scroll', f, { passive: true }); return () => removeEventListener('scroll', f); }, []);
  return (
    <nav className={`nav ${sc ? 'scrolled' : ''}`}>
      <div className="nav__bar">
        <a className="brand" href="#top" onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()} aria-label="7ANTERA">
          <span className="brand__mk"><Logo /></span>
          <span className="brand__wm">{lang === 'ar' ? 'حنتيرة' : '7ANTERA'}</span>
        </a>
        <div className="nav__links">
          <a href="#about" onMouseEnter={() => window.__hover?.()}>{t.navAbout}</a>
          <a href="#live" onMouseEnter={() => window.__hover?.()}>{t.navLive}</a>
          <a href="#channels" onMouseEnter={() => window.__hover?.()}>{t.navChannels}</a>
          <a href="#community" onMouseEnter={() => window.__hover?.()}>{t.navCommunity}</a>
        </div>
        <div className="nav__right">
          <a className="livepill" data-live={isLive} href={`https://kick.com/${KICK_USER}`} target="_blank" rel="noopener noreferrer"
             data-kpv onMouseEnter={() => window.__hover?.()}>
            <span className="dot"></span><span>{isLive ? t.live : t.watchLive}</span>
          </a>
          <div className="langtog" data-l={lang}>
            <button className={lang === 'en' ? 'on' : ''} onClick={() => { setLang('en'); window.__click?.(); }}>EN</button>
            <button className={lang === 'ar' ? 'on' : ''} onClick={() => { setLang('ar'); window.__click?.(); }}>ع</button>
          </div>
          <button className="iconbtn" onClick={() => { onCustomize(); window.__click?.(); }} aria-label={t.czTitle}><Icon.Sliders /></button>
        </div>
      </div>
    </nav>
  );
}

function CustomizePanel({ tw, set, open, onClose }) {
  const { t } = React.useContext(LangContext);
  return (
    <aside className={`cz ${open ? 'open' : ''}`} aria-hidden={!open}>
      <div className="cz__head">
        <span className="cz__title">{t.czTitle}</span>
        <button className="iconbtn" onClick={() => { onClose(); window.__click?.(); }} aria-label={t.czClose}><Icon.Close /></button>
      </div>
      <div className="cz__row">
        <span className="cz__lab">{t.czAccent}</span>
        <div className="cz__swatches">
          {ACCENTS.map(c => (
            <button key={c} className={`cz__sw ${tw.accent === c ? 'on' : ''}`} style={{ background: c }}
              onClick={() => { set('accent', c); window.__click?.(); }} aria-label={c} />
          ))}
        </div>
      </div>
      <div className="cz__row">
        <span className="cz__lab">{t.czFx}</span>
        <div className="cz__seg">
          <button className={tw.fx === 'high' ? 'on' : ''} onClick={() => { set('fx', 'high'); window.__click?.(); }}>{t.czHigh}</button>
          <button className={tw.fx === 'low' ? 'on' : ''} onClick={() => { set('fx', 'low'); window.__click?.(); }}>{t.czLow}</button>
        </div>
      </div>
      <div className="cz__row">
        <span className="cz__lab">{t.czSound}</span>
        <div className="cz__seg">
          <button className={tw.sound ? 'on' : ''} onClick={() => { set('sound', true); window.__click?.(); }}>ON</button>
          <button className={!tw.sound ? 'on' : ''} onClick={() => { set('sound', false); window.__click?.(); }}>OFF</button>
        </div>
      </div>
    </aside>
  );
}

/* Kick hover preview — hovering any [data-kpv] pops an embedded mini-player (desktop). */
function KickPreview() {
  const [show, setShow] = useState(false);
  const [mount, setMount] = useState(false);
  const [pos, setPos] = useState({ top: 0, left: 0 });
  const [muted, setMuted] = useState(true);
  const [vol, setVol] = useState(0.7);
  const hide = useRef(null);

  useEffect(() => {
    if (window.innerWidth < 900) return;
    const W = 480, H = 270, G = 14;
    const open = (el) => {
      clearTimeout(hide.current);
      const r = el.getBoundingClientRect();
      let top = r.bottom + G; if (top + H > innerHeight - 20) top = Math.max(20, r.top - H - G);
      let left = r.left + r.width / 2 - W / 2; left = Math.max(16, Math.min(left, innerWidth - W - 16));
      setPos({ top, left }); setMount(true); setShow(true);
    };
    const sched = () => { clearTimeout(hide.current); hide.current = setTimeout(() => setShow(false), 220); };
    const over = (e) => { const tg = e.target.closest('[data-kpv]'); if (tg) { open(tg); return; } if (e.target.closest('.kpv')) clearTimeout(hide.current); };
    const out = (e) => { const tg = e.target.closest('[data-kpv]'); if (!tg) return; const g = e.relatedTarget; if (g && (g.closest?.('[data-kpv]') || g.closest?.('.kpv'))) return; sched(); };
    const pout = (e) => { if (!e.target.closest('.kpv')) return; const g = e.relatedTarget; if (g && (g.closest?.('[data-kpv]') || g.closest?.('.kpv'))) return; sched(); };
    document.addEventListener('mouseover', over);
    document.addEventListener('mouseout', out);
    document.addEventListener('mouseout', pout);
    return () => { document.removeEventListener('mouseover', over); document.removeEventListener('mouseout', out); document.removeEventListener('mouseout', pout); clearTimeout(hide.current); };
  }, []);

  return (
    <div className={`kpv ${show ? 'show' : ''}`} style={{ top: pos.top, left: pos.left }} aria-hidden={!show}>
      <div className="kpv__v">
        {mount && <iframe key={`k-${muted ? 'm' : 'u'}-${Math.round(vol * 10)}`}
          src={`https://player.kick.com/${KICK_USER}?autoplay=true&muted=${muted}&volume=${vol}`}
          title="7ANTERA live on Kick" allow="autoplay; fullscreen; picture-in-picture" loading="lazy" />}
      </div>
      <div className="kpv__ft">
        <span className="kpv__dot"></span><span>KICK.COM/{KICK_USER.toUpperCase()}</span>
        <span className="kpv__au">
          <button className="kpv__mute" onClick={(e) => { e.preventDefault(); e.stopPropagation(); setMuted(m => !m); }} aria-label={muted ? 'Unmute' : 'Mute'}>
            {muted ? <Icon.VolOff /> : <Icon.VolOn />}
          </button>
          <input className="kpv__vol" type="range" min="0" max="1" step="0.05" value={muted ? 0 : vol}
            onChange={(e) => { const v = parseFloat(e.target.value); setVol(v); setMuted(v === 0); }}
            onClick={(e) => e.stopPropagation()} aria-label="Volume" />
        </span>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
