// home-sections.jsx — featured, pin-scroll, stats, about, marquee
const { useEffect: sUseEffect, useRef: sUseRef, useState: sUseState } = React;

// ----- Script card (used by featured + catalog) -----
function ScriptCard({ s, onOpen, large }) {
  const ref = sUseRef(null);
  const palettes = window.AppData.PALETTES;
  const p = palettes[s.palette % palettes.length];

  sUseEffect(() => {
    const el = ref.current;
    if (!el || !window.ScrollTrigger) return;
    const trig = window.ScrollTrigger.create({
      trigger: el, start: "top 85%",
      onEnter: () => el.classList.add("revealed"),
    });
    return () => trig.kill();
  }, []);

  const swDisplay = { AE: "AE", Blender: "BL", UE5: "UE5" }[s.software] || s.software;

  return (
    <a href={`#/scripts/${s.id}`} ref={ref} className="script-card" data-cursor="ring" data-cursor-label="View"
       onClick={(e)=>{e.preventDefault(); onOpen?.(s.id);}}>
      <div className="script-card__media">
        <div className="blob" style={{ background: `radial-gradient(circle at 30% 30%, ${p[0]} 0%, transparent 55%), radial-gradient(circle at 70% 70%, ${p[1]} 0%, transparent 55%), radial-gradient(circle at 50% 50%, ${p[2]} 0%, transparent 45%)`}}></div>
      </div>
      <div className="script-card__tag">{swDisplay} · {s.category}</div>
      <div className="script-card__hover-cta">View →</div>
      <div className="script-card__bottom">
        <h3 className="script-card__title">{s.title}</h3>
        <div className="script-card__meta">
          <span>v{s.version} · {s.fileSize}</span>
          <span className="price">${s.price}</span>
        </div>
      </div>
    </a>
  );
}

// ----- Marquee -----
function Marquee() {
  const text = ["AE · BLENDER · UE5", "DESIGNED FOR DESIGNERS", "EST. 2021", "AE · BLENDER · UE5", "BERLIN ↔ SHENZHEN"];
  return (
    <div className="marquee">
      <div className="marquee__track">
        {[...text, ...text].map((t, i) => (
          <React.Fragment key={i}><span>{t}</span><span className="dot">●</span></React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ----- Featured strip -----
function Featured({ onOpen }) {
  const scripts = window.AppData.getScripts().slice(0, 6);
  return (
    <section className="featured wrap" data-screen-label="featured">
      <div className="featured__head">
        <div>
          <div className="section-label"><span>Featured drops · 06</span></div>
          <h2>Built for the brief.</h2>
        </div>
        <p className="desc">Each script is shipped after a real production cycle — we use them ourselves before we put a price on them. Pricing covers the source file, presets and a lifetime of patches for this major version.</p>
      </div>
      <div className="scripts-row">
        {scripts.map(s => <ScriptCard key={s.id} s={s} onOpen={onOpen} />)}
      </div>
    </section>
  );
}

// ----- Stats counter -----
function Stats() {
  const ref = sUseRef(null);
  sUseEffect(() => {
    if (!window.ScrollTrigger || !window.gsap) return;
    const counters = ref.current.querySelectorAll("[data-counter]");
    const trigs = [];
    counters.forEach(el => {
      const target = parseFloat(el.getAttribute("data-to"));
      const suffix = el.getAttribute("data-suffix") || "";
      const dec = el.getAttribute("data-dec") ? parseInt(el.getAttribute("data-dec"), 10) : 0;
      const obj = { v: 0 };
      const trig = window.ScrollTrigger.create({
        trigger: el, start: "top 85%",
        onEnter: () => {
          window.gsap.to(obj, {
            v: target, duration: 2.2, ease: "power3.out",
            onUpdate: () => { el.textContent = obj.v.toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + suffix; }
          });
        }
      });
      trigs.push(trig);
    });
    return () => trigs.forEach(t => t.kill());
  }, []);

  return (
    <section className="stats" ref={ref} data-screen-label="stats">
      <div className="wrap">
        <div className="stats__grid">
          <div className="stat-cell">
            <div className="stat-cell__num"><span data-counter data-to="92">0</span><span className="suffix">+</span></div>
            <div className="stat-cell__label">scripts shipped</div>
          </div>
          <div className="stat-cell">
            <div className="stat-cell__num"><span data-counter data-to="14820">0</span></div>
            <div className="stat-cell__label">creators using daily</div>
          </div>
          <div className="stat-cell">
            <div className="stat-cell__num"><span data-counter data-to="4.9" data-dec="1">0</span><span className="suffix"> ★</span></div>
            <div className="stat-cell__label">average rating</div>
          </div>
          <div className="stat-cell">
            <div className="stat-cell__num"><span data-counter data-to="38">0</span><span className="suffix">%</span></div>
            <div className="stat-cell__label">save with annual</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ----- Pin section (3 panels horizontal scroll) -----
function PinStage() {
  const wrap = sUseRef(null);
  const inner = sUseRef(null);
  const track = sUseRef(null);

  sUseEffect(() => {
    if (!window.ScrollTrigger || !window.gsap) return;
    const trackEl = track.current;
    const panels = trackEl.querySelectorAll(".pin-stage__panel");
    const totalWidth = trackEl.scrollWidth - window.innerWidth + 64;
    const trig = window.gsap.to(trackEl, {
      x: -totalWidth, ease: "none",
      scrollTrigger: { trigger: wrap.current, start: "top top", end: () => "+=" + totalWidth, scrub: 0.6, pin: inner.current, anticipatePin: 1, invalidateOnRefresh: true }
    });
    // Subtle parallax on numbers within panels
    panels.forEach(p => {
      const num = p.querySelector(".num");
      if (num) window.gsap.to(num, { yPercent: -20, scrollTrigger: { trigger: p, start: "left right", end: "right left", scrub: true, horizontal: false } });
    });
    return () => { trig.kill(); window.ScrollTrigger.refresh(); };
  }, []);

  return (
    <section className="pin-stage" ref={wrap} data-screen-label="process">
      <div className="pin-stage__inner" ref={inner}>
        <div className="pin-stage__track" ref={track}>
          <article className="pin-stage__panel">
            <div className="blob" style={{ background: "radial-gradient(circle at 30% 30%, #ff3366 0%, transparent 60%)" }}></div>
            <div className="num">01</div>
            <div className="label">Process · 01</div>
            <h3>We design with the script we are about to ship.</h3>
            <p>Every release goes through a 2-week internal production where we use it on real client work. If it breaks the brief, it doesn't ship. If it ships, it's already been through the fire.</p>
          </article>
          <article className="pin-stage__panel">
            <div className="blob" style={{ background: "radial-gradient(circle at 70% 30%, #3d7aff 0%, transparent 60%)" }}></div>
            <div className="num">02</div>
            <div className="label">Process · 02</div>
            <h3>Source files. Always. No watermarks. No gating.</h3>
            <p>You get the unencrypted source — JSX, .blend, .uasset. Open it, fork it, ship your version. The licence covers commercial use up to a per-script revenue cap; members get unlimited.</p>
          </article>
          <article className="pin-stage__panel">
            <div className="blob" style={{ background: "radial-gradient(circle at 50% 70%, #1eff8d 0%, transparent 60%)" }}></div>
            <div className="num">03</div>
            <div className="label">Process · 03</div>
            <h3>Patches for life on a major version.</h3>
            <p>Once you own v2 of a script, every v2.x update is free — forever. We patch for the editor versions we say we support, and we ship breaking changes only with a migration script.</p>
          </article>
          <article className="pin-stage__panel">
            <div className="blob" style={{ background: "radial-gradient(circle at 30% 70%, #ffd93d 0%, transparent 60%)" }}></div>
            <div className="num">04</div>
            <div className="label">Process · 04</div>
            <h3>A README we actually wrote.</h3>
            <p>Not a wiki, not a Discord, not a YouTube playlist. A flat-text README with the parameters that matter, the gotchas we hit, and the keyboard shortcut we wished we'd known.</p>
          </article>
        </div>
      </div>
    </section>
  );
}

// ----- About -----
function About() {
  const ref = sUseRef(null);
  sUseEffect(() => {
    if (!window.ScrollTrigger || !window.gsap) return;
    const ps = ref.current.querySelectorAll("p, h2");
    const trig = window.ScrollTrigger.create({
      trigger: ref.current, start: "top 70%",
      onEnter: () => { window.gsap.from(ps, { opacity: 0, y: 32, duration: 1.1, ease: "power3.out", stagger: 0.1 }); }
    });
    return () => trig.kill();
  }, []);
  return (
    <section className="about" data-screen-label="about" ref={ref}>
      <div className="wrap about__grid">
        <div>
          <div className="section-label"><span>About the studio</span></div>
          <h2 className="about__title">A two-person studio, shipping the tools we wished existed.</h2>
        </div>
        <div className="about__body">
          <p>We came up motion-designing brand work for clients who paid us to render the impossible on a four-day turnaround. Most weeks ended with the same problem: a tool we needed didn't exist, and the closest one was either gatekept or abandoned.</p>
          <p>So we started writing scripts. First for ourselves, then for the few studios we trusted. Now they're here. The price is what we'd happily pay; the licence is what we'd happily live with.</p>
          <p style={{color:"var(--fg-3)", fontSize:"13px", letterSpacing:"0.1em", textTransform:"uppercase", marginTop:"40px"}}>↘ Aiyana Kov & Jin-ho Park · Berlin ↔ Shenzhen</p>
        </div>
      </div>
    </section>
  );
}

window.HomeSections = { ScriptCard, Marquee, Featured, Stats, PinStage, About };
