// ═══════════════════════════════════════════════════════════════
// SHELL — shared chrome, helpers, persistence across all pages
// ═══════════════════════════════════════════════════════════════
const { useEffect, useRef, useState, useMemo } = React;

// ───────────── Palettes ─────────────
const PALETTES = {
  aurora: ["#b5fd5b", "#6ee7ff", "#d894ff"],
  ember:  ["#ffb14a", "#ff6a88", "#f24e64"],
  arctic: ["#a7f3ff", "#7aa6ff", "#c9d1ff"],
  mono:   ["#f4f4f5", "#a1a1aa", "#71717a"],
};

// ───────────── Cross-page Tweak persistence ─────────────
// useTweaks() comes from tweaks-panel.jsx — wraps it with localStorage so palette + grain
// follow the user across pages, while the per-page EDITMODE block still persists official defaults.
function useSiteTweaks(defaults) {
  const stored = (() => {
    try { return JSON.parse(localStorage.getItem("digitacurve.tweaks") || "{}"); }
    catch (e) { return {}; }
  })();
  const merged = { ...defaults, ...stored };
  const t = useTweaks(merged);
  const wrapped = useMemo(() => {
    const orig = t.setTweak;
    return Object.assign({}, t, {
      setTweak: (k, v) => {
        orig(k, v);
        const next = (typeof k === "object") ? { ...t, ...k } : { ...t, [k]: v };
        try {
          const clean = {};
          Object.keys(defaults).forEach(key => { clean[key] = next[key]; });
          localStorage.setItem("digitacurve.tweaks", JSON.stringify(clean));
        } catch (e) {}
      }
    });
  }, [t]);
  return wrapped;
}

// ───────────── Reveal on scroll ─────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((ents) => {
      ents.forEach(e => { if (e.isIntersecting) { el.classList.add("in"); io.unobserve(el); }});
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, delay = 0, as: As = "div", style = {}, className = "" }) {
  const r = useReveal();
  return <As ref={r} className={`reveal ${className}`} style={{ transitionDelay: `${delay}ms`, ...style }}>{children}</As>;
}

// ───────────── 3D tilt card ─────────────
function TiltCard({ children, max = 6, style = {}, className = "", onClick }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width;
    const y = (e.clientY - r.top) / r.height;
    el.style.transform = `perspective(1100px) rotateX(${(0.5 - y) * max}deg) rotateY(${(x - 0.5) * max}deg) translateZ(0)`;
    el.style.setProperty("--mx", `${x * 100}%`);
    el.style.setProperty("--my", `${y * 100}%`);
  };
  const onLeave = () => { const el = ref.current; if (el) el.style.transform = "perspective(1100px) rotateX(0) rotateY(0)"; };
  return (
    <div ref={ref} className={`tilt-card glow-edge ${className}`} style={style}
         onMouseMove={onMove} onMouseLeave={onLeave} onClick={onClick}>
      {children}
    </div>
  );
}

// ───────────── Logo ─────────────
function LogoMark({ accent }) {
  return (
    <div style={{ width: 28, height: 28, position: "relative" }}>
      <svg viewBox="0 0 40 40" width="28" height="28">
        <defs>
          <linearGradient id="lg" x1="0" y1="0" x2="40" y2="40" gradientUnits="userSpaceOnUse">
            <stop offset="0" stopColor={accent[0]}/>
            <stop offset="0.5" stopColor={accent[1]}/>
            <stop offset="1" stopColor={accent[2]}/>
          </linearGradient>
        </defs>
        <path d="M20 4 C 30 4, 36 10, 36 20 C 36 30, 30 36, 20 36 C 12 36, 8 32, 8 26 C 8 20, 12 18, 18 18 C 22 18, 24 20, 24 22"
              fill="none" stroke="url(#lg)" strokeWidth="3.2" strokeLinecap="round"/>
        <circle cx="24" cy="22" r="2.4" fill="url(#lg)"/>
      </svg>
    </div>
  );
}

// ───────────── Cross-page Nav ─────────────
const NAV_LINKS = [
  { label: "Home", href: "index.html" },
  { label: "Work", href: "work.html" },
  { label: "Projects", href: "work.html#archive" },
  { label: "Services", href: "services.html" },
  { label: "Contact", href: "contact.html" },
];

function isActive(href) {
  const path = (window.location.pathname.split("/").pop() || "index.html");
  return path === href || (href === "index.html" && (path === "" || path === "index.html"));
}

function Nav({ accent }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <>
      <div style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
        padding: scrolled ? "14px 24px" : "22px 24px",
        transition: "padding .4s cubic-bezier(.2,.7,.2,1)"
      }}>
        <div className="liquid-glass" style={{
          maxWidth: 1180, margin: "0 auto",
          borderRadius: 999, padding: "10px 14px 10px 22px",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          gap: 24
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 32 }}>
            <a href="index.html" style={{ display: "flex", alignItems: "center", gap: 10, color: "#fff", textDecoration: "none" }}>
              <LogoMark accent={accent} />
              <span style={{ fontSize: 17, letterSpacing: "-0.02em", fontWeight: 600 }}>Digitacurve</span>
            </a>
            <div style={{ display: "flex", alignItems: "center", gap: 26 }} className="nav-links">
              {NAV_LINKS.map(l => {
                const on = isActive(l.href);
                return (
                  <a key={l.label} href={l.href} style={{
                    color: on ? "#fff" : "rgba(255,255,255,0.7)",
                    fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em",
                    textDecoration: "none", position: "relative", padding: "4px 0"
                  }}
                  onMouseEnter={e=>e.currentTarget.style.color="#fff"}
                  onMouseLeave={e=>e.currentTarget.style.color=on?"#fff":"rgba(255,255,255,0.7)"}>
                    {l.label}
                    {on && <span style={{
                      position: "absolute", left: 0, right: 0, bottom: -4, height: 2,
                      background: accent[0], borderRadius: 2,
                    }}/>}
                  </a>
                );
              })}
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <a href="contact.html" style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "10px 18px", borderRadius: 999,
              background: "#fff", color: "#07070a", fontSize: 14, fontWeight: 500,
              textDecoration: "none"
            }} className="nav-cta">
              Start a project <I.ArrowUpRight size={14} stroke={2}/>
            </a>
            <button onClick={()=>setOpen(o=>!o)} className="nav-burger" style={{
              display: "none", width: 40, height: 40, borderRadius: 99,
              background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.1)",
              color: "#fff", alignItems: "center", justifyContent: "center", cursor: "pointer"
            }}>
              {open ? <I.Close size={18} stroke={1.6}/> : <I.Menu size={18} stroke={1.6}/>}
            </button>
          </div>
        </div>
      </div>

      {/* Mobile drawer */}
      {open && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 49,
          background: "rgba(7,7,10,0.92)", backdropFilter: "blur(20px)",
          paddingTop: 100, padding: "100px 24px 40px"
        }}>
          <div style={{ maxWidth: 600, margin: "0 auto", display: "flex", flexDirection: "column", gap: 4 }}>
            {NAV_LINKS.map(l => (
              <a key={l.label} href={l.href} style={{
                color: "#fff", fontSize: 36, padding: "14px 0",
                borderBottom: "1px solid rgba(255,255,255,0.08)",
                textDecoration: "none", fontFamily: "'Instrument Serif', serif",
                letterSpacing: "-0.02em"
              }}>{l.label}</a>
            ))}
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 760px){
          .nav-links{ display: none !important; }
          .nav-burger{ display: inline-flex !important; }
          .nav-cta{ display: none !important; }
        }
      `}</style>
    </>
  );
}

// ───────────── Footer ─────────────
function Footer({ accent }) {
  return (
    <footer style={{ padding: "120px 24px 40px", position: "relative", borderTop: "1px solid rgba(255,255,255,0.06)" }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 48, marginBottom: 80 }} className="footer-grid">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 20 }}>
              <LogoMark accent={accent}/>
              <span style={{ fontSize: 22, letterSpacing: "-0.02em", fontWeight: 600 }}>Digitacurve</span>
            </div>
            <p style={{ color: "rgba(255,255,255,0.5)", fontSize: 15, lineHeight: 1.6, maxWidth: 320, marginBottom: 28 }}>
              An independent studio building brands, products and growth engines for the next generation of category leaders.
            </p>
            <div style={{ display: "flex", gap: 8 }}>
              {[I.Instagram, I.Twitter, I.Linkedin, I.Dribbble].map((Ic, i) => (
                <a key={i} href="#" className="liquid-glass" style={{
                  width: 40, height: 40, borderRadius: 99,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  color: "rgba(255,255,255,0.78)"
                }}>
                  <Ic size={16} stroke={1.5}/>
                </a>
              ))}
            </div>
          </div>

          <div>
            <div style={{ color: "rgba(255,255,255,0.45)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 18 }}>Studio</div>
            <a className="footer-link" href="about.html">About</a>
            <a className="footer-link" href="services.html">Services</a>
            <a className="footer-link" href="work.html">Work</a>
            <a className="footer-link" href="journal.html">Journal</a>
            <a className="footer-link" href="about.html#careers">Careers</a>
            <a className="footer-link" href="contact.html">Contact</a>
          </div>

          <div>
            <div style={{ color: "rgba(255,255,255,0.45)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 18 }}>Studios</div>
            <a className="footer-link" href="contact.html">🇦🇺 Sydney</a>
            <a className="footer-link" href="contact.html">🇮🇳 Bangalore</a>
            <a className="footer-link" href="contact.html">🇺🇸 New York</a>
            <a className="footer-link" href="contact.html">🇬🇧 London</a>
          </div>

          <div>
            <div style={{ color: "rgba(255,255,255,0.45)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 18 }}>Newsletter</div>
            <p style={{ color: "rgba(255,255,255,0.6)", fontSize: 14, lineHeight: 1.5, marginBottom: 16 }}>
              A monthly note. Selected work, what we learned, no fluff.
            </p>
            <form onSubmit={e=>{e.preventDefault();}} className="liquid-glass" style={{ borderRadius: 99, padding: "5px 5px 5px 18px", display: "flex", alignItems: "center", gap: 8 }}>
              <input className="input-bare" placeholder="your@email" style={{ fontSize: 14 }}/>
              <button type="submit" style={{ width: 36, height: 36, borderRadius: 99, background: "#fff", color: "#07070a", display: "flex", alignItems: "center", justifyContent: "center", border: "none", cursor: "pointer" }}>
                <I.Arrow size={14} stroke={2.2}/>
              </button>
            </form>
          </div>
        </div>

        {/* Giant wordmark */}
        <div style={{ overflow: "hidden", marginBottom: 40, borderTop: "1px solid rgba(255,255,255,0.06)", paddingTop: 60 }}>
          <div className="font-serif" style={{
            fontSize: "clamp(80px, 18vw, 280px)",
            lineHeight: 0.9, letterSpacing: "-0.04em",
            textAlign: "center",
            background: `linear-gradient(180deg, rgba(255,255,255,0.92), rgba(255,255,255,0.18) 110%)`,
            WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent",
            whiteSpace: "nowrap"
          }}>
            Digitacurve<span className="italic-serif" style={{ color: accent[0], background: "none", WebkitTextFillColor: accent[0] }}>.</span>
          </div>
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16, color: "rgba(255,255,255,0.42)", fontSize: 13 }}>
          <div>© 2026 Digitacurve Studio Pty Ltd. ABN 71 994 220 011.</div>
          <div style={{ display: "flex", gap: 22 }}>
            <a href="#" style={{ color: "inherit" }}>Privacy</a>
            <a href="#" style={{ color: "inherit" }}>Terms</a>
            <span className="font-mono">v2.6.0 — May 2026</span>
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 880px){ .footer-grid{ grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 520px){ .footer-grid{ grid-template-columns: 1fr !important; } }`}</style>
    </footer>
  );
}

// ───────────── Custom cursor ─────────────
function useCustomCursor(accent) {
  useEffect(() => {
    const dot = document.querySelector(".cursor-dot");
    if (!dot) return;
    let raf, tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => { tx = e.clientX; ty = e.clientY; };
    const tick = () => {
      x += (tx - x) * 0.22;
      y += (ty - y) * 0.22;
      dot.style.transform = `translate(${x}px, ${y}px) translate(-50%,-50%)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener("mousemove", onMove);
    raf = requestAnimationFrame(tick);
    const isHover = (el) => el && (el.matches && el.matches("a, button, [data-cursor]") || el.closest && el.closest("a, button, [data-cursor]"));
    const onOver = (e) => { if (isHover(e.target)) dot.classList.add("hover"); };
    const onOut = (e) => { if (isHover(e.target)) dot.classList.remove("hover"); };
    document.addEventListener("mouseover", onOver);
    document.addEventListener("mouseout", onOut);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseover", onOver);
      document.removeEventListener("mouseout", onOut);
    };
  }, []);
}

// ───────────── Site Chrome wrapper (cursor + nav + content + footer + tweaks) ─────────────
function SiteChrome({ accent, t, children }) {
  useCustomCursor(accent);
  return (
    <>
      <div className="cursor-dot" style={{
        position: "fixed", left: 0, top: 0, width: 18, height: 18,
        borderRadius: 99, border: `1.5px solid ${accent[0]}`,
        background: `${accent[0]}18`,
        pointerEvents: "none", zIndex: 9999,
        mixBlendMode: "difference",
        transition: "width .25s, height .25s, background .25s"
      }}/>
      <style>{`
        .cursor-dot.hover{ width: 44px !important; height: 44px !important; background: ${accent[0]}28 !important; }
        @media (hover: none){ .cursor-dot{ display: none !important; } }
      `}</style>

      <Nav accent={accent}/>
      {children}
      <Footer accent={accent}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent palette">
          <TweakColor
            label="Theme"
            value={accent}
            onChange={(v) => {
              const key = Object.keys(PALETTES).find(k => PALETTES[k][0] === v[0]) || "aurora";
              t.setTweak("palette", key);
            }}
            options={Object.values(PALETTES)}
          />
        </TweakSection>
        {t.videoBg !== undefined && (
          <TweakSection label="Hero">
            <TweakToggle label="Background video" value={t.videoBg} onChange={(v)=>t.setTweak("videoBg", v)}/>
          </TweakSection>
        )}
        <TweakSection label="Atmosphere">
          <TweakToggle label="Subtle grain overlay" value={t.grain} onChange={(v)=>t.setTweak("grain", v)}/>
        </TweakSection>
      </TweaksPanel>

      {t.grain && (
        <div style={{
          position: "fixed", inset: 0, pointerEvents: "none", zIndex: 200,
          backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='160'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1  0 0 0 0 1  0 0 0 0 1  0 0 0 0.45 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>\")",
          opacity: 0.06, mixBlendMode: "overlay"
        }}/>
      )}
    </>
  );
}

// ───────────── Page header used on non-home pages ─────────────
function PageHero({ kicker, title, italic, suffix, sub, accent, eyebrow, children }) {
  return (
    <section style={{ position: "relative", padding: "180px 24px 80px", overflow: "hidden" }}>
      {/* Atmospheric blobs */}
      <div className="blob floaty" style={{ width: 700, height: 700, top: -200, left: -150,
        background: `radial-gradient(circle, ${accent[1]}22, transparent 70%)` }}/>
      <div className="blob floaty" style={{ width: 500, height: 500, top: 100, right: -100,
        background: `radial-gradient(circle, ${accent[2]}22, transparent 70%)`, animationDelay: "-4s" }}/>
      {/* Grid */}
      <div style={{ position: "absolute", inset: 0, opacity: 0.4,
        backgroundImage: "linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)",
        backgroundSize: "60px 60px", maskImage: "radial-gradient(ellipse at center, black 30%, transparent 75%)" }}/>

      <div className="container" style={{ position: "relative", zIndex: 2 }}>
        {eyebrow && <Reveal><div style={{ marginBottom: 20 }}><span className="kicker"><span className="dot"/> {eyebrow}</span></div></Reveal>}
        {kicker && <Reveal><div className="font-mono" style={{ color: "rgba(255,255,255,0.5)", fontSize: 12, letterSpacing: "0.22em", textTransform: "uppercase", marginBottom: 28 }}>{kicker}</div></Reveal>}
        <Reveal delay={80}>
          <h1 className="font-serif" style={{
            fontSize: "clamp(56px, 9vw, 148px)",
            lineHeight: 0.94, letterSpacing: "-0.028em",
            color: "#fff", marginBottom: 28, textWrap: "balance", maxWidth: 1100
          }}>
            {title}{italic && <> <span className="italic-serif" style={{ color: "rgba(255,255,255,0.55)" }}>{italic}</span></>}
            {suffix && <> <span style={{
              background: `linear-gradient(110deg, ${accent[0]}, ${accent[1]} 55%, ${accent[2]})`,
              WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent"
            }}>{suffix}</span></>}
          </h1>
        </Reveal>
        {sub && (
          <Reveal delay={160}>
            <p style={{ color: "rgba(255,255,255,0.68)", fontSize: 19, lineHeight: 1.55, maxWidth: 640 }}>{sub}</p>
          </Reveal>
        )}
        {children && <Reveal delay={220}><div style={{ marginTop: 36 }}>{children}</div></Reveal>}
      </div>
    </section>
  );
}

// ───────────── CTA band ─────────────
function CTABand({ accent, eyebrow = "Ready when you are", title = "Let's build something the internet remembers.", cta = "Start a project", href = "contact.html" }) {
  return (
    <section style={{ padding: "0 24px 60px", position: "relative" }}>
      <div className="container">
        <div className="liquid-glass-strong" style={{
          borderRadius: 32, padding: "80px 60px", position: "relative", overflow: "hidden", textAlign: "center"
        }}>
          <div style={{ position: "absolute", inset: 0,
            background: `radial-gradient(ellipse at 30% 0%, ${accent[1]}22, transparent 60%), radial-gradient(ellipse at 80% 100%, ${accent[2]}22, transparent 60%)`,
            pointerEvents: "none"
          }}/>
          <div style={{ position: "relative", zIndex: 1 }}>
            <div className="font-mono" style={{ color: "rgba(255,255,255,0.5)", fontSize: 12, letterSpacing: "0.22em", textTransform: "uppercase", marginBottom: 22 }}>{eyebrow}</div>
            <h3 className="font-serif" style={{ fontSize: "clamp(40px, 5.4vw, 84px)", lineHeight: 1, letterSpacing: "-0.02em", maxWidth: 900, margin: "0 auto 36px" }} dangerouslySetInnerHTML={{__html: title}}/>
            <a href={href} className="btn-primary" style={{ fontSize: 16 }}>{cta} <I.Arrow size={16} stroke={2}/></a>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  PALETTES, useSiteTweaks, useReveal, Reveal, TiltCard, LogoMark, Nav, Footer,
  SiteChrome, PageHero, CTABand, NAV_LINKS
});
