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

/* ============================================================
   Icons
   ============================================================ */
const Icon = ({ name, size = 18, stroke = 1.6, ...rest }) => {
  const paths = {
    arrowRight:  <><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></>,
    arrowUpRight:<><path d="M7 17L17 7"/><path d="M8 7h9v9"/></>,
    check:       <path d="M5 12.5l4.5 4.5L19 7.5"/>,
    plus:        <><path d="M12 5v14"/><path d="M5 12h14"/></>,
    menu:        <><path d="M4 7h16"/><path d="M4 17h16"/></>,
    close:       <><path d="M6 6l12 12"/><path d="M18 6L6 18"/></>,
    sun:         <><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4"/></>,
    moon:        <path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>,
    download:    <><path d="M12 4v12"/><path d="M7 11l5 5 5-5"/><path d="M5 20h14"/></>,
    heart:       <path d="M12 21s-7-4.35-7-10a4 4 0 0 1 7-2.65A4 4 0 0 1 19 11c0 5.65-7 10-7 10z"/>,
    leaf:        <><path d="M5 19c0-9 6-15 15-15 0 9-6 15-15 15z"/><path d="M5 19l8-8"/></>,
    pulse:       <path d="M3 12h4l2-6 4 12 2-6h6"/>,
    book:        <><path d="M4 5a2 2 0 0 1 2-2h12v18H6a2 2 0 0 1-2-2V5z"/><path d="M8 7h8M8 11h8M8 15h6"/></>,
    flask:       <><path d="M9 3h6M10 3v6.5L5 19a2 2 0 0 0 1.7 3h10.6A2 2 0 0 0 19 19l-5-9.5V3"/></>,
    shield:      <path d="M12 3l8 3v6c0 5-4 8-8 9-4-1-8-4-8-9V6l8-3z"/>,
    sparkle:     <><path d="M12 3l1.6 5.4L19 10l-5.4 1.6L12 17l-1.6-5.4L5 10l5.4-1.6z"/></>,
    users:       <><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0"/><circle cx="17" cy="9" r="2.5"/><path d="M21 19a4.5 4.5 0 0 0-4.5-4.5"/></>,
    map:         <><path d="M3 6l6-2 6 2 6-2v14l-6 2-6-2-6 2z"/><path d="M9 4v16M15 6v16"/></>,
    phone:       <path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.6a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.5-1.5a2 2 0 0 1 2.1-.5c.8.3 1.7.6 2.6.7A2 2 0 0 1 22 16.9z"/>,
    chat:        <><path d="M21 12a8 8 0 0 1-12.4 6.7L3 20l1.3-5.6A8 8 0 1 1 21 12z"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" {...rest}>
      {paths[name]}
    </svg>
  );
};

/* ============================================================
   Logo mark
   ============================================================ */
const WillowMark = ({ size = 30 }) => (
  <span className="mark" style={{ width: size, height: size, borderRadius: size * 0.33 }}>
    <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 24 24" fill="none">
      <path d="M4 20C 4 10, 10 4, 20 4 C 18 12, 14 18, 4 20 Z" fill="currentColor"/>
      <path d="M4 20 L 14 10" stroke="rgba(241,237,228,0.45)" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  </span>
);

/* ============================================================
   Button
   ============================================================ */
const Button = ({ variant = "primary", size = "", children, withArrow = false, onClick, ...rest }) => {
  const cls = `btn btn-${variant} ${size === "lg" ? "btn-lg" : size === "sm" ? "btn-sm" : ""}`;
  return (
    <button className={cls} onClick={onClick} {...rest}>
      {children}
      {withArrow && <span className="arrow"><Icon name="arrowRight" size={16}/></span>}
    </button>
  );
};

/* ============================================================
   useInView
   ============================================================ */
const useInView = (options = {}) => {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); io.disconnect(); }
    }, { threshold: 0.15, ...options });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, inView];
};

/* ============================================================
   Counter
   ============================================================ */
const Counter = ({ end, duration = 1600, prefix = "", suffix = "", className = "" }) => {
  const [ref, inView] = useInView();
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!inView) return;
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setV(Math.round(end * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, end, duration]);
  return <span ref={ref} className={className}>{prefix}{v.toLocaleString()}{suffix}</span>;
};

/* ============================================================
   Reveal
   ============================================================ */
const Reveal = ({ children, as = "div", delay = 0, stagger = false, className = "", ...rest }) => {
  const [ref, inView] = useInView();
  const Tag = as;
  const style = delay ? { transitionDelay: `${delay}ms` } : undefined;
  return (
    <Tag ref={ref} className={`${stagger ? "stagger" : "reveal"} ${inView ? "in" : ""} ${className}`} style={style} {...rest}>
      {children}
    </Tag>
  );
};

/* ============================================================
   Particles
   ============================================================ */
const Particles = () => {
  const canvasRef = useRef(null);
  useEffect(() => {
    const cvs = canvasRef.current;
    if (!cvs) return;
    const ctx = cvs.getContext("2d");
    let raf, dots = [], w = 0, h = 0, dpr = Math.min(2, window.devicePixelRatio || 1);
    const resize = () => {
      const rect = cvs.getBoundingClientRect();
      w = rect.width; h = rect.height;
      cvs.width = w * dpr; cvs.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      const count = Math.floor((w * h) / 22000);
      dots = Array.from({ length: count }, () => ({
        x: Math.random() * w, y: Math.random() * h,
        r: Math.random() * 1.8 + 0.4,
        vx: (Math.random() - 0.5) * 0.18, vy: (Math.random() - 0.5) * 0.18,
        a: Math.random() * 0.5 + 0.15,
      }));
    };
    resize();
    window.addEventListener("resize", resize);
    const tick = () => {
      ctx.clearRect(0, 0, w, h);
      for (const d of dots) {
        d.x += d.vx; d.y += d.vy;
        if (d.x < 0 || d.x > w) d.vx *= -1;
        if (d.y < 0 || d.y > h) d.vy *= -1;
        ctx.beginPath();
        ctx.fillStyle = `rgba(92,124,95,${d.a})`;
        ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2);
        ctx.fill();
      }
      for (let i = 0; i < dots.length; i++) {
        for (let j = i + 1; j < dots.length; j++) {
          const a = dots[i], b = dots[j];
          const dist = Math.hypot(a.x - b.x, a.y - b.y);
          if (dist < 140) {
            ctx.strokeStyle = `rgba(92,124,95,${0.08 * (1 - dist / 140)})`;
            ctx.lineWidth = 0.6;
            ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
          }
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, []);
  return <canvas ref={canvasRef} className="particle-canvas" aria-hidden="true"/>;
};

/* ============================================================
   Nav
   ============================================================ */
const NAV_ITEMS = [
  { id: "community",  label: "About" },
  { id: "home",       label: "Home" },
  { id: "ourwork",    label: "Our Work" },
  { id: "chapters",   label: "Chapters" },
  { id: "ambassador", label: "Ambassador" },
  { id: "officers",   label: "Officers" },
  { id: "research",   label: "Professors" },
  { id: "outreach",   label: "Contribute" },
];

const Nav = ({ current, go, dark, setDark }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => { document.body.classList.toggle("no-scroll", open); }, [open]);

  return (
    <>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div className="nav-inner">
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
            <a className="logo" onClick={(e) => { e.preventDefault(); go("home"); }} href="#" aria-label="Willow Initiative — Home">
              <WillowMark/><span>Willow</span>
            </a>
            <button onClick={() => go("community")} style={{ padding: "8px 14px", borderRadius: "var(--r-pill)", fontSize: 14, color: current === "community" ? "var(--ink)" : "var(--ink-soft)", background: current === "community" ? "var(--bg-2)" : "transparent", border: "none", cursor: "pointer", fontWeight: current === "community" ? 500 : 400 }}>
              About
            </button>
          </div>
          <div className="nav-pill">
            <div className="links">
              {NAV_ITEMS.filter(it => it.id !== "community").map(it => (
                <button key={it.id} className={current === it.id ? "active" : ""} onClick={() => go(it.id)}>
                  {it.label}
                </button>
              ))}
            </div>
            <button className="nav-mobile-btn btn btn-ghost btn-sm" style={{ boxShadow: "none" }} onClick={() => setOpen(true)} aria-label="Open menu">
              <Icon name="menu" size={18}/>
            </button>
          </div>
          <div className="nav-ctas-desktop" style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <Button variant="ghost" size="sm" onClick={() => go("gethelp")} style={{ color: "var(--sage)", boxShadow: "inset 0 0 0 1px var(--sage)" }}>
              <Icon name="phone" size={13}/> Get Help
            </Button>
            <Button variant="sage" size="sm" onClick={() => go("donate")}>Donate</Button>
          </div>
        </div>
      </nav>

      {open && (
        <div className="nav-sheet" onClick={() => setOpen(false)}>
          <div className="nav-sheet-inner" onClick={(e) => e.stopPropagation()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, padding: "0 8px" }}>
              <a className="logo" href="#" onClick={(e) => { e.preventDefault(); go("home"); setOpen(false); }}>
                <WillowMark/><span>Willow</span>
              </a>
              <button className="btn btn-ghost btn-sm" style={{ width: 38, height: 38, padding: 0, borderRadius: 999 }} onClick={() => setOpen(false)}>
                <Icon name="close" size={16}/>
              </button>
            </div>
            {NAV_ITEMS.concat([{ id: "gethelp", label: "Get Help" }, { id: "donate", label: "Donate" }]).map(it => (
              <button key={it.id} className={current === it.id ? "active" : ""} onClick={() => { go(it.id); setOpen(false); }}>
                {it.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </>
  );
};

/* ============================================================
   Footer
   ============================================================ */
const Footer = ({ go }) => (
  <footer className="footer">
    <div className="footer-grid">
      <div>
        <a className="logo" href="#" onClick={(e) => { e.preventDefault(); go("home"); }}>
          <WillowMark/><span>Willow Initiative</span>
        </a>
        <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 14.5, maxWidth: "34ch" }}>
          A youth-led movement. Every life matters.
        </p>
        <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
          <Button variant="soft" size="sm" onClick={() => go("gethelp")}>Get Involved</Button>
          <Button variant="sage" size="sm" onClick={() => go("donate")}>Donate</Button>
        </div>
      </div>
      <div>
        <h4>Get Involved</h4>
        <ul>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("ambassador"); }}>Become an Ambassador</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("ambassador"); }}>Open a Chapter</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("community"); }}>Mentor Network</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("donate"); }}>Donate</a></li>
        </ul>
      </div>
      <div>
        <h4>Resources</h4>
        <ul>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("research"); }}>Professors</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("gethelp"); }}>Get Help Now</a></li>
          <li><a href="tel:18006624357">SAMHSA: 1-800-662-4357</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("gethelp"); }}>Crisis Text Line</a></li>
        </ul>
      </div>
      <div>
        <h4>Organization</h4>
        <ul>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("ourwork"); }}>Our Work</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("officers"); }}>Officers</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("outreach"); }}>Contribute</a></li>
          <li><a href="#" onClick={(e) => { e.preventDefault(); go("community"); }}>About</a></li>
        </ul>
      </div>
      <div>
        <h4>Contact</h4>
        <ul>
          <li><a href="mailto:willowinitiative333@gmail.com">willowinitiative333@gmail.com</a></li>
          <li><a href="tel:988">988 Crisis Lifeline</a></li>
          <li><a href="https://www.instagram.com/willowinitiative/" target="_blank" rel="noopener noreferrer">Instagram @willowinitiative</a></li>
        </ul>
      </div>
    </div>
    <div className="footer-base">
      <span>© 2026 The Willow Initiative. All rights reserved.</span>
      <span>Built by students, for the next generation.</span>
    </div>
  </footer>
);

/* ============================================================
   FooterCTA
   ============================================================ */
const FooterCTA = ({ go, title, sub, buttons }) => (
  <div className="cta-block reveal in">
    <h2>{title || <>Help build a generation <span className="ital">free from addiction.</span></>}</h2>
    {sub && <p className="lede" style={{ color: "rgba(241,237,228,0.7)", maxWidth: "60ch", marginTop: 18, position: "relative" }}>{sub}</p>}
    <div className="row">
      {(buttons || [
        { label: "Join the movement", variant: "primary", page: "gethelp", withArrow: true },
        { label: "Donate",            variant: "ghost",   page: "donate" },
      ]).map(b => (
        <Button key={b.label} variant={b.variant} withArrow={b.withArrow} onClick={() => go(b.page)}>{b.label}</Button>
      ))}
    </div>
  </div>
);

/* ============================================================
   Spark
   ============================================================ */
const Spark = ({ points, accent = "var(--sage)" }) => {
  const max = Math.max(...points), min = Math.min(...points), span = max - min || 1;
  const w = 100, h = 28, step = w / (points.length - 1);
  const d = points.map((p, i) => `${i === 0 ? "M" : "L"} ${i * step} ${h - ((p - min) / span) * h}`).join(" ");
  const last = points.length - 1;
  return (
    <svg className="spark" viewBox={`0 -2 ${w} ${h + 4}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="sg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={accent} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={accent} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={`${d} L ${w} ${h} L 0 ${h} Z`} fill="url(#sg)"/>
      <path d={d} fill="none" stroke={accent} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke"/>
      <circle cx={last * step} cy={h - ((points[last] - min) / span) * h} r="2" fill={accent}/>
    </svg>
  );
};

const InstagramReel = ({ url }) => {
  React.useEffect(() => {
    if (window.instgrm) window.instgrm.Embeds.process();
    else {
      const s = document.createElement("script");
      s.src = "https://www.instagram.com/embed.js";
      s.async = true;
      s.onload = () => window.instgrm?.Embeds?.process();
      document.body.appendChild(s);
    }
  }, [url]);
  return (
    <div style={{ display: "flex", justifyContent: "center", width: "100%" }}>
      <blockquote
        className="instagram-media"
        data-instgrm-permalink={url}
        data-instgrm-version="14"
        style={{ background: "#FFF", border: 0, borderRadius: 3, margin: "0 auto", maxWidth: 400, width: "100%" }}
      />
    </div>
  );
};

Object.assign(window, {
  Icon, WillowMark, Button, Nav, Footer, FooterCTA,
  Reveal, Counter, useInView, Particles, Spark,
  NAV_ITEMS, InstagramReel,
});
