// ── API helper ──────────────────────────────────────────────────
const API = `${window.location.origin}/api`;

async function apiFetch(path, options = {}) {
  const res = await fetch(`${API}${path}`, {
    ...options,
    headers: { "Content-Type": "application/json", ...options.headers },
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || "Request failed");
  return data;
}

// ── Contact / Invest Modal ───────────────────────────────────────
const Modal = ({ type, onClose }) => {
  const isInvestor = type === "invest";
  const [form, setForm] = React.useState({ name: "", email: "", company: "", subject: "", message: "" });
  const [status, setStatus] = React.useState("idle");
  const [errMsg, setErrMsg] = React.useState("");

  // Lock background scroll (Lenis) while the modal is open; close on Escape.
  React.useEffect(() => {
    if (window.lenis) window.lenis.stop();
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
      if (window.lenis) window.lenis.start();
    };
  }, [onClose]);

  const set = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    setStatus("loading");
    try {
      if (isInvestor) {
        await apiFetch("/invest/lead", { method: "POST", body: JSON.stringify({ name: form.name, email: form.email, company: form.company, message: form.message }) });
      } else {
        await apiFetch("/contact", { method: "POST", body: JSON.stringify({ ...form, type: "collaborate" }) });
      }
      setStatus("success");
    } catch (err) {
      setErrMsg(err.message);
      setStatus("error");
    }
  };

  const overlayStyle = {
    position: "fixed", inset: 0, background: "rgba(14,26,18,0.7)", zIndex: 100,
    display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
    backdropFilter: "blur(4px)",
  };
  const boxStyle = {
    background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 8,
    padding: "40px 36px", width: "100%", maxWidth: 520, position: "relative",
    maxHeight: "90vh", overflowY: "auto",
  };
  const inputStyle = {
    width: "100%", padding: "10px 12px", border: "1px solid var(--line)",
    borderRadius: 4, fontFamily: "var(--sans)", fontSize: 14,
    background: "var(--bg)", color: "var(--ink)", boxSizing: "border-box",
    marginTop: 6, display: "block",
  };
  const labelStyle = {
    fontSize: 11, fontFamily: "var(--mono)", letterSpacing: "0.12em",
    textTransform: "uppercase", color: "var(--ink-mute)", display: "block", marginTop: 16,
  };

  return (
    <div style={overlayStyle} onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div style={boxStyle} data-lenis-prevent>
        <button onClick={onClose} style={{ position: "absolute", top: 16, right: 16, background: "none", border: "none", fontSize: 20, cursor: "pointer", color: "var(--ink-mute)" }}>✕</button>
        {status === "success" ? (
          <div style={{ textAlign: "center", padding: "24px 0" }}>
            <div style={{ fontSize: 40, marginBottom: 16 }}>🌿</div>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 28, marginBottom: 12 }}>Thank you!</h3>
            <p style={{ color: "var(--ink-mute)", fontSize: 15 }}>
              {isInvestor ? "We've received your interest and will be in touch soon." : "We've received your message and will be in touch shortly."}
            </p>
            <button onClick={onClose} style={{ marginTop: 24, padding: "10px 24px", background: "var(--ink)", color: "var(--bg)", border: "none", borderRadius: 999, cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600 }}>Close</button>
          </div>
        ) : (
          <>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 28, marginBottom: 6, fontWeight: 400 }}>
              {isInvestor ? "Investor Enquiry" : "Collaborate with us"}
            </h3>
            <p style={{ color: "var(--ink-mute)", fontSize: 14, marginBottom: 8 }}>
              {isInvestor ? "Tell us about yourself and we'll be in touch." : "Tell us about your idea and we'll get back to you."}
            </p>
            {status === "error" && (
              <div style={{ padding: "10px 14px", background: "#fdecea", color: "#b71c1c", borderRadius: 4, fontSize: 13, marginBottom: 12 }}>{errMsg}</div>
            )}
            <form onSubmit={submit}>
              <label style={labelStyle}>Full Name *</label>
              <input style={inputStyle} value={form.name} onChange={set("name")} required placeholder="Your name" />
              <label style={labelStyle}>Email *</label>
              <input style={inputStyle} type="email" value={form.email} onChange={set("email")} required placeholder="your@email.com" />
              {isInvestor && (
                <>
                  <label style={labelStyle}>Company / Fund</label>
                  <input style={inputStyle} value={form.company} onChange={set("company")} placeholder="Your firm name" />
                </>
              )}
              {!isInvestor && (
                <>
                  <label style={labelStyle}>Subject</label>
                  <input style={inputStyle} value={form.subject} onChange={set("subject")} placeholder="What's this about?" />
                </>
              )}
              <label style={labelStyle}>Message *</label>
              <textarea
                style={{ ...inputStyle, resize: "vertical", minHeight: 120 }}
                value={form.message} onChange={set("message")} required
                placeholder={isInvestor ? "Tell us about your investment focus…" : "Tell us about your idea or how you'd like to collaborate…"}
              />
              <button type="submit" disabled={status === "loading"} style={{ marginTop: 24, padding: "12px 28px", background: "var(--ink)", color: "var(--bg)", border: "none", borderRadius: 999, cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600, width: "100%" }}>
                {status === "loading" ? "Sending…" : isInvestor ? "Send Enquiry" : "Send Message"}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

/* Section components for Herb Immortal homepage */

const Tag = ({ children }) => (
  <span className="tag">{children}</span>
);

const SectionHead = ({ tag, num, children }) => null;

const Arrow = () => <span className="arr" aria-hidden="true"></span>;

// ----------------------------- Nav -----------------------------
const Nav = () => {
  const [isScrolled, setIsScrolled] = React.useState(false);
  const [isHidden, setIsHidden] = React.useState(false);
  const lastScrollY = React.useRef(0);
  const frame = React.useRef(0);
  const [navModal, setNavModal] = React.useState(null);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    // The ecosystem scene is a pinned, full-bleed stage; the bar floating over it
    // fights the imagery, so it stays hidden there in both scroll directions.
    //
    // Its position is measured on resize and cached, never read during a scroll.
    // Reading it per event meant a getBoundingClientRect() — a forced synchronous
    // layout — on every frame Lenis emitted, interleaved with ScrollScene writing
    // transforms in the same frame. That read/write thrash was the scroll jank.
    // The scene's own height is set from JS, so a ResizeObserver keeps the cache
    // honest without ever measuring mid-scroll.
    const scene = document.getElementById("solutions");
    let sceneTop = 0;
    let sceneBottom = 0;

    const measure = () => {
      if (!scene) return;
      const r = scene.getBoundingClientRect();
      sceneTop = r.top + window.scrollY;
      sceneBottom = sceneTop + r.height;
    };
    measure();

    const ro = scene && "ResizeObserver" in window ? new ResizeObserver(measure) : null;
    if (ro) ro.observe(scene);

    const update = () => {
      frame.current = 0;
      const currentScrollY = window.scrollY;
      setIsScrolled(currentScrollY > 24);

      // Same test as before, from the cached box instead of a live measurement.
      const overEcosystem =
        !!scene &&
        sceneTop - currentScrollY <= 8 &&
        sceneBottom - currentScrollY >= window.innerHeight * 0.5;

      // Hide on scroll down, show on scroll up — except over the ecosystem scene.
      if (menuOpen) {
        setIsHidden(false);
      } else if (overEcosystem) {
        setIsHidden(true);
      } else {
        // Smooth scrolling emits sub-pixel deltas, so an exact `>` comparison
        // flip-flops on the tail of a flick and makes the bar flicker on the way
        // back up. A few pixels of deadband keeps the direction unambiguous.
        const delta = currentScrollY - lastScrollY.current;
        if (Math.abs(delta) > 4) {
          setIsHidden(currentScrollY > 150 && delta > 0);
          lastScrollY.current = currentScrollY;
        }
        return;
      }
      lastScrollY.current = currentScrollY;
    };

    // One update per frame at most, on the frame the browser is about to paint.
    const handleScroll = () => {
      if (!frame.current) frame.current = requestAnimationFrame(update);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("resize", measure);
    return () => {
      if (frame.current) cancelAnimationFrame(frame.current);
      frame.current = 0;
      if (ro) ro.disconnect();
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", measure);
    };
  }, [menuOpen]);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    if (window.lenis) { menuOpen ? window.lenis.stop() : window.lenis.start(); }
    return () => { document.body.style.overflow = ""; if (window.lenis) window.lenis.start(); };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  const NavTag = window.motion ? window.motion.nav : 'nav';

  return (
    <>
      {navModal && <Modal type={navModal} onClose={() => setNavModal(null)} />}
      <NavTag
        className={`nav ${isScrolled ? "scrolled" : ""}`}
        initial={{ y: 0, opacity: 1 }}
        animate={{
          y: isHidden && !menuOpen ? "-100%" : "0%",
          opacity: isHidden && !menuOpen ? 0 : 1
        }}
        transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
      >
        <div className="wrap nav-inner">
          <a href="/" className="brand" aria-label="Herb Immortal home" onClick={(e) => { closeMenu(); window.__nav(e, 'top'); }}>
            <img className="mark" src={window.__resources?.logoMark || "assets/logo-mark.png"} alt="" />
            <span className="wordmark">Herb Immortal</span>
          </a>
          <div className="nav-links">
            <a href="#vision" onClick={(e) => window.__nav(e, 'vision')}>Vision</a>
            <a href="#solutions" onClick={(e) => window.__nav(e, 'solutions')}>Solutions</a>
            <a href="#platforms" onClick={(e) => window.__nav(e, 'platforms')}>Platforms</a>
            <a href="#founders" onClick={(e) => window.__nav(e, 'founders')}>Founders</a>
            <a href="#invest" onClick={(e) => window.__nav(e, 'invest')}>Investors</a>
          </div>
          <div className="nav-cta desktop-only">
            <a href="#invest" className="btn" onClick={(e) => window.__nav(e, 'invest')}>We're raising <Arrow /></a>
          </div>
          <button
            className="mobile-menu-btn"
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label="Toggle menu"
          >
            <span className={`hamburger ${menuOpen ? "open" : ""}`}>
              <span></span>
              <span></span>
            </span>
          </button>
        </div>
      </NavTag>

      {/* Mobile menu overlay */}
      <div className={`mobile-menu-overlay ${menuOpen ? "open" : ""}`}>
        <div className="mobile-menu-content">
          <a href="#vision" className="mobile-menu-link h3" onClick={(e) => { closeMenu(); window.__nav(e, 'vision'); }}>Vision</a>
          <a href="#solutions" className="mobile-menu-link h3" onClick={(e) => { closeMenu(); window.__nav(e, 'solutions'); }}>Solutions</a>
          <a href="#platforms" className="mobile-menu-link h3" onClick={(e) => { closeMenu(); window.__nav(e, 'platforms'); }}>Platforms</a>
          <a href="#founders" className="mobile-menu-link h3" onClick={(e) => { closeMenu(); window.__nav(e, 'founders'); }}>Founders</a>
          <a href="#invest" className="mobile-menu-link h3" onClick={(e) => { closeMenu(); window.__nav(e, 'invest'); }}>Investors</a>
        </div>
        <div className="mobile-menu-actions">
          <a href="https://myherbalshop.ai/" className="btn" style={{ width: "100%", justifyContent: "center", marginBottom: "12px" }}>Sign in to Myherbalshop</a>
          <a href="https://herbimmortal.org/" className="btn ghost" style={{ width: "100%", justifyContent: "center" }}>Sign in to herbimmortal.org</a>
        </div>
      </div>
    </>
  );
};

// ----------------------------- Hero -----------------------------
const Hero = () => {
  return (
    <section className="hero" id="top">
      <DNAHelix
        className="hero-dna-helix"
        primaryColor="#3DAF5F"
        secondaryColor="#1F7A3D"
        speed={0.4}
        scale={1.0}
        opacity={0.5}
        glow={0.5}
        mouseInteractive={true}
      />
      <div className="wrap hero-center">
        <Reveal delay={0.12}>
          <span className="tag">Est. 2022 · Toronto · India · Global</span>
        </Reveal>
        <Reveal delay={0.24}>
          <h1 className="display">
            The Operating&nbsp;System<br />
            for <em>Traditional Wellness.</em>
          </h1>
        </Reveal>
        <Reveal delay={0.36}>
          <p className="hero-slogan">
            The world's first unified platform for traditional wellness. We connect healers,
            knowledge, and communities across every tradition, language, and border.
          </p>
        </Reveal>
        <Reveal delay={0.48}>
          <div className="btn-row">
            <a href="#vision" className="btn" onClick={(e) => window.__nav(e, 'vision')}>Explore our vision <Arrow /></a>
            <a href="#invest" className="btn ghost" onClick={(e) => window.__nav(e, 'invest')}>We're raising <Arrow /></a>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

const Globe = () => (
  <div className="globe-wrap">
    <AnimatedGlobe />
  </div>
);

// --------------------------- Marquee ----------------------------
const Marquee = () => {
  const traditions = [
    "Chinese Medicine", "Unani", "Siddha", "Indigenous Healing",
    "Herbal Medicine", "Naturopathy", "Ayurveda", "Kampo"
  ];

  const Item = ({ children }) => (
    <span className="premium-marquee-item">
      {children}
      <span className="premium-marquee-dash"></span>
    </span>
  );

  return (
    <div className="premium-marquee">
      <div className="premium-marquee-track">
        {[...traditions, ...traditions, ...traditions].map((t, i) => <Item key={i}>{t}</Item>)}
      </div>
    </div>
  );
};

// ---------------------- Industry Gap ---------------------------


const IndustryGap = () => {
  const gaps = [
    {
      n: "I",
      t: "Discovery Gap",
      b: "With no universal way to find trusted practitioners and products globally, every search starts from zero.",
      m: "DISCOVERY GAP • GLOBAL DISCOVERY • PRACTITIONERS • VERIFIED PRODUCTS • ",
      img: [
        "https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?q=80&w=400&auto=format&fit=crop",
        "https://images.unsplash.com/photo-1512466699195-2d936166e5db?q=80&w=400&auto=format&fit=crop"
      ]
    },
    {
      n: "II",
      t: "Trust Gap",
      b: "No consistent cross-region verification or quality standards. Trust is a question, not a feature.",
      m: "TRUST GAP • VERIFICATION • CERTIFICATIONS • AUTHENTICITY • QUALITY STANDARDS • ",
      img: [
        "https://images.unsplash.com/photo-1579541592065-27a3c3e214d0?q=80&w=400&auto=format&fit=crop",
        "https://images.unsplash.com/photo-1601758003122-53c40e686a19?q=80&w=400&auto=format&fit=crop"
      ]
    },
    {
      n: "III",
      t: "Access Gap",
      b: "Knowledge remains locked in silos of books, lineages, and languages, rather than serving as a usable, queryable infrastructure.",
      m: "ACCESS GAP • KNOWLEDGE • ANCIENT TEXTS • LANGUAGES • LIBRARIES • PRESERVATION • ",
      img: [
        "https://images.unsplash.com/photo-1532012197267-da84d127e765?q=80&w=400&auto=format&fit=crop",
        "https://images.unsplash.com/photo-1507842217343-583bb7270b66?q=80&w=400&auto=format&fit=crop"
      ]
    },
  ];

  return (
    <section id="gap">
      <div className="wrap">
        <SectionHead tag="The Industry Gap" num="01 / 06" />
        <div className="split">
          <h2 className="h2">The industry exists.<br />The infrastructure does not.</h2>
          <div>
            <p className="body-lg">
              Systems like Ayurveda, TCM, Unani, and Siddha represent the lived reality of billions.
              Despite this immense scale, the industry still operates without a shared digital infrastructure.
            </p>
            <p className="body-lg" style={{ marginTop: 20, color: "var(--ink-mute)" }}>
              Knowledge is fragmented. Trust standards are uneven. Access still depends on
              geography and language. <span style={{ color: "var(--ink)" }}>Herb Immortal is building the missing layer.</span>
            </p>
          </div>
        </div>
      </div>

      <div style={{ height: '600px', position: 'relative' }}>
        <FlowingMenu
          items={gaps.map(g => ({
            link: '#',
            text: `${g.n}. ${g.t}`,
            marqueeText: g.b
          }))}
          bgColor="transparent"
          textColor="var(--ink)"
          marqueeBgColor="var(--ink)"
          marqueeTextColor="var(--paper)"
          borderColor="var(--line)"
        />
      </div>
    </section>
  );
};

// ----------------------------- Stats ----------------------------
const Stats = () => (
  <section className="stats">
    <div className="wrap">
      <SectionHead tag="The Moment" num="02 / 06" />
      <div className="split" style={{ alignItems: "end" }}>
        <h2 className="h2">A $6.8T industry.<br />Zero shared infrastructure.</h2>
        <p className="body-lg" style={{ color: "color-mix(in oklab, currentColor 78%, transparent)" }}>
          Global demand. Cultural momentum. AI readiness. All three are converging.
          The missing piece has always been trusted, unified infrastructure.
        </p>
      </div>
      <div className="stats-row">
        <Reveal delay={0.08} className="stat premium-card">
          <span className="label">Market</span>
          <div className="figure"><StatCount to={6.8} decimal prefix="$" suffix="T" /></div>
          <p className="desc">The global wellness economy is the fastest-growing slice of healthcare.</p>
        </Reveal>
        <Reveal delay={0.16} className="stat premium-card">
          <span className="label">Users</span>
          <div className="figure"><StatCount to={3.5} decimal suffix="B+" /></div>
          <p className="desc">People who already use traditional medicine as primary care.</p>
        </Reveal>
        <Reveal delay={0.24} className="stat premium-card">
          <span className="label">Platforms</span>
          <div className="figure">Only <StatCount to={1} /></div>
          <p className="desc">Unified, cross-tradition, cross-border infrastructure. Just one.</p>
        </Reveal>
        <Reveal delay={0.32} className="stat premium-card">
          <span className="label">Window</span>
          <div className="figure">Now</div>
          <p className="desc">AI maturity, mobile-first regions, and a global wellness shift are perfectly aligned.</p>
        </Reveal>
      </div>
      <p className="stats-foot">Until now.</p>
    </div>
  </section>
);

// ----------------------------- Image Strip --------------------
const ImageStripSection = () => <ImageStrip />;

// ----------------------------- Vision ---------------------------
// Cinematic, scroll-driven "chapter" moment — pins the section, inverts the
// theme, drifts the headline, and reveals the botanical. Fully self-contained:
// scoped ScrollTriggers, gsap.matchMedia auto-cleanup, Lenis-compatible, and a
// reduced-motion / mobile fallback. Nothing here touches any other section.
const Vision = () => {
  const rootRef = React.useRef(null);

  // Clean light editorial section — the headline reveals via SplitText; no
  // scroll-driven background inversion (kept the site white + green, not murky).

  return (
    <section id="vision" ref={rootRef}>
      <div className="wrap">
        <SectionHead tag="The Vision" num="03 / 06" />
        <div className="vision-with-art">
          <div>
            <SplitText
              className="vision-quote h3"
              delay={30}
              duration={0.8}
              ease="power3.out"
              splitType="words"
              from={{ opacity: 0, y: 30 }}
              to={{ opacity: 1, y: 0 }}
              threshold={0.3}
              textAlign="left"
              tag="p"
            >
              A future where traditional wellness is <em>easier to discover,</em> easier to trust,
              and easier to live. It must be <em>affordable</em> and accessible to <em>everyone,</em> every single day.
            </SplitText>
            <SplitText
              className="vision-tagline"
              delay={20}
              duration={0.6}
              ease="power2.out"
              splitType="chars"
              from={{ opacity: 0, x: -10 }}
              to={{ opacity: 1, x: 0 }}
              threshold={0.7}
              textAlign="left"
              tag="div"
            >
              One Globe. One Vision. One Platform.
            </SplitText>
          </div>
          <div className="vision-art">
            <BotanicalLeaf />
          </div>
        </div>
      </div>
    </section>
  );
};

// --------------------------- Solutions --------------------------
// Deep-green anchor section: the section pins itself and the four pillar images
// stack full-bleed in the background (<ScrollScene>), each sliding up over the
// last while the one it covers eases back. The intro holds for the whole run and
// only the pillar's index/heading/body swaps, crossfading in place. Same on
// mobile — the stage is just a shorter viewport.
const Solutions = () => {
  const rootRef = React.useRef(null);

  const pillars = [
    { t: "Global Practitioner Network", b: "Connect with vetted traditional healers and certified clinics worldwide.", img: "assets/pillar_network.jpg" },
    { t: "Clinical Documentation", b: "Integrate historical texts with modern evidence-based research.", img: "assets/pillar_clinical.jpg" },
    { t: "Verified Botanicals", b: "Source authenticated medicinal plants and traceable formulations.", img: "assets/pillar_botanicals.jpg" },
    { t: "Unified Ecosystem", b: "A secure, decentralized ledger linking every facet of traditional medicine.", img: "assets/pillar_ecosystem.jpg" },
  ];
  const total = String(pillars.length).padStart(2, "0");

  return (
    <section id="solutions" className="eco-section" ref={rootRef}>
      <ScrollScene className="eco-scene" stepVh={0.55}>
        <div className="scroll-scene-stage eco-stage">
          <div className="eco-stage-bg" aria-hidden="true">
            {pillars.map((it) => (
              <div
                key={it.t}
                className="scroll-scene-layer"
                style={{ backgroundImage: `url(${it.img})` }}
              />
            ))}
          </div>
          <div className="eco-stage-scrim" aria-hidden="true" />

          <div className="wrap eco-stage-content">
            {/* Swapping pillar copy on top, section intro anchoring the bottom. */}
            <div className="eco-stage-lead">
              {/* One grid cell for every step, so the block is as tall as the
                  tallest heading and the text crossfades in place. */}
              <div className="eco-steps">
                {pillars.map((it, idx) => (
                  <article key={it.t} className="scroll-scene-step eco-step">
                    <span className="eco-step-index">
                      {String(idx + 1).padStart(2, "0")} / {total}
                    </span>
                    <h3 className="eco-step-title">{it.t}</h3>
                    <p className="eco-step-body">{it.b}</p>
                  </article>
                ))}
              </div>
              <div className="eco-rail" aria-hidden="true">
                {pillars.map((it) => (
                  <span key={it.t} className="scroll-scene-tick eco-tick" />
                ))}
              </div>
            </div>

            <div className="eco-head">
              <span className="eco-eyebrow">The Platform</span>
              <h2 className="eco-section-main-title">One Connected Ecosystem</h2>
              <p className="eco-section-sub">
                Four pillars, one shared infrastructure for traditional medicine.
              </p>
            </div>
          </div>
        </div>
      </ScrollScene>
    </section>
  );
};

const Glyph = ({ name }) => {
  const stroke = "currentColor";
  const props = { width: 36, height: 36, viewBox: "0 0 36 36", fill: "none", stroke, strokeWidth: 1.2 };
  switch (name) {
    case "search": return (<svg {...props}><circle cx="15" cy="15" r="9" /><line x1="22" y1="22" x2="30" y2="30" /></svg>);
    case "shield": return (<svg {...props}><path d="M18 4 L30 9 V18 C30 25 24 30 18 32 C12 30 6 25 6 18 V9 Z" /><path d="M12 17 L17 22 L24 14" /></svg>);
    case "book": return (<svg {...props}><path d="M6 7 H17 V30 H6 Z" /><path d="M19 7 H30 V30 H19 Z" /><path d="M17 7 V30" /></svg>);
    case "leaf": return (<svg {...props}><path d="M6 30 C6 16 16 6 30 6 C30 20 20 30 6 30 Z" /><path d="M9 27 L24 12" /></svg>);
    case "spark": return (<svg {...props}><path d="M18 4 L20 16 L32 18 L20 20 L18 32 L16 20 L4 18 L16 16 Z" /></svg>);
    case "grid": return (<svg {...props}><rect x="6" y="6" width="9" height="9" /><rect x="21" y="6" width="9" height="9" /><rect x="6" y="21" width="9" height="9" /><rect x="21" y="21" width="9" height="9" /></svg>);
    case "profile": return (<svg {...props}><circle cx="18" cy="13" r="6" /><path d="M7 30 C7 23 12 20 18 20 C24 20 29 23 29 30" /></svg>);
    case "globe": return (<svg {...props}><circle cx="18" cy="18" r="12" /><ellipse cx="18" cy="18" rx="5" ry="12" /><line x1="6" y1="18" x2="30" y2="18" /><path d="M8.5 11 C12 13 24 13 27.5 11" /><path d="M8.5 25 C12 23 24 23 27.5 25" /></svg>);
    default: return null;
  }
};

// --------------------------- Platforms --------------------------
const Platforms = () => {
  const [activeTab, setActiveTab] = React.useState(0);
  const platformsData = [
    {
      id: "consumer",
      glyph: "[ MARKETPLACE · CONSUMER ]",
      name: "MyHerbalShop",
      ext: ".ai",
      sub: "Your trusted gateway to traditional wellness.",
      desc: "An AI-powered marketplace connecting conscious consumers with verified herbalists, ethical producers, and authentic botanical goods from across the globe.",
      bullets: ["AI-powered personalisation", "Verified practitioners & producers", "Transparent ingredient sourcing"],
      image: "screen 2.png",
      url: "https://myherbalshop.ai/"
    },
    {
      id: "open",
      glyph: "[ KNOWLEDGE COMMONS · OPEN ]",
      name: "HerbImmortal",
      ext: ".org",
      sub: "Free knowledge for every healer, forever.",
      desc: "An open-access knowledge platform preserving and democratizing traditional wellness wisdom. It is freely available to practitioners and communities everywhere.",
      bullets: ["Free cross-tradition knowledge", "Practitioner-contributed content", "Multi-language & multi-tradition"],
      image: "screen.png",
      url: "https://herbimmortal.org/"
    }
  ];

  return (
    <section id="platforms">
      <div className="wrap">
        <SectionHead tag="Our Platforms" num="05 / 06" />
        <div className="split">
          <h2 className="h2">One platform.<br />One mission.</h2>
          <p className="body-lg">
            A trusted consumer gateway and an open knowledge commons work together to form
            the infrastructure for global traditional wellness.
          </p>
        </div>
        <div className="platform-tabs-container">
          <div className="platform-tabs">
            <div className="platform-tab-highlight" style={{ transform: `translateX(${activeTab * 100}%)` }}></div>
            {platformsData.map((p, idx) => (
              <button key={p.id} className={`platform-tab ${activeTab === idx ? "active" : ""}`} onClick={() => setActiveTab(idx)}>
                {p.name}{p.ext}
              </button>
            ))}
          </div>
        </div>
        <div className="platforms-carousel">
          <a href={platformsData[activeTab].url} target="_blank" rel="noreferrer" className="platform-card-link fade-in" key={activeTab} style={{ display: "block", textDecoration: "none", color: "inherit", cursor: "pointer" }}>
            <Reveal delay={0.1}>
              <article className="platform-card premium-card">
                <div className="platform-card-visual" style={{ padding: 0, overflow: "hidden", borderRadius: 24 }}>
                  <img
                    src={platformsData[activeTab].image}
                    alt={platformsData[activeTab].name + platformsData[activeTab].ext}
                    style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", transition: "transform 0.4s ease" }}
                    onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.02)"}
                    onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
                  />
                </div>
                <p className="platform-card-desc">{platformsData[activeTab].desc}</p>
              </article>
            </Reveal>
          </a>
        </div>
      </div>
    </section>
  );
};

// --------------------------- Founders ---------------------------
const Founders = () => (
  <section id="founders">
    <div className="wrap">
      <SectionHead tag="Founders' Note" num="06 / 06" />
      <div className="split">
        <h2 className="h2">Why we are<br />building this.</h2>
        <div>
          <p className="body-lg">
            Traditional medicine is not alternative. For billions of people around the world,
            it is simply medicine. It is the care they grew up with. The wisdom passed through
            families, communities, healers, and generations.
          </p>
          <p className="body-lg" style={{ marginTop: 20 }}>
            Yet this vast, living body of knowledge has no global home. No shared language.
            No infrastructure that connects a healer in rural India with a seeker in Toronto.
          </p>
          <p className="body-lg" style={{ marginTop: 20 }}>
            We are building that home. Our goal is not to replace what exists, but to give it the
            infrastructure it has always deserved.
          </p>
        </div>
      </div>
      <p className="founders-quote">
        The world's oldest healing systems deserve world-class digital infrastructure.
      </p>
    </div>
  </section>
);

// --------------------------- Seed ---------------------------
const Seed = () => {
  const [modal, setModal] = React.useState(null);

  const openDeck = async () => {
    try {
      const data = await apiFetch("/invest/deck");
      window.open(data.url, "_blank");
    } catch {
      alert("Investor deck is not available yet. Please check back soon.");
    }
  };

  return (
    <>
      {modal && <Modal type={modal} onClose={() => setModal(null)} />}
      <section className="seed" id="invest">
        <div className="wrap">
          <div className="seed-inner">
            <div>
              <Tag>Seed Round Open</Tag>
              <h2 className="display-xl" style={{ marginTop: 20 }}>Join us at the beginning.</h2>
            </div>
            <div>
              <p className="body-lg">
                We are raising our first round. If you believe the world's oldest healing systems
                deserve world-class digital infrastructure, we would love to hear from you.
              </p>
              <div className="btn-row" style={{ marginTop: 32 }}>
                <button className="btn" onClick={openDeck}>View investor deck <Arrow /></button>
                <button className="btn ghost" onClick={() => setModal("collaborate")}>Collaborate with us <Arrow /></button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

// --------------------------- Footer ---------------------------
const Footer = () => (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-grid">
        <div className="brand-block">
          <div className="name-row">
            <img className="mark" src={window.__resources?.logoMark || "assets/logo-mark.png"} alt="" />
            <div className="name">Herb Immortal</div>
          </div>
          <p className="desc">
            The Operating System for Traditional Wellness. One Globe. One Vision. One Platform.
          </p>
          <div className="locales">Toronto · India · Global</div>
        </div>
        <div>
          <h4>Platform</h4>
          <ul>
            <li><a href="#vision" onClick={(e) => window.__nav(e, 'vision')}>Our Vision</a></li>
            <li><a href="#solutions" onClick={(e) => window.__nav(e, 'solutions')}>Solutions</a></li>
            <li><a href="#founders" onClick={(e) => window.__nav(e, 'founders')}>Founders' Note</a></li>
            <li><a href="BrandGuidelines.html">Brand Guidelines</a></li>
          </ul>
        </div>
        <div>
          <h4>Products</h4>
          <ul>
            <li><a href="https://myherbalshop.ai/">MyHerbalShop.ai</a></li>
            <li><a href="https://herbimmortal.org/">HerbImmortal.org</a></li>
          </ul>
        </div>
        <div>
          <h4>Company</h4>
          <ul>
            <li><a href="#">About</a></li>
            <li><a href="#">Founders</a></li>
            <li><a href="#invest">Investors</a></li>
            <li><a href="#">Collaborate</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-meta">
        <span>© 2026 Herb Immortal</span>
        <span>Timeless wisdom. Modern infrastructure.</span>
      </div>
      <div className="footer-bigname">
        <span className="serif">Herb Immortal</span>
      </div>
    </div>
  </footer>
);

Object.assign(window, {
  Nav, Hero, Marquee, IndustryGap, Stats, ImageStripSection, Vision, Solutions, Platforms, Founders, Seed, Footer
});
