/* Aelune — site sections (hi-fi finalized) */

const { useState: useSt, useEffect: useEf, useRef: useRf } = React;

// ============================
// HEADER
// ============================
function Header() {
  const [scrolled, setScrolled] = useSt(false);
  const [onDark, setOnDark] = useSt(false);

  useEf(() => {
    const onScroll = () => {
      const y = window.scrollY || 0;
      setScrolled(y > 12);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const NAV = [
    ["Home", "#home"],
    ["About", "#about"],
    ["How", "#how"],
    ["Agents", "#agents"],
    ["Features", "#features"],
    ["Roadmap", "#roadmap"],
    ["FAQ", "#faq"],
  ];

  return (
    <header className={"site-header" + (scrolled ? " scrolled" : "")}>
      <a href="#home" className="brand">
        <div className="mark" />
        <span>Aelune</span>
      </a>
      <nav>
        {NAV.map(([label, href]) => (
          <a key={href} href={href}>{label}</a>
        ))}
      </nav>
      <a href="https://x.com/AeluneAgent" target="_blank" rel="noopener noreferrer" className="header-x" aria-label="Aelune on X">
        <svg viewBox="0 0 22 22" width="18" height="18" fill="currentColor" aria-hidden="true">
          <path d="M13.093 9.3155L21.283 0H19.3422L12.2308 8.08852L6.55101 0H0L8.58902 12.2313L0 22H1.94088L9.45067 13.4583L15.449 22H22L13.0925 9.3155H13.093ZM10.4347 12.339L9.56445 11.1211L2.6402 1.42964H5.62127L11.2092 9.25094L12.0795 10.4689L19.3431 20.6354H16.3621L10.4347 12.3395V12.339Z" />
        </svg>
      </a>
      <a href="#cta" className="btn btn-primary btn-sm">
        Get early access <span className="arrow">→</span>
      </a>
    </header>
  );
}

// ============================
// HERO
// ============================
function Hero() {
  return (
    <section className="hero" id="home">
      <div className="stars">
        <Stars count={45} seed={3} color="#0d0d10" opacity={0.25} />
      </div>
      <div className="container hero-inner">
        <h1 className="reveal reveal-blur" style={{ "--reveal-delay": "100ms" }}>Aelune</h1>
        <div className="hero-sub reveal" style={{ "--reveal-delay": "260ms" }}>
          Hunt memecoin ideas in viral tweets.
        </div>
        <div className="hero-tagline reveal" style={{ "--reveal-delay": "380ms" }}>
          Create an agent. Give it a theme. Swipe through ideas the timeline is already telling you.
        </div>
        <div className="hero-ctas reveal" style={{ "--reveal-delay": "500ms" }}>
          <a href="#cta" className="btn btn-primary">
            Get early access <span className="arrow">→</span>
          </a>
          <a href="#about" className="btn btn-ghost">
            See how it works ↓
          </a>
        </div>
      </div>
    </section>
  );
}

// ============================
// ABOUT
// ============================
function About() {
  return (
    <section className="about section" id="about">
      <div className="container-narrow">
        <div className="section-heading" style={{ marginBottom: 56 }}>
          <div className="eyebrow reveal">02 &nbsp;/&nbsp; About</div>
        </div>
        <h2 className="reveal" style={{ textAlign: "center", "--reveal-delay": "80ms" }}>What is Aelune.</h2>
        <div className="about-copy" style={{ marginTop: 56 }}>
          <p className="reveal" style={{ "--reveal-delay": "0ms" }}>
            Every cycle, the next memecoin is hiding in plain sight — in a tweet that just hit a million views, in a phrase mutating across the timeline faster than humans can catch.
          </p>
          <p className="reveal" style={{ "--reveal-delay": "180ms" }}>
            Aelune watches Twitter for you. You set the theme. It reads the timeline in real time and turns each viral signal into a fully-formed memecoin concept — name, ticker, story, and the reason it would hit.
          </p>
        </div>
      </div>
    </section>
  );
}

// ============================
// HOW IT WORKS
// ============================
function How() {
  const STEPS = [
    ["01", "Create your agent", "Pick a name. Describe what your agent should watch for, in plain language."],
    ["02", "Set the theme", "Your agent translates your idea into a real-time search across the entire timeline."],
    ["03", "Swipe through ideas", "Each viral signal becomes a token concept. Skip what's flat. Save what hits."],
    ["04", "Launch the winner", "Take the full kit — name, ticker, lore — and ship it on pump.fun."],
  ];
  return (
    <section className="how section" id="how">
      <div className="container">
        <div className="section-heading">
          <div className="eyebrow reveal">03 &nbsp;/&nbsp; How it works</div>
          <h2 className="reveal" style={{ "--reveal-delay": "80ms" }}>How it works.</h2>
        </div>
        <div className="steps">
          {STEPS.map(([n, t, b], i) => (
            <div className="step reveal" key={n} style={{ "--reveal-delay": (i * 100) + "ms" }}>
              <div className="step-node">
                <div className="dot-outer"><div className="dot-inner" /></div>
              </div>
              <div className="step-content">
                <div className="eyebrow">Step {n}</div>
                <h3>{t}</h3>
                <p>{b}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================
// AGENTS
// ============================
function Agents() {
  const AGENTS = [
    { name: "Nocturne", theme: "Viral late-night X posts that turn into morning memes", Avatar: Avatar_Nocturne },
    { name: "Vesper", theme: "AI agent narrative, Solana ecosystem, and anything Murad reposts", Avatar: Avatar_Vesper },
    { name: "Halcyon", theme: "Political moments, Trump quotes, and White House clips going viral", Avatar: Avatar_Halcyon },
  ];
  return (
    <section className="agents-section" id="agents">
      <div className="container">
        <div className="section-heading">
          <div className="eyebrow reveal">04 &nbsp;/&nbsp; Agents</div>
          <h2 className="reveal" style={{ "--reveal-delay": "80ms" }}>Your agent. Your edge.</h2>
          <p className="reveal" style={{ "--reveal-delay": "160ms" }}>
            Every Aelune user creates their own agent. It learns what you like, remembers what you've passed on, and gets sharper the more you swipe.
          </p>
        </div>
        <div className="agents-grid">
          {AGENTS.map(({ name, theme, Avatar }, i) => (
            <div className="agent-card reveal" key={name} style={{ "--reveal-delay": (i * 120) + "ms" }}>
              <div className="agent-avatar">
                <Avatar size={62} />
              </div>
              <div className="agent-name">{name}</div>
              <div className="agent-theme">"{theme}"</div>
            </div>
          ))}
        </div>
        <div className="agents-foot reveal">One agent per account in beta · More slots coming soon</div>
      </div>
    </section>
  );
}

// ============================
// FEATURES
// ============================
function Features() {
  const FEATURES = [
    ["01", G_Scan,    "Real-time timeline scan", "Your agent reads viral tweets the moment they break."],
    ["02", G_Concept, "AI memecoin concepts",    "Every signal becomes a full token concept: name, ticker, lore, why it hits."],
    ["03", G_Swipe,   "Swipe interface",         "Decide fast. Keep what works. Skip what doesn't."],
    ["04", G_Learn,   "Learning agent",          "Every swipe teaches your agent your taste."],
    ["05", G_Source,  "Source-backed ideas",     "Every idea shows the tweet it came from. No hallucinations."],
    ["06", G_Launch,  "Launch-ready kits",       "Export the full asset pack and launch on pump.fun in minutes."],
  ];
  return (
    <section className="features-section" id="features">
      <div className="container">
        <div className="section-heading">
          <div className="eyebrow reveal">05 &nbsp;/&nbsp; Features</div>
          <h2 className="reveal" style={{ "--reveal-delay": "80ms" }}>What's inside.</h2>
        </div>
        <div className="features-grid">
          {FEATURES.map(([n, Glyph, t, b], i) => (
            <div className="feature reveal" key={n} style={{ "--reveal-delay": ((i % 3) * 100) + "ms" }}>
              <div className="feature-num">{n}</div>
              <div className="feature-glyph"><Glyph /></div>
              <h3>{t}</h3>
              <p>{b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================
// ROADMAP
// ============================
function Roadmap() {
  const MONTHS = [
    "May '26", "Jun '26", "Jul '26", "Aug '26", "Sep '26", "Oct '26",
    "Nov '26", "Dec '26", "Jan '27", "Feb '27", "Mar '27", "Apr '27",
  ];
  const TOTAL = MONTHS.length;
  // start/end are 0-indexed month positions (end is exclusive)
  const PHASES = [
    { phase: "01", t: "Beta launch",      b: "Agent creation, theme tuning, swipe interface, idea export.",                start: 0, end: 4 },
    { phase: "02", t: "Visual studio",    b: "In-platform image generator. Logos, banners, tweet visuals.",               start: 2, end: 6 },
    { phase: "03", t: "One-click launch", b: "Direct pump.fun integration. Launch from inside Aelune.",                   start: 4, end: 8 },
    { phase: "04", t: "Promo agent",      b: "A second agent running your token's first 48 hours on Twitter.",            start: 6, end: 10 },
    { phase: "05", t: "Multi-agent",      b: "Run multiple agents in parallel. Different themes, one dashboard.",        start: 8, end: 12 },
  ];

  const [now, setNow] = useSt(0); // months into the chart, driven by scroll + drag
  const [dragging, setDragging] = useSt(false);
  const bodyRef = useRf(null);
  const sectionRef = useRf(null);
  const draggingRef = useRf(false);
  useEf(() => { draggingRef.current = dragging; }, [dragging]);

  // Scroll-driven playhead: as the user scrolls through the pinned section,
  // the marker walks from Phase 1 → Phase 5.
  useEf(() => {
    const onScroll = () => {
      if (draggingRef.current) return;
      const sec = sectionRef.current;
      if (!sec) return;
      const r = sec.getBoundingClientRect();
      const vh = window.innerHeight;
      const extra = r.height - vh;
      if (extra <= 0) return;
      const scrolled = -r.top;
      const progress = Math.max(0, Math.min(1, scrolled / extra));
      setNow(progress * TOTAL);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  // Pick the "current" phase: among all bars containing `now`, prefer the latest-started one.
  // If none contain it, fall back to the nearest by midpoint.
  const currentIdx = (() => {
    const containing = PHASES
      .map((p, i) => ({ p, i }))
      .filter(({ p }) => now >= p.start && now <= p.end);
    if (containing.length) {
      containing.sort((a, b) => b.p.start - a.p.start);
      return containing[0].i;
    }
    let best = 0, bestDist = Infinity;
    PHASES.forEach((p, i) => {
      const mid = (p.start + p.end) / 2;
      const d = Math.abs(mid - now);
      if (d < bestDist) { bestDist = d; best = i; }
    });
    return best;
  })();

  const updateFromClientX = (clientX) => {
    const el = bodyRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
    setNow(ratio * TOTAL);
  };

  const onPointerDown = (e) => {
    e.preventDefault();
    setDragging(true);
    updateFromClientX(e.clientX);
    const onMove = (ev) => updateFromClientX(ev.clientX);
    const onUp = () => {
      setDragging(false);
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
    };
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", onUp);
  };

  return (
    <section className="roadmap-section section" id="roadmap" ref={sectionRef}>
      <div className="roadmap-stars">
        <Stars count={80} seed={9} color="#ffffff" opacity={0.55} />
      </div>
      <div className="roadmap-sticky">
      <div className="container">
        <div className="section-heading">
          <div className="eyebrow reveal">06 &nbsp;/&nbsp; Roadmap</div>
          <h2 className="reveal" style={{ "--reveal-delay": "80ms" }}>What's next.</h2>
          <p className="reveal" style={{ "--reveal-delay": "160ms" }}>
            Aelune unfolds in five phases. Each one expands what your agent can see, decide and do.
          </p>
        </div>

        <div className="gantt reveal" style={{ "--reveal-delay": "240ms", "--cols": TOTAL }}>
          <div className="gantt-head">
            {MONTHS.map((m, i) => (
              <div className="gantt-month" key={m} style={{ gridColumn: (i + 1) + " / span 1" }}>{m}</div>
            ))}
          </div>

          <div
            className={"gantt-body" + (dragging ? " is-dragging" : "")}
            ref={bodyRef}
            onPointerDown={onPointerDown}
          >
            {/* vertical gridlines */}
            <div className="gantt-grid-lines">
              {MONTHS.map((m, i) => (
                <div className="gantt-grid-line" key={i} style={{ left: (i / TOTAL) * 100 + "%" }} />
              ))}
              <div className="gantt-grid-line gantt-grid-line-end" style={{ left: "100%" }} />
            </div>

            {/* "We are here" playhead — draggable */}
            <div
              className={"gantt-now" + (dragging ? " is-dragging" : "")}
              style={{ left: (now / TOTAL) * 100 + "%" }}
            >
              <div className="gantt-now-tab">WE ARE HERE</div>
              <div className="gantt-now-line" />
              <div className="gantt-now-handle" aria-hidden="true" />
            </div>

            {/* rows */}
            <div className="gantt-rows">
              {PHASES.map((p, i) => {
                const left = (p.start / TOTAL) * 100;
                const width = ((p.end - p.start) / TOTAL) * 100;
                const isCurrent = i === currentIdx;
                return (
                  <div className="gantt-row reveal reveal-left" key={p.phase} style={{ "--reveal-delay": (300 + i * 90) + "ms" }}>
                    <div
                      className={"gantt-bar" + (isCurrent ? " current" : "")}
                      style={{ left: left + "%", width: width + "%" }}
                    >
                      <div className="gantt-bar-meta">Phase {p.phase}{isCurrent && " \u00b7 Now"}</div>
                      <div className="gantt-bar-title">{p.t}</div>
                      <div className="gantt-bar-body">{p.b}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      </div>
    </section>
  );
}

// ============================
// CTA STRIP
// ============================
function CTAStrip() {
  return (
    <section className="section-tight" id="cta" style={{ background: "var(--paper)", textAlign: "center" }}>
      <div className="container-narrow">
        <h2 className="serif reveal" style={{ fontSize: "clamp(48px, 6vw, 88px)", lineHeight: 0.95, margin: "0 0 20px", letterSpacing: "-0.02em" }}>
          Look up.
        </h2>
        <p className="reveal" style={{ fontSize: 16, color: "var(--ink-2)", margin: "0 auto 36px", maxWidth: 460, lineHeight: 1.6, "--reveal-delay": "100ms" }}>
          The signal is already on your timeline. We just point your agent at it.
        </p>
        <div className="reveal" style={{ "--reveal-delay": "200ms" }}>
          <a href="#" className="btn btn-primary">Get early access <span className="arrow">→</span></a>
        </div>
      </div>
    </section>
  );
}

// ============================
// FAQ
// ============================
function FAQ() {
  const QAS = [
    ["What exactly does Aelune do?", "It's a personal AI agent that watches Twitter for viral content matching the theme you set, then turns each signal into a memecoin concept you can review and launch."],
    ["Do I need to know how to code?", "No. You describe what you want in plain language. Your agent handles everything else."],
    ["Where do the ideas come from?", "Every idea is generated from a real, high-engagement tweet. You can always see the original source."],
    ["Can I launch tokens directly from Aelune?", "Direct launch is coming in Phase 3. For now, you export the full kit and launch on pump.fun manually."],
    ["Will my agent learn what I like?", "Yes. Every swipe — left or right — shapes how your agent thinks. The longer you use it, the sharper it gets."],
    ["Is this just for memecoins?", "Right now, yes. Memecoin ideation is what Aelune does best. Other use cases may follow."],
    ["When does beta open?", "Soon. Join the waitlist to be first in."],
    ["Is there a token?", "Details on the Aelune token will be shared with beta users first."],
  ];

  const [open, setOpen] = useSt(0);

  return (
    <section className="faq-section" id="faq">
      <div className="container">
        <div className="section-heading">
          <div className="eyebrow reveal">07 &nbsp;/&nbsp; FAQ</div>
          <h2 className="reveal" style={{ "--reveal-delay": "80ms" }}>Questions.</h2>
        </div>
        <div className="faq-list">
          {QAS.map(([q, a], i) => (
            <div key={i} className={"faq-item reveal reveal-up-sm" + (open === i ? " open" : "")} style={{ "--reveal-delay": (i * 60) + "ms" }}>
              <button className="faq-trigger" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span className="q">{q}</span>
                <span className="toggle" />
              </button>
              <div className="faq-answer">
                <div className="faq-answer-inner">{a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================
// FOOTER
// ============================
function SiteFooter() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-row" data-stagger="100">
          <a href="#home" className="brand reveal reveal-up-sm"><div className="mark" /><span>Aelune</span></a>
          <div className="socials reveal reveal-up-sm">
            <a href="https://x.com/AeluneAgent" target="_blank" rel="noopener noreferrer" aria-label="Aelune on X">
              <svg viewBox="0 0 22 22" width="14" height="14" fill="currentColor" aria-hidden="true">
                <path d="M13.093 9.3155L21.283 0H19.3422L12.2308 8.08852L6.55101 0H0L8.58902 12.2313L0 22H1.94088L9.45067 13.4583L15.449 22H22L13.0925 9.3155H13.093ZM10.4347 12.339L9.56445 11.1211L2.6402 1.42964H5.62127L11.2092 9.25094L12.0795 10.4689L19.3431 20.6354H16.3621L10.4347 12.3395V12.339Z" />
              </svg>
              <span>@AeluneAgent</span>
            </a>
          </div>
        </div>
        <div className="footer-fine reveal reveal-fade" style={{ "--reveal-delay": "360ms" }}>© Aelune 2026</div>
      </div>
    </footer>
  );
}

Object.assign(window, { Header, Hero, About, How, Agents, Features, Roadmap, CTAStrip, FAQ, SiteFooter });
