/* global React, ReactDOM, Nav, Hero, Services, How, Work, Testimonials, About, Pricing, FAQ, FootCTA, Legal, LogoMarquee,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakText, TweakSelect */
const { useEffect } = React;

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#1A1814",
  "accentHi": "#3A352E",
  "headline": "Your website should be |working harder| than it is.",
  "heroBg": "gradient",
  "density": "default"
}/*EDITMODE-END*/;

function applyTokens({ accent, accentHi, heroBg, density }) {
  const root = document.documentElement;
  root.style.setProperty("--accent", accent);
  root.style.setProperty("--accent-hi", accentHi);
  // soft = 12% alpha — derive crudely
  const hex = accent.replace("#", "");
  const r = parseInt(hex.slice(0,2),16), g = parseInt(hex.slice(2,4),16), b = parseInt(hex.slice(4,6),16);
  root.style.setProperty("--accent-soft", `rgba(${r},${g},${b},0.14)`);
  root.setAttribute("data-hero-bg", heroBg);
  root.setAttribute("data-density", density);
}

function useReveal() {
  useEffect(() => {
    // Auto-tag children of any .reveal-stagger as .reveal with cascading delays.
    document.querySelectorAll(".reveal-stagger").forEach((parent) => {
      [...parent.children].forEach((child, i) => {
        child.classList.add("reveal");
        child.style.setProperty("--reveal-delay", (i * 0.09) + "s");
      });
    });

    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: "0px 0px -6% 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* Top-of-page scroll-progress bar */
function ScrollProgress() {
  useEffect(() => {
    const bar = document.getElementById("scroll-progress");
    let raf = 0;
    const update = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      const pct = max > 0 ? (h.scrollTop || window.scrollY) / max : 0;
      bar.style.transform = `scaleX(${Math.min(1, Math.max(0, pct))})`;
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    update();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, []);
  return <div className="scroll-progress" aria-hidden="true"><span id="scroll-progress" /></div>;
}

/* Magnetic 3D tilt on .tilt cards (work cards). Disabled on touch + reduced-motion. */
function useMagneticTilt() {
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const touch = window.matchMedia("(hover: none)").matches;
    if (reduce || touch) return;
    const cards = document.querySelectorAll(".tilt");
    const handlers = [];
    cards.forEach(card => {
      const onMove = (ev) => {
        const r = card.getBoundingClientRect();
        const x = (ev.clientX - r.left) / r.width - 0.5;
        const y = (ev.clientY - r.top) / r.height - 0.5;
        card.style.setProperty("--tx", (x * 8).toFixed(2) + "deg");
        card.style.setProperty("--ty", (-y * 8).toFixed(2) + "deg");
        card.style.setProperty("--mx", (x * 100 + 50) + "%");
        card.style.setProperty("--my", (y * 100 + 50) + "%");
      };
      const onLeave = () => {
        card.style.setProperty("--tx", "0deg");
        card.style.setProperty("--ty", "0deg");
      };
      card.addEventListener("pointermove", onMove);
      card.addEventListener("pointerleave", onLeave);
      handlers.push([card, onMove, onLeave]);
    });
    return () => handlers.forEach(([c, m, l]) => { c.removeEventListener("pointermove", m); c.removeEventListener("pointerleave", l); });
  }, []);
}

function App() {
  const [tweaks, setTweak] = useTweaks(DEFAULTS);

  useEffect(() => { applyTokens(tweaks); }, [tweaks]);
  useReveal();
  useMagneticTilt();

  return (
    <>
      <ScrollProgress />
      <Nav />
      <main>
        <Hero headline={tweaks.headline} />
        <LogoMarquee />
        <Services />
        <How />
        <Work />
        <Testimonials />
        <About />
        {/* <Pricing /> — hidden for now */}
        <FAQ />
        <FootCTA />
      </main>
      <Legal />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Accent">
          <TweakColor label="Primary"  value={tweaks.accent}    onChange={v => setTweak("accent", v)} />
          <TweakColor label="Hover"    value={tweaks.accentHi}  onChange={v => setTweak("accentHi", v)} />
          <div style={{ display: "flex", gap: 6, marginTop: 6, flexWrap: "wrap" }}>
            {[
              ["Teal",   "#0E7C67", "#1A9E88"],
              ["Lime",   "#9DCC4D", "#B8E26E"],
              ["Amber",  "#D9A24A", "#E7B86B"],
              ["Indigo", "#6366F1", "#818CF8"],
              ["Coral",  "#E5614C", "#F2826F"],
              ["Off-white", "#EDEAE2", "#F5F2EA"],
            ].map(([n,a,h]) => (
              <button key={n}
                onClick={() => setTweak({ accent: a, accentHi: h })}
                style={{
                  background: a, color: "#0a0a0a", fontSize: 11, fontWeight: 500,
                  padding: "5px 9px", borderRadius: 999, border: "1px solid rgba(255,255,255,0.1)"
                }}>{n}</button>
            ))}
          </div>
        </TweakSection>

        <TweakSection title="Hero background">
          <TweakRadio
            value={tweaks.heroBg}
            onChange={v => setTweak("heroBg", v)}
            options={[
              { value: "gradient", label: "Gradient" },
              { value: "grain",    label: "Grain"   },
              { value: "flat",     label: "Flat"    },
            ]}
          />
        </TweakSection>

        <TweakSection title="Density">
          <TweakRadio
            value={tweaks.density}
            onChange={v => setTweak("density", v)}
            options={[
              { value: "tight",    label: "Tight"   },
              { value: "default",  label: "Default" },
              { value: "spacious", label: "Spacious"},
            ]}
          />
        </TweakSection>

        <TweakSection title="Headline" subtitle="Use | to mark the italic accent word(s)">
          <TweakText value={tweaks.headline} onChange={v => setTweak("headline", v)} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
