/* global React, VideoSlot */
const { useEffect, useRef, useState } = React;

/* ---------- Featured Clients ---------- */
/* Bordered "showcase rail" — pill label top-left, horizontal row of brand
   cards. Each card: square image slot (user drops their own), brand name
   with arrow, two metric rows. Scrolls horizontally on mobile; on desktop
   the rightmost card peeks past the edge to suggest more. */
const CLIENTS = [
  { id: "cli-1", name: "Northwave",   stat1: ["$4.20",  "CPM"], stat2: ["12,400",  "Conversions"] },
  { id: "cli-2", name: "Halocup",     stat1: ["$3.80",  "CPM"], stat2: ["8,950",   "Conversions"] },
  { id: "cli-3", name: "Pebble & Co", stat1: ["$5.10",  "CPM"], stat2: ["21,300",  "Conversions"] },
  { id: "cli-4", name: "Saint Field", stat1: ["$2.90",  "CPM"], stat2: ["18,700",  "Conversions"] },
  { id: "cli-5", name: "Loop Audio",  stat1: ["$4.60",  "CPM"], stat2: ["9,200",   "Conversions"] },
  { id: "cli-6", name: "Foundry",     stat1: ["$3.40",  "CPM"], stat2: ["14,800",  "Conversions"] },
];

function FeaturedClients() {
  const trackRef = useRef(null);
  const railRef  = useRef(null);
  useEffect(() => {
    const track = trackRef.current;
    const rail  = railRef.current;
    if (!track || !rail) return;
    // Don't wire up the hover-slowmo listener on mobile — the rail still
    // animates at FAST speed, but touch interaction doesn't slow it down.
    const isMobile = window.matchMedia("(max-width: 600px)").matches;

    // Track is two copies of CLIENTS side-by-side. We scroll continuously,
    // wrapping back to 0 when we've slid one full copy width (half of total).
    // Driving the position in JS (not CSS animation) lets us change speed
    // mid-flight WITHOUT the position snapping — duration changes on a CSS
    // keyframe animation cause exactly the glitch the user reported.
    let pos = 0;
    let halfWidth = 0;
    let lastTs = performance.now();
    // Speeds in pixels/sec — full speed normally, much slower while hovered.
    const SPEED_FAST = 60;
    const SPEED_SLOW = 16;
    let speed = SPEED_FAST;
    let target = SPEED_FAST;

    const onPointerMove = (e) => {
      const el = document.elementFromPoint(e.clientX, e.clientY);
      target = (el && el.closest && el.closest(".cli-card")) ? SPEED_SLOW : SPEED_FAST;
    };
    const onLeave = () => { target = SPEED_FAST; };
    if (!isMobile) {
      rail.addEventListener("pointermove", onPointerMove, { passive: true });
      rail.addEventListener("pointerleave", onLeave);
    }

    let raf = 0;
    const tick = (ts) => {
      const dt = Math.min(0.05, (ts - lastTs) / 1000);
      lastTs = ts;
      // Initialize once track has measured. We start at -halfWidth so the
      // SECOND copy of the cards is on-screen, and slide rightward toward 0.
      // When pos reaches 0 we jump back to -halfWidth — invisible to the
      // eye because the two copies are identical at that boundary.
      if (halfWidth === 0) {
        halfWidth = track.scrollWidth / 2;
        if (halfWidth > 0) pos = -halfWidth;
      }
      speed += (target - speed) * Math.min(1, dt * 8);
      // POSITIVE delta → cards slide LEFT-TO-RIGHT
      pos += speed * dt;
      if (halfWidth > 0 && pos >= 0) pos -= halfWidth;
      track.style.transform = `translate3d(${Math.round(pos)}px, 0, 0)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      rail.removeEventListener("pointermove", onPointerMove);
      rail.removeEventListener("pointerleave", onLeave);
    };
  }, []);

  return (
    <section className="clients" aria-label="Featured clients">
      <div className="clients-rail" ref={railRef}>
        <div className="clients-pill">
          <span>Creatives Showcase</span>
        </div>
        <div className="clients-marquee">
          <div className="clients-track" ref={trackRef}>
            {[...CLIENTS, ...CLIENTS].map((c, i) => (
              <div className="cli-card" key={c.id + "-" + i}>
                <div className="cli-media">
                  <VideoSlot id={i < CLIENTS.length ? c.id : c.id + "-b"} />
                </div>
                <div className="cli-foot">
                  <div className="cli-name">
                    <span>{c.name}</span>
                  </div>
                  <div className="cli-stats">
                    <div className="cli-stat">
                      <div className="cli-stat-v">{c.stat1[0]}</div>
                      <div className="cli-stat-l">{c.stat1[1]}</div>
                    </div>
                    <div className="cli-stat">
                      <div className="cli-stat-v">{c.stat2[0]}</div>
                      <div className="cli-stat-l">{c.stat2[1]}</div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Marquee ---------- */
const MARQUEE_ITEMS = ["AI UGC", "Product demos", "Talking heads", "B-roll", "Hooks", "Static + motion", "Native exports"];

function Marquee() {
  const trackRef = useRef(null);
  useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    let raf;
    let x = 0;
    const speed = 28; // px/s
    let last = performance.now();
    const w = () => el.scrollWidth / 2;
    const step = (now) => {
      const dt = (now - last) / 1000; last = now;
      x -= speed * dt;
      const ww = w();
      if (-x >= ww) x += ww;
      el.style.transform = `translate3d(${x}px,0,0)`;
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, []);
  const Row = () => (
    <>
      {MARQUEE_ITEMS.map((it, i) => (
        <span className="item" key={i}>
          <span>{it}</span>
          <span className="dotmark"></span>
        </span>
      ))}
    </>
  );
  return (
    <section className="marquee" aria-hidden>
      <div className="marquee-row" ref={trackRef}>
        <Row /><Row />
      </div>
    </section>
  );
}

/* ---------- Services (How do we serve CREATORS?) ---------- */
const PILLARS = [
  {
    id: "money",
    title: "Capture Attention",
    desc: "Hooks and angles built to make your brand stand out in crowded feeds.",
    icon: (
      <svg viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M2.5 14C5 9 9 6.5 14 6.5s9 2.5 11.5 7.5C23 19 19 21.5 14 21.5S5 19 2.5 14z" />
        <circle cx="14" cy="14" r="3.4" />
        <circle cx="14" cy="14" r="1.1" fill="currentColor" stroke="none" />
      </svg>
    ),
  },
  {
    id: "time",
    title: "Save You Time",
    desc: "Turn scripts and concepts into ready-to-test creatives in hours, not days.",
    icon: (
      <svg viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="14" cy="15" r="8.5" />
        <path d="M14 15V10M14 6.5V5M11 5h6" />
      </svg>
    ),
  },
  {
    id: "brand",
    title: "Scale Winning Creatives",
    desc: "Create more ad variations, spot what converts, and scale the winners with confidence.",
    icon: (
      <svg viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 22h20" />
        <rect x="5.5" y="16" width="3.5" height="6" rx="0.6" />
        <rect x="12.25" y="12" width="3.5" height="10" rx="0.6" />
        <rect x="19" y="8" width="3.5" height="14" rx="0.6" />
        <path d="M5 7l6 -3 5 2 7 -4" />
        <path d="M19.5 2h3.5v3.5" />
      </svg>
    ),
  },
];

const COMPARE_ROWS = [
  ["Hooks",                "Limited.",                    "Hook angles built to stop scroll."],
  ["Scalability",          "Capped by creator capacity.", "Scales infinitely."],
  ["Performance Loop",     "Slow A/B testing.",           "Daily testing data → faster wins."],
  ["Turnaround",           "2–4 weeks per shoot.",        "24hrs from brief to ad-ready."],
  ["Brand Consistency",    "Can vary.",                   "More consistent visuals."],
  ["Talent",               "Limited creator pool.",       "Unlimited AI faces & voices."],
  ["Localization",         "Reshoot for each market.",    "Instant language & voice swaps."],
  ["Creative Variations",  "Limited.",                    "Infinite."],
  ["Production",           "Limited.",                    "High volume."],
];

function Services() {
  return (
    <section id="services" className="services-v2">
      <div className="services-v2-inner">
        <div className="services-v2-pillwrap">
          <span className="services-v2-pill">Services</span>
        </div>
        <h2 className="services-v2-title title-reveal reveal">
          <span className="line-1"><span className="title-inner">How do we serve</span></span>
          <span className="line-2"><span className="title-inner">BRANDS?</span></span>
        </h2>

        <div className="pillars pillars-reveal reveal">
          {PILLARS.map((p) => (
            <div className="pillar" key={p.id}>
              <div className="pillar-icon">{p.icon}</div>
              <div className="pillar-title">{p.title}</div>
              <div className="pillar-desc">{p.desc}</div>
            </div>
          ))}
        </div>

        <div className="compare compare-reveal reveal">
          <div className="compare-grid compare-head">
            <div className="compare-col-label">Feature</div>
            <div className="compare-col">
              <div className="compare-col-title">Traditional UGC</div>
            </div>
            <div className="compare-col">
              <div className="compare-col-title">AI Ad Creative System</div>
            </div>
          </div>
          <div className="compare-rows">
            {COMPARE_ROWS.map(([label, trad, ai]) => (
              <div className="compare-grid compare-row" key={label}>
                <div className="compare-row-label">{label}</div>
                <div className="compare-cell compare-text trad">{trad}</div>
                <div className="compare-cell compare-text ai">{ai}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Performance / case studies ---------- */
const AD_TYPES = [
  { id: "ugc",     label: "UGC Ads" },
  { id: "product", label: "Product Ads" },
  { id: "talking", label: "Talking Head" },
];

const CASES = [
  {
    brand: "Mira Glow", type: "ugc",
    sub: "AI UGC · Beauty",
    platform: "TikTok",
    bg: "linear-gradient(165deg,#2b1f25 0%,#140f12 60%,#080608 100%)",
    revenue: 412800, roas: 6.4, delta: "+312% vs control"
  },
  {
    brand: "Atlas Protein", type: "ugc",
    sub: "AI UGC · Health",
    platform: "Meta",
    bg: "linear-gradient(150deg,#2b261d 0%,#15120e 60%,#080706 100%)",
    revenue: 286100, roas: 4.9, delta: "+184% vs control"
  },
  {
    brand: "Foundry App", type: "talking",
    sub: "Talking Head · SaaS",
    platform: "YouTube",
    bg: "linear-gradient(210deg,#22262d 0%,#12141a 60%,#070708 100%)",
    revenue: 1240000, roas: 3.8, delta: "CAC −41%"
  },
  {
    brand: "Brewlab", type: "product",
    sub: "Product Demo · F&B",
    platform: "Meta",
    bg: "linear-gradient(190deg,#1e2128 0%,#0e0f14 60%,#050608 100%)",
    revenue: 198400, roas: 5.6, delta: "+228% vs control"
  },
  {
    brand: "Riftwear", type: "ugc",
    sub: "AI UGC · Apparel",
    platform: "TikTok",
    bg: "linear-gradient(155deg,#352216 0%,#19100a 60%,#090605 100%)",
    revenue: 521600, roas: 5.1, delta: "+267% vs control"
  },
  {
    brand: "Lumen Audio", type: "product",
    sub: "Product Demo · Tech",
    platform: "Reels",
    bg: "linear-gradient(180deg,#18202b 0%,#0c1018 60%,#040608 100%)",
    revenue: 364200, roas: 4.4, delta: "+196% vs control"
  },
  {
    brand: "Verra Skincare", type: "product",
    sub: "Product Demo · Beauty",
    platform: "TikTok",
    bg: "linear-gradient(165deg,#2a2025 0%,#150f12 60%,#070506 100%)",
    revenue: 442100, roas: 5.2, delta: "+218% vs control"
  },
  {
    brand: "Helio Studio", type: "talking",
    sub: "Talking Head · Founder",
    platform: "YouTube",
    bg: "linear-gradient(170deg,#1f2422 0%,#0e1110 60%,#050706 100%)",
    revenue: 482000, roas: 4.2, delta: "+158% vs control"
  },
  {
    brand: "Carbon CRM", type: "talking",
    sub: "Talking Head · SaaS",
    platform: "Meta",
    bg: "linear-gradient(195deg,#1c1f24 0%,#0c0f12 60%,#050608 100%)",
    revenue: 728500, roas: 3.6, delta: "CAC −38%"
  },
];

function fmt(n) {
  if (n >= 1e6) return "$" + (n/1e6).toFixed(2) + "M";
  if (n >= 1e3) return "$" + Math.round(n/1e3) + "K";
  return "$" + n;
}

function useCountUp(target, trigger) {
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!trigger) return;
    let raf;
    const start = performance.now();
    const dur = 1400;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / dur);
      // easeOutExpo
      const e = t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
      setV(target * e);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, trigger]);
  return v;
}

function PerfCard({ c, idx }) {
  const cardRef = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = cardRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && setVis(true)),
      { threshold: 0.3 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const rev = useCountUp(c.revenue, vis);
  const roas = useCountUp(c.roas, vis);

  // Waveform bars on the media (smaller)
  const mini = Array.from({ length: 18 }, (_, i) => {
    const h = 30 + ((i * 13 + idx * 7) % 60);
    const delay = -((Math.sin(i * 0.7 + idx) + 1) / 2) * 1.2;
    const dur = 1 + ((i * 5 + idx * 11) % 6) * 0.07;
    return { h, delay, dur };
  });

  return (
    <article className="perf-card" ref={cardRef}>
      <div className="perf-media">
        {/* User-uploadable MP4. Click empty tile to browse or drag-drop. */}
        <VideoSlot id={`perf-${c.brand.replace(/\W+/g, "-").toLowerCase()}`} />
      </div>
      <div className="perf-body">
        <div className="brand">{c.brand}</div>
        <div className="sub">{c.sub}</div>
      </div>
    </article>
  );
}

function Performance() {
  const [active, setActive] = useState(AD_TYPES[0].id);
  const [page, setPage] = useState(0);
  const railRef = useRef(null);
  const filtered = CASES.filter((c) => c.type === active);

  // Reset to first slide whenever the user switches tabs — so the rail
  // doesn't appear scrolled past the new tab's first card.
  useEffect(() => {
    setPage(0);
    if (railRef.current) railRef.current.scrollTo({ left: 0, behavior: "instant" });
  }, [active]);

  // Track which card is centered while scrolling, on mobile only. Each card
  // is roughly viewport-wide so we divide scrollLeft by card-stride to get
  // the active page index.
  useEffect(() => {
    const rail = railRef.current;
    if (!rail) return;
    const onScroll = () => {
      const card = rail.querySelector(".perf-card");
      if (!card) return;
      const stride = card.getBoundingClientRect().width + 14; // 14 = gap
      const idx = Math.round(rail.scrollLeft / stride);
      setPage(Math.max(0, Math.min(filtered.length - 1, idx)));
    };
    rail.addEventListener("scroll", onScroll, { passive: true });
    return () => rail.removeEventListener("scroll", onScroll);
  }, [filtered.length]);

  const goTo = (i) => {
    const rail = railRef.current;
    if (!rail) return;
    const card = rail.querySelector(".perf-card");
    if (!card) return;
    const stride = card.getBoundingClientRect().width + 14;
    rail.scrollTo({ left: stride * i, behavior: "smooth" });
  };

  return (
    <section id="performance" className="section">
      <div className="shell">
        <div className="section-head">
          <div className="section-head-center">
            <span className="scale-pill">What We Ship</span>
            <h2 className="section-title perf-title title-reveal reveal">
              <span className="line-1"><span className="title-inner">Ads that print</span></span>
              <span className="line-2"><span className="title-inner">REVENUE.</span></span>
            </h2>
          </div>
        </div>

        {/* Category tabs — UGC, Product, Talking Head */}
        <div className="adtype-tabs" role="tablist" aria-label="Ad format">
          {AD_TYPES.map((t) => (
            <button
              key={t.id}
              role="tab"
              aria-selected={active === t.id}
              className={`adtype-tab ${active === t.id ? "is-active" : ""}`}
              onClick={() => setActive(t.id)}
            >
              {t.label}
            </button>
          ))}
        </div>

        <div className="perf-grid" ref={railRef}>
          {filtered.map((c, i) => <PerfCard key={c.brand} c={c} idx={i} />)}
        </div>

        {/* Mobile-only page dots — mirrors which card is in view */}
        <div className="perf-dots" role="tablist" aria-label="Slides">
          {filtered.map((c, i) => (
            <button
              key={c.brand}
              role="tab"
              aria-selected={page === i}
              className={`perf-dot ${page === i ? "is-active" : ""}`}
              onClick={() => goTo(i)}
              aria-label={`Go to ${c.brand}`}
            ></button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Stats strip ---------- */
function Stats() {
  return (
    <section aria-label="Stats">
      <div className="strip">
        <div className="cell"><div className="lbl">Creatives / month</div><div className="num">120+</div><div className="sub">across formats</div></div>
        <div className="cell"><div className="lbl">Avg. ROAS lift</div><div className="num">3.8×</div><div className="sub">vs in-house control</div></div>
        <div className="cell"><div className="lbl">Turnaround</div><div className="num">48h</div><div className="sub">brief → first cuts</div></div>
        <div className="cell"><div className="lbl">Spend optimized</div><div className="num">$14M</div><div className="sub">2025–2026 trailing</div></div>
      </div>
    </section>
  );
}

/* ---------- Process ---------- */
const STEPS = [
  { n: "Step 01", t: "Brief",    d: "30-min call. Audience, offer, hooks, references. We translate it into a creative brief." },
  { n: "Step 02", t: "Concept",  d: "We send 8–12 storyboards in 48h. Angles, scripts, AI talent options. You pick the winners." },
  { n: "Step 03", t: "Render",   d: "Our AI stack produces final cuts in every aspect ratio. Iterations are free until you scroll-stop." },
  { n: "Step 04", t: "Scale",    d: "Ad-ready bundles weekly. You feed Meta, TikTok, YouTube — and watch CAC drop." },
];

function Process() {
  return (
    <section id="process" className="section">
      <div className="shell">
        <div className="section-head">
          <div>
            <div className="section-eyebrow"><span className="tick"></span>03 / How it works</div>
            <h2 className="section-title">Brief on Monday. <em>Ad-ready</em> by Friday.</h2>
          </div>
        </div>
        <div className="process-grid">
          {STEPS.map((s) => (
            <div className="step" key={s.n}>
              <div className="n">{s.n}</div>
              <div className="t">{s.t}</div>
              <div className="d">{s.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA ---------- */
function CTA() {
  return (
    <section id="contact" className="cta">
      <div className="shell">
        <div className="services-v2-pillwrap">
          <span className="services-v2-pill">Contact</span>
        </div>
        <div className="cta-card">
          <h2 className="cta-title title-reveal reveal">
            <span className="line-1"><span className="title-inner">Ready to scale your</span></span>
            <span className="line-2"><span className="title-inner">REVENUE?</span></span>
          </h2>
          <p className="cta-sub">
            If you want creatives that print revenue, TRY ROAS Marketing is your
            solution. Join the other 50+ DTC brands scaling with us.
          </p>
          <div className="cta-actions">
            <a href="#" className="cta-btn">
              Book a Call <span aria-hidden>↗</span>
            </a>
            <p className="cta-or">
              or email on{" "}
              <a href="mailto:hello@tryroasmarketing.com" className="cta-mail">
                hello@tryroasmarketing.com
              </a>
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="shell foot-shell">
        <div className="foot-left">
          <a href="#top" className="foot-brand">
            <img src="logo.png" alt="ROAS Marketing" className="foot-brand-img"/>
          </a>
          <h3 className="foot-headline">Still not sure?</h3>
          <p className="foot-copy">
            Message us before committing to a 30-minute discovery call.
            We'll show you 3 AI creatives built for your brand — before
            you spend a dollar.
          </p>
          <a href="mailto:romanleveling@gmail.com" className="foot-cta">Contact via Email</a>
        </div>

        <div className="foot-right">
          <div className="foot-col">
            <div className="foot-col-head">Links</div>
            <a href="#" aria-label="X / Twitter" className="foot-social">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.25 2.25H8.08l4.713 6.231 5.451-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117l11.966 15.644Z"/></svg>
            </a>
          </div>
          <div className="foot-col">
            <div className="foot-col-head">Information</div>
            <a href="#performance">Work</a>
            <a href="#services">Services</a>
            <a href="#contact">Testimonials</a>
            <a href="#contact">Team</a>
          </div>
        </div>
      </div>

      <div className="foot-legal shell">
        <span>© 2026 TRY ROAS Marketing. All rights reserved.</span>
        <span>Made with intent, not prompts.</span>
      </div>
    </footer>
  );
}

/* ---------- Scale callout (red check + pill badge + huge stat) ---------- */
function ScaleSection() {
  return (
    <section className="scale-section">
      <div className="shell scale-inner">
        {/* Hand-drawn red check arrow */}
        <svg className="scale-check" viewBox="0 0 120 90" aria-hidden>
          <defs>
            <filter id="scaleGlow" x="-30%" y="-30%" width="160%" height="160%">
              <feGaussianBlur stdDeviation="2" result="blur"/>
              <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
            </filter>
          </defs>
          <path
            d="M 12 18 Q 30 62 56 78 Q 58 80 60 78 Q 75 60 108 8"
            fill="none"
            stroke="#FF3B22"
            strokeWidth="9"
            strokeLinecap="round"
            strokeLinejoin="round"
            filter="url(#scaleGlow)"
          />
        </svg>
        <span className="scale-pill">Try ROAS Marketing</span>
        <h2 className="scale-headline title-reveal reveal">
          <span className="scale-prefix"><span className="title-inner">$14M+</span></span>
          <span className="scale-emph"><span className="title-inner">SPEND OPTIMIZED</span></span>
        </h2>
      </div>
    </section>
  );
}

window.ScaleSection = ScaleSection;
window.FeaturedClients = FeaturedClients;
window.Marquee = Marquee;
window.Services = Services;
window.Performance = Performance;
window.Stats = Stats;
window.Process = Process;
window.CTA = CTA;
window.Footer = Footer;

