/* ============================================================
   Sections — Hero, LiveNow, Stats, Channels, About, Gallery,
   Community, Footer. Pure presentational; live data + polling
   live in app.jsx.
   ============================================================ */
const { useContext: useCtx } = React;

const KICK_USER = '7anteraagaming';
const CHANNELS = [
  { key: 'kick',      name: 'KICK',      handle: 'kick.com/7anteraagaming', url: 'https://kick.com/7anteraagaming',                            color: '#53fc18', icon: 'Kick' },
  { key: 'instagram', name: 'INSTAGRAM', handle: '@Muhhamedemaad',          url: 'https://www.instagram.com/Muhhamedemaad',                    color: '#e1306c', icon: 'Instagram' },
  { key: 'facebook',  name: 'FACEBOOK',  handle: 'muhhamed.emaad',          url: 'https://www.facebook.com/muhhamed.emaad/',                   color: '#1877f2', icon: 'Facebook' },
  { key: 'tiktok',    name: 'TIKTOK',    handle: '@7anteragaming',          url: 'https://www.tiktok.com/@7anteragaming',                      color: '#25f4ee', icon: 'TikTok' },
  { key: 'whatsapp',  name: 'WHATSAPP',  handle: 'Official channel',        url: 'https://www.whatsapp.com/channel/0029VbB1ujpBPzjdsZyQsT0n',  color: '#25d366', icon: 'WhatsApp' },
];

function Logo({ className }) {
  return <img src="assets/crest.jpg" alt="7ANTERA" className={className} decoding="async" />;
}

function SecHead({ tag, icon, children }) {
  const IC = (window.Icon[icon]) || window.Icon.Star;
  return (
    <div className="sec__head">
      <div className="tag rv"><span className="tag__star"><IC /></span>{tag}</div>
      <h2 className="h-sec rv" style={{ transitionDelay: '.08s' }}>{children}</h2>
    </div>
  );
}

/* hero rotating phrase */
function RotatingLine() {
  const { t } = useCtx(LangContext);
  const items = t.heroRotate || [];
  const [idx, setIdx] = React.useState(0);
  const [show, setShow] = React.useState(true);
  React.useEffect(() => {
    setIdx(0); setShow(true);
    if (items.length < 2) return;
    let alive = true;
    const id = setInterval(() => {
      setShow(false);
      setTimeout(() => { if (alive) { setIdx(p => (p + 1) % items.length); setShow(true); } }, 420);
    }, 2600);
    return () => { alive = false; clearInterval(id); };
  }, [t]);
  return (
    <div className="hero__rotate rv" style={{ transitionDelay: '.18s' }}>
      <span className={`hero__rotate-i ${show ? 'show' : ''}`}>{items[idx]}</span>
    </div>
  );
}

/* ---------------- HERO ---------------- */
function Hero({ isLive }) {
  const { t } = useCtx(LangContext);
  const KICK = `https://kick.com/${KICK_USER}`;
  const Crest3D = window.Crest3D;
  return (
    <header className="hero" id="top">
      <div className="app-pad hero__in">
        <div className="hero__copy">
          <div className="tag hero__kick rv"><span className="tag__star"><Icon.Crown /></span>{t.heroKicker}</div>
          <h1 className="hero__name rv" style={{ transitionDelay: '.04s' }}>{t.heroName}</h1>
          <p className="hero__sub rv" style={{ transitionDelay: '.12s' }}>{t.heroSub}</p>
          <RotatingLine />
          <div className="hero__cta rv" style={{ transitionDelay: '.24s' }}>
            <a className="btn btn-primary" href={KICK} target="_blank" rel="noopener noreferrer"
               data-kpv onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
              <Icon.Kick /><span>{t.heroWatch}</span>
            </a>
            <a className="btn btn-ghost" href="#channels" onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
              <Icon.Arrow /><span>{t.heroChannels}</span>
            </a>
          </div>
        </div>

        <div className="crest rv rv-s">
          <span className="crest__rays" aria-hidden="true"></span>
          <span className="crest__halo" aria-hidden="true"></span>
          <span className="crest__ring" aria-hidden="true"></span>
          {Crest3D ? <Crest3D /> : <img className="crest3d__fallback" src="assets/crest.jpg" alt="7ANTERA crest" />}
          <a className="crest__live" data-live={isLive} href="#live"
             onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
            <span className="dot"></span><span>{isLive ? t.liveTag : t.offTag}</span>
          </a>
        </div>
      </div>

      <a className="scrollcue" href="#live" aria-label={t.scroll} onClick={() => window.__click?.()}>
        <span>{t.scroll}</span>
        <span className="scrollcue__mouse"><i></i></span>
      </a>
    </header>
  );
}

/* ---------------- LIVE CONSOLE (auto-sync every 55s) ---------------- */
function LiveNow({ data, refreshing, onRefresh, nextIn }) {
  const { t } = useCtx(LangContext);
  const KICK = `https://kick.com/${KICK_USER}`;
  const k = data && data.kick;
  const live = !!(k && k.live);
  const fmtNum = (n) => (typeof n === 'number') ? n.toLocaleString('en-US') : null;
  const title = (k && k.title) ? k.title : '';
  const viewers = k ? fmtNum(k.viewers) : null;
  const category = (k && k.category) ? k.category : '';
  const p = Math.max(0, Math.min(1, (55 - (nextIn ?? 55)) / 55));

  return (
    <section className="sec live" id="live">
      <div className="app-pad">
        <div className={`liveband rv rv-s ${live ? 'is-live' : (data ? 'is-off' : 'is-load')}`}>
          <span className="liveband__bg" aria-hidden="true"></span>

          <div className="liveband__top">
            <span className={`livestat ${live ? 'on' : ''}`}>
              <span className="livestat__dots"><i></i></span>
              {live ? t.liveNowLab : t.offlineLab}
            </span>
            <a className="liveband__url" href={KICK} target="_blank" rel="noopener noreferrer"
               onMouseEnter={() => window.__hover?.()}>kick.com/{KICK_USER}</a>
          </div>

          {live ? (
            <div className="liveband__grid">
              <div className="livestage">
                <iframe src={`https://player.kick.com/${KICK_USER}?muted=true&autoplay=true`}
                  title="7ANTERA live on Kick" allow="autoplay; fullscreen; picture-in-picture" loading="lazy" />
                <span className="livestage__badge"><span className="dot2"></span>LIVE</span>
                {viewers && <span className="livestage__vc"><Icon.Eye />{viewers}</span>}
              </div>
              <div className="liveband__info">
                <div className="liveband__lab"><span className="livedot"></span>{t.liveWatching}</div>
                <h3 className="liveband__title">{title || t.liveTitleFallback}</h3>
                <div className="liveband__meta">
                  {viewers && <span className="livepill2"><Icon.Eye /><b>{viewers}</b><span>{t.viewersLab}</span></span>}
                  {category && <span className="livepill2"><Icon.Gamepad /><span>{category}</span></span>}
                </div>
                <a className="btn btn-primary liveband__cta" href={KICK} target="_blank" rel="noopener noreferrer"
                   data-kpv onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
                  <Icon.Kick /><span>{t.heroWatch}</span><Icon.Ext />
                </a>
              </div>
            </div>
          ) : (
            <div className="liveband__off">
              <span className="liveband__offic">{data ? <Icon.Shield /> : <Icon.Refresh />}</span>
              <h3 className="liveband__title liveband__title--off">{data ? t.liveOfflineTitle : t.liveLoading}</h3>
              {data && <p className="liveband__sub">{t.liveOfflineSub}</p>}
              {data &&
                <a className="btn btn-primary liveband__cta" href={KICK} target="_blank" rel="noopener noreferrer"
                   data-kpv onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
                  <Icon.Kick /><span>{t.heroWatch}</span><Icon.Ext />
                </a>}
            </div>
          )}

          <div className="liveband__foot">
            <span className="liveband__auto">
              <span className="sync-ring" style={{ '--p': p }}><span>{Math.max(0, Math.round(nextIn ?? 55))}</span></span>
              {t.syncAuto}
            </span>
            <button className={`refreshbtn ${refreshing ? 'spin' : ''}`} onClick={() => { onRefresh && onRefresh(); window.__click?.(); }}
               onMouseEnter={() => window.__hover?.()} aria-label={t.refreshNow}>
              <Icon.Refresh /><span>{refreshing ? t.syncNow : t.refreshNow}</span>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- STATS RAIL ---------------- */
function Stats() {
  const { t } = useCtx(LangContext);
  return (
    <section className="sec stats">
      <div className="app-pad">
        <div className="stats__rail rv rv-s">
          {t.stats.map((s, i) => (
            <div className="stat" key={i}>
              <div className="stat__v">{s.v}</div>
              <div className="stat__l">{s.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- CHANNELS ---------------- */
function Channels() {
  const { t } = useCtx(LangContext);
  return (
    <section className="sec" id="channels">
      <div className="app-pad">
        <SecHead tag={t.navChannels} icon="Star">
          <span className="rv">{t.chTitleA}</span>{' '}
          <span className="rv" style={{ color: 'var(--ac)' }}>{t.chTitleB}</span>
        </SecHead>
        <p className="lead rv" style={{ marginBottom: '40px' }}>{t.chSub}</p>
        <div className="hub">
          {CHANNELS.map((c, i) => {
            const IC = Icon[c.icon];
            const kick = c.key === 'kick';
            return (
              <a key={c.key} className="plaque rv" href={c.url} target="_blank" rel="noopener noreferrer"
                 data-tilt="5" style={{ '--pc': c.color, transitionDelay: `${i * 0.05}s` }}
                 {...(kick ? { 'data-kpv': '' } : {})}
                 onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
                <span className="plaque__tok"><IC /></span>
                <span className="plaque__mid">
                  <span className="plaque__name">{c.name}</span>
                  <span className="plaque__handle">{c.handle}</span>
                </span>
                <span className="plaque__act">
                  <span className="plaque__act-txt">{t.act[c.key]}</span>
                  <span className="plaque__arrow"><Icon.Arrow /></span>
                </span>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------------- ABOUT ---------------- */
function About() {
  const { t } = useCtx(LangContext);
  const mq = [...t.marquee, ...t.marquee];
  return (
    <section className="sec" id="about">
      <div className="app-pad about__grid">
        <div className="about__art rv rv-l" data-tilt="6">
          <span className="about__halo" aria-hidden="true"></span>
          <div className="about__frame">
            <img src="assets/shot-1.jpg" alt={t.aboutTitle} loading="lazy" decoding="async" />
            <span className="cn tl" aria-hidden="true"></span>
            <span className="cn br" aria-hidden="true"></span>
          </div>
        </div>
        <div className="about__copy">
          <div className="tag rv"><span className="tag__star"><Icon.Shield /></span>{t.aboutTag}</div>
          <div className="about__title rv" style={{ transitionDelay: '.06s' }}>{t.aboutTitle}</div>
          <p className="lead rv" style={{ transitionDelay: '.12s' }}>{t.aboutBody}</p>
          <div className="creds rv" style={{ transitionDelay: '.18s' }}>
            {t.creds.map((c, i) => (
              <div className="cred" key={i}>
                <div className="cred__v">{c.v}</div>
                <div className="cred__l">{c.l}</div>
              </div>
            ))}
          </div>
          <div className="tags rv" style={{ transitionDelay: '.24s' }}>
            {t.tags.map(x => <span key={x}>{x}</span>)}
          </div>
        </div>
      </div>
      <div className="app-pad">
        <div className="mq">
          <div className="mq__track">
            <i><span>{mq.map((w, k) => <React.Fragment key={k}>{w}<b><Icon.Star /></b></React.Fragment>)}</span></i>
            <i aria-hidden="true"><span>{mq.map((w, k) => <React.Fragment key={'b' + k}>{w}<b><Icon.Star /></b></React.Fragment>)}</span></i>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- GALLERY (pinned scroll-stack deck) ----------------
   The section pins while you scroll through it; each photo slides in
   from the right and stacks onto the deck (right to left). On mobile,
   reduced-motion, or without GSAP it degrades to a plain vertical list. */
function Gallery() {
  const { t } = useCtx(LangContext);
  const stageRef = React.useRef(null);
  const shots = [
    { src: 'assets/shot-2.jpg', cap: t.shots[2], focus: '50% 30%' },
    { src: 'assets/crest.jpg',  cap: t.shots[0], focus: '50% 50%' },
    { src: 'assets/shot-1.jpg', cap: t.shots[1], focus: '50% 26%' },
  ];

  React.useEffect(() => {
    const gsap = window.gsap;
    const ScrollTrigger = window.ScrollTrigger;
    const stage = stageRef.current;
    const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (!gsap || !ScrollTrigger || !stage || reduceMotion || window.innerWidth < 800) return;

    gsap.registerPlugin(ScrollTrigger);
    stage.classList.add('is-pinned');
    const scene = gsap.context(() => {
      const cards = gsap.utils.toArray('.gcard', stage);
      cards.forEach((card, i) => gsap.set(card, {
        xPercent: i === 0 ? 0 : 128,
        rotation: i === 0 ? 0 : 9,
        opacity: i === 0 ? 1 : 0,
      }));
      const timeline = gsap.timeline({
        scrollTrigger: {
          trigger: stage, start: 'top top', end: '+=' + (cards.length - 1) * 85 + '%',
          pin: true, scrub: 0.8, anticipatePin: 1, invalidateOnRefresh: true,
        },
      });
      for (let i = 1; i < cards.length; i++) {
        timeline
          .to(cards.slice(0, i), { xPercent: (k) => -9 * (i - k), rotation: (k) => -3.5 * (i - k), ease: 'power2.inOut' }, i - 1)
          .to(cards[i], { xPercent: 0, rotation: 0, opacity: 1, ease: 'power3.out' }, '<');
      }
    }, stage);
    return () => { scene.revert(); stage.classList.remove('is-pinned'); };
  }, []);

  return (
    <section className="sec gal" id="gallery">
      <div className="app-pad">
        <SecHead tag={t.galTag} icon="Sparkle">{t.galTitle}</SecHead>
        <p className="lead rv">{t.galSub}</p>
      </div>
      <div className="gal__stage" ref={stageRef}>
        <div className="gal__deck">
          {shots.map((s, i) => (
            <figure className="gcard" key={i} style={{ zIndex: i + 1 }}>
              <img src={s.src} alt={s.cap} loading="lazy" decoding="async" style={{ objectPosition: s.focus }} />
              <figcaption className="gcard__cap"><Icon.Sparkle />{s.cap}</figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- COMMUNITY ---------------- */
function Community() {
  const { t } = useCtx(LangContext);
  const W = CHANNELS.find(c => c.key === 'whatsapp');
  return (
    <section className="sec" id="community">
      <div className="app-pad">
        <SecHead tag={t.commTag} icon="Users">{t.commTitle}</SecHead>
        <p className="lead rv" style={{ marginBottom: '40px' }}>{t.commBody}</p>
        <div className="comm__grid">
          <div className="panel rv rv-l" data-tilt="5">
            <span className="panel__ic"><Icon.WhatsApp /></span>
            <h3>WhatsApp</h3>
            <p>{t.commWaBody}</p>
            <a className="btn btn-primary panel__cta" href={W.url} target="_blank" rel="noopener noreferrer"
               onMouseEnter={() => window.__hover?.()} onClick={() => window.__click?.()}>
              <Icon.WhatsApp /><span>{t.whatsappCta}</span>
            </a>
          </div>
          <div className="panel rv rv-r" data-tilt="5">
            <span className="panel__ic"><Icon.Sparkle /></span>
            <h3>{t.followCta}</h3>
            <p>{t.chSub}</p>
            <div className="footer__soc" style={{ marginTop: 'auto' }}>
              {CHANNELS.map(c => { const IC = Icon[c.icon]; return (
                <a key={c.key} href={c.url} target="_blank" rel="noopener noreferrer" aria-label={c.name}
                   style={{ '--pc': c.color }} onMouseEnter={() => window.__hover?.()}><IC /></a>
              ); })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FOOTER ---------------- */
function Footer() {
  const { t } = useCtx(LangContext);
  const top = (e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); };
  return (
    <footer className="footer">
      <div className="footer__ghost" aria-hidden="true">7ANTERA</div>
      <div className="app-pad footer__in">
        <div className="footer__tag rv">{t.footTagline}</div>
        <div className="footer__soc rv" style={{ transitionDelay: '.08s' }}>
          {CHANNELS.map(c => { const IC = Icon[c.icon]; return (
            <a key={c.key} href={c.url} target="_blank" rel="noopener noreferrer" aria-label={c.name}
               onMouseEnter={() => window.__hover?.()}><IC /></a>
          ); })}
        </div>
        <a className="credit rv" href="https://mohamedmavis.com/" target="_blank" rel="noopener noreferrer"
           style={{ transitionDelay: '.14s' }} onMouseEnter={() => window.__hover?.()} aria-label="MaviS · mohamedmavis.com">
          <span className="credit__mk"><Icon.Crown /></span>
          <span className="credit__txt"><b>MaviS</b><small>mohamedmavis.com</small></span>
          <span className="credit__go"><Icon.Arrow /></span>
        </a>
        <div className="footer__bottom">
          <span>{t.rights}</span>
          <a href="#top" onClick={top} onMouseEnter={() => window.__hover?.()}>{t.backTop} ↑</a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { KICK_USER, CHANNELS, Logo, SecHead, Hero, LiveNow, Stats, Channels, About, Gallery, Community, Footer });
