/* All page sections. */

const { motion, AnimatePresence, useScroll, useTransform } = window.FM;
const L = window.Lucide;
const { gsap, ScrollTrigger } = window;

/* ────────────────────────────────────────────────────────────────
   NAV
   ──────────────────────────────────────────────────────────────── */
const Nav = () => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <header
      className={
        'fixed top-0 inset-x-0 z-50 transition-all duration-300 ease-out ' +
        (scrolled ? 'py-2.5' : 'py-4')
      }
    >
      <div className="mx-auto max-w-[1180px] px-4 sm:px-6">
        <nav
          className={
            'relative flex items-center justify-between rounded-full transition-all duration-300 ' +
            (scrolled
              ? 'glass-strong px-3 pr-3 py-1.5 shadow-[0_8px_28px_-12px_rgba(0,0,0,0.55)]'
              : 'px-3 pr-3 py-2')
          }
        >
          <a href="#top" className="inline-flex items-center gap-2 pl-2.5">
            <img
              src="assets/enwrite-logo-256.png"
              alt="Enwrite"
              width="20"
              height="20"
              className="inline-block size-5 rounded-md"
            />
            <span className="font-semibold text-[15px] tracking-tight gradient-text">Enwrite</span>
          </a>
          <ul className="hidden md:flex items-center gap-1 text-[13px] text-white/70">
            {[
              ['Product', '#product'],
              ['Pricing', '#pricing'],
              ['Privacy', 'https://enwrite.spectatr.ai/privacy'],
              ['Enterprise', '#enterprise'],
            ].map(([label, href]) => (
              <li key={label}>
                <a className="px-3 py-1.5 rounded-full hover:text-white hover:bg-white/5 transition" href={href}>{label}</a>
              </li>
            ))}
          </ul>
          <div className="flex items-center gap-1.5">
            <a
              href="https://play.google.com/store/apps/details?id=com.enwrite.keyboard"
              className="hidden sm:inline-flex items-center rounded-full px-3.5 py-1.5 text-[13px] text-white/70 hover:text-white"
            >
              Download
            </a>
            <GradPill href="#beta" size="md" className="text-[13px] px-4 py-2">Get Enwrite</GradPill>
          </div>
        </nav>
      </div>
    </header>
  );
};

/* ────────────────────────────────────────────────────────────────
   HERO
   ──────────────────────────────────────────────────────────────── */
const Hero = ({ reduced }) => {
  return (
    <section id="top" className="relative pt-32 sm:pt-36 pb-20 sm:pb-28 overflow-hidden">
      <div aria-hidden className="absolute inset-0 -z-10">
        <ParticleField reduced={reduced} />
        <div className="absolute inset-0 grid-lines opacity-60" />
        <div className="absolute inset-x-0 bottom-0 h-40 bg-gradient-to-b from-transparent to-ink-950" />
      </div>

      <div className="mx-auto max-w-[1180px] px-5 sm:px-8 text-center">
        <InView delay={0.05}>
          <Eyebrow>
            <span>Now in private beta · iOS · Android · Mac · Win · Chrome</span>
          </Eyebrow>
        </InView>

        <h1 className="mt-6 text-[40px] sm:text-[64px] lg:text-[78px] leading-[1.02] font-semibold tracking-[-0.025em] text-white text-balance">
          <WordReveal
            text="Your English is perfect."
            delay={0.05}
            shimmerWords={['perfect.']}
          />
          <br />
          <span className="text-white/55">
            <WordReveal
              text="Your tools just don't know it yet."
              delay={0.45}
            />
          </span>
        </h1>

        <motion.p
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.95 }}
          className="mx-auto mt-6 max-w-[640px] text-[16px] sm:text-[18px] leading-[1.55] text-white/65 text-balance"
        >
          One tap polishes messy English or <span className="text-white/85">Hinglish</span> into native-sounding writing.
          Inside any app. In 2 seconds.
        </motion.p>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 1.1 }}
          className="mt-8 flex flex-col sm:flex-row items-center justify-center gap-3"
        >
          <GradPill
            href="#beta"
            size="lg"
            onClick={(e) => {
              // Confetti burst on tap. We still let the anchor navigate
              // to the beta section after — don't preventDefault.
              window.confetti && window.confetti({
                particleCount: 90,
                spread: 70,
                origin: { y: 0.35 },
                colors: ['#38BDF8', '#D946EF', '#8B5CF6', '#ffffff'],
              });
            }}
            icon={<L.ArrowRight size={16} strokeWidth={2.25} />}
          >
            Get Enwrite — free
          </GradPill>
          <GhostPill href="#demo" size="lg" icon={<L.Play size={14} strokeWidth={2.25} />}>
            Watch the demo
          </GhostPill>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 1.25 }}
          className="mt-7 flex flex-wrap items-center justify-center gap-1.5"
        >
          {/* Real destinations where they exist. iOS is private TestFlight
              (request an invite via email). Android is live on Play Store.
              Mac / Windows / Chrome are planned — all funnel into beta
              email for now. */}
          <PlatformPill
            icon={L.Apple}
            label="iOS"
            sub="TestFlight"
            href="mailto:contact@spectatr.ai?subject=Enwrite%20iOS%20TestFlight%20invite"
          />
          <PlatformPill
            icon={L.Smartphone}
            label="Android"
            sub="Play Store"
            href="https://play.google.com/store/apps/details?id=com.enwrite.keyboard"
          />
          <PlatformPill
            icon={L.Monitor}
            label="Mac"
            sub="planned"
            href="mailto:contact@spectatr.ai?subject=Enwrite%20Mac%20beta"
          />
          <PlatformPill
            icon={L.MonitorDot}
            label="Windows"
            sub="planned"
            href="mailto:contact@spectatr.ai?subject=Enwrite%20Windows%20beta"
          />
          <PlatformPill
            icon={L.Chrome}
            label="Chrome"
            sub="planned"
            href="mailto:contact@spectatr.ai?subject=Enwrite%20Chrome%20beta"
          />
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 24 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 1.5 }}
          className="mt-14 sm:mt-20"
          id="demo"
        >
          <HeroDemo />
        </motion.div>

        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 1.9 }}
          className="mt-10 flex items-center justify-center gap-6 text-[12px] text-white/35"
        >
          <span className="inline-flex items-center gap-1.5"><L.Zap size={11} /> ~1.9s rewrites</span>
          <span className="hidden sm:inline-flex items-center gap-1.5"><L.ShieldCheck size={11} /> No text logged</span>
          <span className="inline-flex items-center gap-1.5"><L.IndianRupee size={11} /> ₹0.10/rewrite</span>
        </motion.div>
      </div>
    </section>
  );
};

/* ────────────────────────────────────────────────────────────────
   HINGLISH PROBLEM (scroll-pinned)
   ──────────────────────────────────────────────────────────────── */
const HINGLISH_RAW = 'Bhai, ye meeting ka समय change kar sakte ho?';
const HINGLISH_OUT = 'Hey — could we possibly move the meeting time? Let me know what works.';

const HinglishProblem = ({ reduced }) => {
  const wrap = React.useRef(null);
  const stick = React.useRef(null);
  const [progress, setProgress] = React.useState(0); // 0..1

  React.useEffect(() => {
    if (reduced) { setProgress(1); return; }
    const el = wrap.current;
    if (!el) return;
    const ctx = gsap.context(() => {
      const obj = { p: 0 };
      gsap.to(obj, {
        p: 1,
        ease: 'none',
        scrollTrigger: {
          trigger: el,
          start: 'top top',
          end: '+=1400',
          scrub: 0.6,
          pin: stick.current,
          pinSpacing: true,
          onUpdate: (st) => setProgress(st.progress),
        },
      });
    }, el);
    return () => ctx.revert();
  }, [reduced]);

  // Word-by-word reveal driven by scroll progress
  const rawWords = HINGLISH_RAW.split(' ');
  const outWords = HINGLISH_OUT.split(' ');
  const rawVisible = Math.floor(progress * 2.0 * rawWords.length);
  const outStart = 0.45;
  const outVisible = Math.max(0, Math.floor(((progress - outStart) / (1 - outStart)) * outWords.length * 1.05));

  return (
    <section ref={wrap} className="relative" id="problem">
      <div ref={stick} className="h-screen flex items-center justify-center px-5 sm:px-8 relative overflow-hidden">
        <div aria-hidden className="absolute inset-0 -z-10">
          <div className="absolute left-[-10%] top-[20%] size-[420px] rounded-full bg-violet-brand/15 blur-[100px]" />
          <div className="absolute right-[-10%] bottom-[10%] size-[420px] rounded-full bg-fuchsia-brand/15 blur-[100px]" />
          <div className="absolute inset-0 grid-lines opacity-40" />
        </div>

        <div className="mx-auto max-w-[1180px] w-full">
          <div className="text-center">
            <Eyebrow>The Hinglish problem</Eyebrow>
            <h2 className="mt-5 text-[34px] sm:text-[54px] font-semibold tracking-[-0.02em] leading-[1.05] text-balance">
              The 30 seconds you waste rewriting
              <br />
              in ChatGPT? <span className="gradient-text">Gone.</span>
            </h2>
          </div>

          <div className="mt-10 sm:mt-14 grid lg:grid-cols-2 gap-6 lg:gap-10 items-stretch">
            {/* Voice / Hinglish */}
            <div className="glass-strong rounded-3xl p-6 sm:p-8 relative overflow-hidden">
              <div className="flex items-center justify-between mb-4">
                <div className="inline-flex items-center gap-2 text-[12px] text-white/55">
                  <span className="size-2 rounded-full bg-rose-400 animate-pulse"></span>
                  Voice note · 0:07
                </div>
                <div className="text-[11px] text-white/40 font-mono">EN · HI · MIX</div>
              </div>

              <Waveform progress={progress} />

              <div className="mt-6 min-h-[100px]">
                <div className="text-[10.5px] uppercase tracking-[0.22em] text-white/40 mb-2">Heard</div>
                <p className="text-[20px] sm:text-[26px] leading-[1.3] tracking-tight">
                  {rawWords.slice(0, rawVisible).map((w, i) => (
                    <span
                      key={i}
                      className={
                        'inline-block mr-[0.3em] ' +
                        (/[\u0900-\u097F]/.test(w) ? 'font-deva text-white' : 'text-white/90')
                      }
                    >
                      {w}
                    </span>
                  ))}
                  {rawVisible < rawWords.length && <span className="caret text-white/0">.</span>}
                </p>
              </div>
            </div>

            {/* Polished */}
            <div className="glass-strong rounded-3xl p-6 sm:p-8 relative overflow-hidden grad-border">
              <div className="flex items-center justify-between mb-4">
                <div className="inline-flex items-center gap-2 text-[12px] text-white/55">
                  <L.Sparkles size={12} className="text-fuchsia-300" />
                  Drafted by Enwrite
                </div>
                <div className="text-[11px] text-white/40 font-mono">PROFESSIONAL</div>
              </div>

              <div className="rounded-2xl border border-white/10 p-5 bg-white/[0.02]">
                <div className="text-[10.5px] uppercase tracking-[0.22em] text-emerald-300/80 mb-2">Reply</div>
                <p className="text-[20px] sm:text-[26px] leading-[1.3] tracking-tight">
                  {outWords.slice(0, outVisible).map((w, i) => (
                    <span key={i} className="inline-block mr-[0.3em] text-white/95">{w}</span>
                  ))}
                  {outVisible < outWords.length && progress > outStart && <span className="caret text-white/0">.</span>}
                </p>
              </div>

              <div className="mt-4 flex items-center gap-4 text-[11px] text-white/40">
                <span className="inline-flex items-center gap-1.5"><L.Languages size={12} /> Idiom preserved</span>
                <span className="inline-flex items-center gap-1.5"><L.IndianRupee size={12} /> Lakh → Million ready</span>
              </div>
            </div>
          </div>

          {/* Stat bar */}
          <div className="mt-8 sm:mt-10 grid grid-cols-3 rounded-2xl glass overflow-hidden text-center">
            <Stat value="2.1s" label="avg rewrite" />
            <Stat value="15 / day" label="free rewrites" border />
            <Stat value="40+" label="apps supported" />
          </div>
        </div>
      </div>
    </section>
  );
};

const Stat = ({ value, label, border }) => (
  <div className={'py-5 sm:py-6 ' + (border ? 'border-x border-white/8' : '')}>
    <div className="text-[24px] sm:text-[32px] font-semibold tracking-tight text-white">{value}</div>
    <div className="mt-1 text-[11px] uppercase tracking-[0.22em] text-white/45">{label}</div>
  </div>
);

const Waveform = ({ progress }) => {
  // 48 bars driven by sine + index, "playing" through progress
  const bars = 48;
  const head = Math.floor(progress * 2 * bars);
  return (
    <div className="flex items-end gap-[3px] h-[64px]">
      {Array.from({ length: bars }).map((_, i) => {
        const seed = Math.sin(i * 0.7) * Math.cos(i * 0.31);
        const h = 12 + Math.abs(seed) * 46 + (i % 4) * 2;
        const active = i < head;
        return (
          <span
            key={i}
            className="block w-[3px] rounded-full transition-colors duration-200"
            style={{
              height: h,
              background: active
                ? 'linear-gradient(180deg, #38BDF8, #D946EF)'
                : 'rgba(255,255,255,0.10)',
              opacity: active ? 1 : 0.5,
            }}
          />
        );
      })}
    </div>
  );
};

/* ────────────────────────────────────────────────────────────────
   FEATURE GRID
   ──────────────────────────────────────────────────────────────── */
const FEATURES = [
  { icon: L.Languages, title: 'Hinglish hi-fidelity', body: 'Trained on Indian English. Knows your idioms, your “revert,” your “do the needful.”' },
  { icon: L.SlidersHorizontal, title: 'Tone, in one tap', body: 'Professional, casual, concise. From the keyboard. Never settings.' },
  { icon: L.IndianRupee, title: 'Lakh ↔ Million', body: 'Auto-convert numbers and ₹ formatting for any audience.' },
  { icon: L.ShieldCheck, title: 'Privacy-first', body: "Your text isn't logged after the rewrite returns. Period." },
  { icon: L.Undo2, title: '5-second undo', body: 'Rewrite, regret, undo. From the same toolbar.' },
  { icon: L.RefreshCw, title: 'One account, every device', body: 'Top up on laptop, rewrite on phone. Credits sync via Google.' },
];

const FeatureCard = ({ icon: Icon, title, body, delay }) => (
  <InView delay={delay} y={28} className="h-full">
    <div className="group relative h-full glass rounded-2xl p-6 transition-all duration-300 hover:-translate-y-0.5 hover:bg-white/[0.05]">
      <div className="absolute inset-0 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-300"
           style={{
             background: 'radial-gradient(120px 80px at var(--mx,50%) var(--my,30%), rgba(217,70,239,0.10), transparent 70%)',
             pointerEvents: 'none',
           }}
      />
      <div className="relative">
        <div className="relative inline-flex items-center justify-center size-10 rounded-xl grad-border bg-white/[0.03] transition-transform duration-300 group-hover:-translate-y-0.5">
          <Icon size={18} strokeWidth={1.75} className="text-white/85" />
        </div>
        <h3 className="mt-5 text-[17px] font-semibold tracking-tight text-white">{title}</h3>
        <p className="mt-2 text-[14px] leading-[1.55] text-white/55 text-balance">{body}</p>
      </div>
      <div className="absolute right-5 top-5 size-1.5 rounded-full bg-white/10 group-hover:bg-fuchsia-brand/80 transition-colors duration-300" />
    </div>
  </InView>
);

const FeatureGrid = () => (
  <section id="product" className="relative py-24 sm:py-32 px-5 sm:px-8">
    <div className="mx-auto max-w-[1180px]">
      <div className="max-w-[680px]">
        <Eyebrow>Why people stay</Eyebrow>
        <h2 className="mt-5 text-[34px] sm:text-[48px] font-semibold tracking-[-0.02em] leading-[1.05] text-balance">
          Built for the way <span className="font-deva">भारत</span> actually writes.
        </h2>
        <p className="mt-4 text-[16px] text-white/55 max-w-[520px]">
          Not another wrapper around a generic model. Every feature is specifically tuned for how Indian professionals
          actually communicate at work.
        </p>
      </div>

      <div className="mt-12 sm:mt-16 grid sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-5">
        {FEATURES.map((f, i) => (
          <FeatureCard key={f.title} {...f} delay={i * 0.04} />
        ))}
      </div>
    </div>
  </section>
);

Object.assign(window, { Nav, Hero, HinglishProblem, FeatureGrid });
