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

/* ---------- Reveal-on-scroll hook ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -60px 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ---------- Nav ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [clicks, setClicks] = useState(0);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const onLogoClick = (e) => {
    const n = clicks + 1;
    setClicks(n);
    if (n >= 5) {
      e.preventDefault();
      document.body.classList.toggle("rainbow");
      setClicks(0);
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    const p = window.location.pathname;
    if (!p.endsWith("preise.html") && !p.endsWith("kontakt.html")) {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  return (
    <header
      style={{
        position: "fixed",
        top: 0, left: 0, right: 0,
        zIndex: 100,
        padding: scrolled ? "10px 0" : "18px 0",
        background: scrolled ? "rgba(255,255,255,0.78)" : "transparent",
        backdropFilter: scrolled ? "saturate(180%) blur(20px)" : "none",
        WebkitBackdropFilter: scrolled ? "saturate(180%) blur(20px)" : "none",
        borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
        transition: "all .35s cubic-bezier(.22,.61,.36,1)",
      }}
    >
      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <a href="index.html" onClick={onLogoClick} style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Logo />
        </a>
        <nav style={{ display: "flex", alignItems: "center", gap: 6 }} className="nav-links">
          <NavLink href={navHref("#leistungen")}>Leistungen</NavLink>
          <NavLink href={navHref("#problem")}>Problem-Finder</NavLink>
          <NavLink href={navHref("#ablauf")}>So geht's</NavLink>
          <NavLink href="preise.html">Preise</NavLink>
          <NavLink href={navHref("#faq")}>FAQ</NavLink>
          <NavLink href="kontakt.html">Kontakt</NavLink>
        </nav>
        <a href="kontakt.html" className="btn btn-primary" style={{ padding: "10px 18px", fontSize: 14 }}>
          Anfragen
        </a>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .nav-links { display: none !important; }
        }
      `}</style>
    </header>
  );
}

function navHref(anchor) {
  if (typeof window === "undefined") return anchor;
  const p = window.location.pathname;
  if (p.endsWith("preise.html") || p.endsWith("kontakt.html")) {
    return "index.html" + anchor;
  }
  return anchor;
}

function NavLink({ href, children }) {
  return (
    <a
      href={href}
      style={{
        padding: "8px 14px",
        fontSize: 14,
        color: "var(--muted)",
        borderRadius: 999,
        transition: "color .2s ease, background .2s ease",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.color = "var(--ink)"; e.currentTarget.style.background = "rgba(10,10,10,0.04)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.color = "var(--muted)"; e.currentTarget.style.background = "transparent"; }}
    >
      {children}
    </a>
  );
}

function Logo({ size = 22 }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontWeight: 600, fontSize: size, letterSpacing: "-0.03em" }}>
      <LogoMark size={size + 4} />
      <span>Paul</span>
      <span className="grad-text" style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontWeight: 400 }}>.tech</span>
    </span>
  );
}

function LogoMark({ size = 26 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <defs>
        <linearGradient id="lg" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
          <stop stopColor="#7c3aed" />
          <stop offset="1" stopColor="#ec4899" />
        </linearGradient>
      </defs>
      <rect x="2" y="2" width="28" height="28" rx="8" fill="url(#lg)" />
      <path d="M11.5 22V10h4.8c2.5 0 4.2 1.6 4.2 4s-1.7 4-4.2 4h-2.3" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ---------- Section header ---------- */
function SectionHeader({ eyebrow, title, sub, align = "left" }) {
  const ref = useReveal();
  return (
    <div ref={ref} className="reveal" style={{ textAlign: align, maxWidth: align === "center" ? 760 : "100%", margin: align === "center" ? "0 auto" : 0, marginBottom: 56 }}>
      {eyebrow && <span className="eyebrow grad-text" style={{ fontWeight: 600 }}>{eyebrow}</span>}
      <h2 className="section-title">{title}</h2>
      {sub && <p className="section-sub" style={{ margin: align === "center" ? "0 auto" : 0 }}>{sub}</p>}
    </div>
  );
}

/* ---------- Confetti utility ---------- */
function fireConfetti() {
  const colors = ["#7c3aed", "#a855f7", "#ec4899", "#fbbf24", "#34d399", "#60a5fa"];
  for (let i = 0; i < 80; i++) {
    const c = document.createElement("div");
    c.className = "confetti";
    c.style.left = Math.random() * 100 + "vw";
    c.style.background = colors[Math.floor(Math.random() * colors.length)];
    c.style.transform = `rotate(${Math.random() * 360}deg)`;
    document.body.appendChild(c);
    const dur = 1800 + Math.random() * 1800;
    c.animate(
      [
        { transform: c.style.transform, opacity: 1, top: "-20px" },
        { transform: `rotate(${Math.random() * 720 - 360}deg)`, opacity: 0, top: "100vh" },
      ],
      { duration: dur, easing: "cubic-bezier(.22,.61,.36,1)" }
    );
    setTimeout(() => c.remove(), dur);
  }
}

Object.assign(window, {
  useReveal, useState, useEffect, useRef, useCallback,
  Nav, NavLink, Logo, LogoMark, SectionHeader, fireConfetti, navHref,
});
