/* global React */
/* =====================================================================
   SITE FOOTER — shared across every page (index + all case studies).
   Edit here once; every page that imports site-footer.jsx updates.

   Renders:
   - reversed 40px line grid (faded at top, clear at bottom)
   - big "Reach Out" headline with green accent + overlapping signature
   - green badge with slowly auto-rotating circular text + click icon
   - bottom credits bar
   - a footer-scoped purple "reach.me@naridha.id" pill cursor that takes
     over from the page's default cursor while the pointer is inside
   ===================================================================== */
(function () {
  const { useEffect, useRef, useState } = React;

  const EMAIL = "reach.me@naridha.id";

  const SendIcon = () =>
    <svg width="14" height="14" viewBox="0 0 16 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.5 1.5L7.5 8.5"></path>
      <path d="M14.5 1.5L10 13L7.5 8.5L3 6L14.5 1.5Z"></path>
    </svg>;
  const CloseIcon = () =>
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 4l10 10M14 4L4 14"></path>
    </svg>;

  /* ---------------------------------------------------------------
     CaseStudyNav — the shared header for every case-study page.
     Mirrors the homepage nav's mobile behaviour (hamburger + compact
     reach-out pill under 720px) so all pages switch to mobile mode
     consistently. Pass the page's own logo element as `logo`.
     --------------------------------------------------------------- */
  const CS_NAV_LINKS = [
    { href: "index.html#projects", label: "Projects" },
    { href: "index.html#highlights", label: "Highlights" },
    { href: "index.html#about", label: "About" },
    { href: "index.html#journal", label: "Journal" }];

  function CaseStudyNav({ logo }) {
    const [menuOpen, setMenuOpen] = useState(false);
    useEffect(() => {
      document.body.style.overflow = menuOpen ? "hidden" : "";
      return () => { document.body.style.overflow = ""; };
    }, [menuOpen]);
    const reach = (e) => {
      e.preventDefault();
      setMenuOpen(false);
      if (window.openReachOut) window.openReachOut();
    };
    return (
      <React.Fragment>
        <div className="nav-wrap">
          <nav className="nav">
            <a href="index.html" className="nav-logo" aria-label="Home">{logo}</a>
            <div className="nav-links">
              {CS_NAV_LINKS.map((l) => <a key={l.href} href={l.href} className="nav-link">{l.label}</a>)}
            </div>
            <div className="nav-right">
              <button
                className={`nav-burger ${menuOpen ? "is-open" : ""}`}
                onClick={() => setMenuOpen((o) => !o)}
                aria-label={menuOpen ? "Close menu" : "Open menu"}
                aria-expanded={menuOpen}>
                <span className="nav-burger-lines" aria-hidden="true"><span></span><span></span><span></span></span>
              </button>
              <a href="index.html" className="nav-cta" aria-label="Reach Out" onClick={reach}>
                <span className="nav-cta-label">Reach Out</span>
                <span className="icon"><SendIcon /></span>
              </a>
            </div>
          </nav>
        </div>
        <div className={`mobile-menu ${menuOpen ? "is-open" : ""}`} onClick={() => setMenuOpen(false)}>
          <div className="mobile-menu-inner" onClick={(e) => e.stopPropagation()}>
            {CS_NAV_LINKS.map((l) => <a key={l.href} href={l.href}>{l.label}</a>)}
            <button className="pill-cta mobile-menu-cta" onClick={reach}>
              Reach Out
              <span className="icon"><SendIcon /></span>
            </button>
          </div>
        </div>
      </React.Fragment>);
  }
  window.CaseStudyNav = CaseStudyNav;

  /* ---------------------------------------------------------------
     ReachOutModal — the shared contact modal. Lives here so every
     page that loads site-footer.jsx gets the exact same component;
     open it from anywhere with window.openReachOut().
     Reuses the site's existing patterns: the footer line-grid
     background, the hero ".pill-cta" button, and outline headline.
     --------------------------------------------------------------- */
  function ReachOutModal({ open, onClose }) {
    const [sent, setSent] = useState(false);
    useEffect(() => {
      if (!open) { setSent(false); return; }
      const onKey = (e) => { if (e.key === "Escape") onClose(); };
      window.addEventListener("keydown", onKey);
      document.body.classList.add("modal-open");
      return () => {
        window.removeEventListener("keydown", onKey);
        document.body.classList.remove("modal-open");
      };
    }, [open, onClose]);

    return (
      <div className={`modal-backdrop ${open ? "is-open" : ""}`} onClick={onClose} aria-hidden={!open}>
        <div className="modal reachout-modal" onClick={(e) => e.stopPropagation()}>
          <div className="ro-grid" aria-hidden="true" />
          <button className="modal-close" onClick={onClose} aria-label="Close"><CloseIcon /></button>
          {sent ?
          <div className="ro-sent">
              <h3 className="ro-title"><span className="ro-title-outline">Talk</span><br />Soon.&nbsp;<span role="img" aria-label="wave">👋</span></h3>
              <p className="ro-desc">Thanks for reaching out — I'll write back within 24 hours.</p>
              <button type="button" className="pill-cta ro-submit" onClick={onClose}>Close <span className="icon"><SendIcon /></span></button>
            </div> :

          <div className="ro-layout">
              <div className="ro-intro">
                <h3 className="ro-title"><span className="ro-title-outline">Let's Build</span><br />Something</h3>
                <p className="ro-desc">Drop a few words about your project — timeline, scope, anything that matters. I'll write back personally.</p>
              </div>
              <form className="modal-form ro-form" onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
                <label>Your name
                  <input required type="text" placeholder="Jane Doe" />
                </label>
                <label>Email
                  <input required type="email" placeholder="jane@company.com" />
                </label>
                <label>What's on your mind?
                  <textarea required placeholder="A new product, a redesign, a quick call…" />
                </label>
                <button type="submit" className="pill-cta ro-submit">Send Message <span className="icon"><SendIcon /></span></button>
              </form>
            </div>
          }
        </div>
      </div>);
  }
  window.ReachOutModal = ReachOutModal;

  /* shared project data + page mapping (mirrors homepage Projects section) */
  const PROJECTS = [
    { id: "koolio", title: "Koolio", sub: "Apps for kid's achievement report", img: "assets/project-koolio.png", href: "koolio.html" },
    { id: "styledoubler", title: "StyleDoubler", sub: "Apps micro animation", img: "assets/project-styledoubler.png", href: "styledoubler.html" },
    { id: "kvliah", title: "Kvliah", sub: "Online learning platform", img: "assets/project-kvliah.png", href: "kvliah.html" },
    { id: "indiesel", title: "Indiesel", sub: "Startup business landing page", img: "assets/project-indiesel.png", href: "indiesel.html" }];

  /* Other-projects CTA — same card design as the homepage Projects section,
     with an "Other projects" headline on the left; the currently-open case
     study is filtered out so only the others are shown. */
  function OtherProjects({ current }) {
    const items = PROJECTS.filter((p) => p.id !== current);
    const idx = PROJECTS.findIndex((p) => p.id === current);
    const next = PROJECTS[(idx + 1) % PROJECTS.length];
    return (
      <section className="op-section" data-screen-label="Other projects">
        <div className="container">
          <div className="op-layout">
            <div className="op-head">
              <h2><span className="op-w">Other</span> <span className="op-w">projects</span></h2>
              <a className="op-arrow" href={next.href} aria-label={`Next project: ${next.title}`}>
                <span className="op-arrow-track"><span>→</span><span>→</span></span>
              </a>
            </div>
            <div className="op-grid">
              {items.map((p) =>
              <a key={p.id} href={p.href} className={`ph-card ph-card-${p.id}`}>
                  <div className="ph-head">
                    <span className="ph-title">{p.title}</span>
                    <span className="ph-sub">{p.sub}</span>
                  </div>
                  <div className="ph-thumb">
                    <img src={p.img} alt={p.title} loading="lazy" />
                  </div>
                </a>
              )}
            </div>
          </div>
        </div>
      </section>);
  }
  window.OtherProjects = OtherProjects;

  /* Purple email pill cursor scoped to the footer. Self-contained so every
     page that renders SiteFooter (all case studies) gets it. On the homepage
     portfolio.jsx already renders this pill via its global CustomCursor, so we
     stay dormant there (window.__portfolioCursorActive) to avoid a duplicate. */
  function FooterCursor() {
    const wrap = useRef(null);
    useEffect(() => {
      const isFinePointer = window.matchMedia("(hover: hover) and (pointer: fine)").matches;
      if (!isFinePointer) return;

      let cx = -100, cy = -100, mx = -100, my = -100, firstMove = true, raf;
      const tick = () => {
        cx += (mx - cx) * 0.55;
        cy += (my - cy) * 0.55;
        if (wrap.current) wrap.current.style.transform = `translate(${cx}px, ${cy}px)`;
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);

      let footerEl = null;
      /* the case-study pages render their own base kite cursor (.cursor);
         suppress it while the footer pill shows so they don't stack */
      const setBaseCursor = (suppressed) => {
        document.querySelector(".cursor")?.classList.toggle("is-suppressed", suppressed);
      };
      const deactivate = () => {
        wrap.current?.classList.remove("is-active");
        if (footerEl) { footerEl.classList.remove("footer-cursor-on"); footerEl = null; }
        setBaseCursor(false);
      };
      const onMove = (e) => {
        /* homepage's global cursor owns the footer pill — stay hidden */
        if (window.__portfolioCursorActive) { deactivate(); return; }
        mx = e.clientX; my = e.clientY;
        if (firstMove) { cx = mx; cy = my; firstMove = false; }
        const t = e.target;
        const f = (t.closest && t.closest(".site-footer")) || null;
        if (f) {
          wrap.current?.classList.add("is-active");
          footerEl = f;
          f.classList.add("footer-cursor-on");
          setBaseCursor(true);
        } else {
          deactivate();
        }
      };
      const onLeave = deactivate;

      window.addEventListener("mousemove", onMove);
      document.documentElement.addEventListener("mouseleave", onLeave);
      return () => {
        cancelAnimationFrame(raf);
        window.removeEventListener("mousemove", onMove);
        document.documentElement.removeEventListener("mouseleave", onLeave);
        deactivate();
      };
    }, []);

    return (
      <div ref={wrap} className="cursor-about cursor-footer" aria-hidden="true">
        <div className="cursor-about-inner">
          <span className="cursor-about-text cursor-footer-text">{EMAIL}&nbsp;<span role="img" aria-label="call me">🤙</span></span>
          <svg className="cursor-footer-tail" width="30" height="30" viewBox="0 0 30 30" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M25.8067 12.0084L16.336 15.6054L12.7397 25.0754L4.34003 3.60944L25.8067 12.0084Z" fill="#9747FF"></path>
          </svg>
        </div>
      </div>);
  }

  function SiteFooter({ onReachOut }) {
    const root = useRef(null);
    const [reachOpen, setReachOpen] = useState(false);

    /* expose a global opener so any trigger on any page — nav CTAs, hero
       buttons, footer — can open this one shared modal without prop-drilling */
    useEffect(() => {
      window.openReachOut = () => setReachOpen(true);
      return () => { if (window.openReachOut) delete window.openReachOut; };
    }, []);

    const reach = (e) => {
      e.preventDefault();
      setReachOpen(true);
    };

    const circular = "click anywhere • to reach me out • ";

    return (
      <React.Fragment>
      <footer id="journal" className="site-footer" data-screen-label="Footer" ref={root} onClick={reach}>
        <div className="sf-grid" aria-hidden="true" />
        <div className="sf-grid-fade" aria-hidden="true" />

        <div className="sf-stage">
          <div className="sf-reach">
            <img className="sf-reach-graphic" src="assets/footer-reachout.svg" alt="Reach Out" />
            <button type="button" className="sf-badge" onClick={reach} aria-label="Reach out">
              <img className="sf-badge-ring" src="assets/badge-ring.svg" alt="" aria-hidden="true" />
              <img className="sf-badge-mouse" src="assets/badge-mouse.svg" alt="" aria-hidden="true" />
            </button>
          </div>
        </div>

        <div className="sf-bottom">
          <span className="sf-rights">Purpose in Pixels</span>
          <span>© {new Date().getFullYear()} <strong>Rizqi Naridha</strong></span>
          <span className="sf-rights">All Rights Reserved</span>
        </div>
      </footer>
      <FooterCursor />
      <ReachOutModal open={reachOpen} onClose={() => setReachOpen(false)} />
      </React.Fragment>);

  }

  window.SiteFooter = SiteFooter;
})();
