// Shefa; — Shared scaffolding: logo, header, footer, nodes bg, reveal, sticky CTA.

// ---------- RESPONSIVE HOOK ----------
function useIsMobile(bp = 768) {
  const [is, setIs] = React.useState(() => typeof window !== "undefined" && window.innerWidth < bp);
  React.useEffect(() => {
    const fn = () => setIs(window.innerWidth < bp);
    window.addEventListener("resize", fn, { passive: true });
    return () => window.removeEventListener("resize", fn);
  }, [bp]);
  return is;
}

function useShefaTheme() {
  const read = () => {
    const api = window.ShefaTheme;
    const mode = api ? api.get() : (document.documentElement.dataset.themeMode || "system");
    const resolved = document.documentElement.dataset.theme || (api ? api.resolve(mode) : "dark");
    return { mode, resolved };
  };
  const [theme, setThemeState] = React.useState(read);

  React.useEffect(() => {
    const onChange = () => setThemeState(read());
    window.addEventListener("shefa-theme-change", onChange);
    return () => window.removeEventListener("shefa-theme-change", onChange);
  }, []);

  const setTheme = React.useCallback((mode) => {
    if (window.ShefaTheme) window.ShefaTheme.set(mode);
  }, []);

  return { ...theme, setTheme };
}

// ---------- LOGO ----------
function ShefaMark({ size = 28 }) {
  return (
    <img
      src="/assets/symbol-mark-purple.png"
      alt=""
      aria-hidden="true"
      style={{ display: "block", width: size, height: size, objectFit: "contain" }}
    />
  );
}

function ShefaWordmark({ size = 28, variant }) {
  const theme = typeof document !== "undefined" ? document.documentElement.dataset.theme : "dark";
  const resolvedVariant = variant || (theme === "light" ? "light" : "dark");
  return (
    <img
      src={resolvedVariant === "light" ? "/assets/logo-horizontal-light.png" : "/assets/logo-horizontal-dark.png"}
      alt="Shefa; Creative Agency"
      style={{ display: "block", width: "auto", height: Math.round(size * 1.45), objectFit: "contain" }}
    />
  );
}

function ThemeToggle({ compact = false }) {
  const { resolved, setTheme } = useShefaTheme();
  const next = resolved === "light" ? "dark" : "light";
  return (
    <button
      type="button"
      onClick={() => setTheme(next)}
      aria-label={`Switch to ${next} mode`}
      title={`Switch to ${next} mode`}
      style={{
        width: compact ? 38 : 42,
        height: compact ? 38 : 40,
        borderRadius: 10,
        border: "1px solid var(--line)",
        background: "var(--surface-glass)",
        color: "var(--text)",
        cursor: "pointer",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        transition: "all 160ms var(--ease-std)",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent-soft)"; e.currentTarget.style.color = "var(--accent)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.color = "var(--text)"; }}
    >
      {resolved === "light" ? (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <path d="M12 3a6 6 0 0 0 9 7.4A8.5 8.5 0 1 1 12 3z"/>
        </svg>
      ) : (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
        </svg>
      )}
    </button>
  );
}

// ---------- ANIMATED NODES BACKGROUND ----------
function NodesBg({ density = 18, opacity = 0.55, color = "#8A5CFF" }) {
  const nodes = React.useMemo(() => {
    let s = 7;
    const rand = () => { s = (s * 1103515245 + 12345) % 2147483648; return s / 2147483648; };
    return Array.from({ length: density }, () => ({
      x: rand() * 100, y: rand() * 100,
      r: 1 + rand() * 2.5, delay: rand() * 4,
    }));
  }, [density]);

  const lines = React.useMemo(() => {
    const out = [];
    for (let i = 0; i < nodes.length; i++) {
      for (let j = i + 1; j < nodes.length; j++) {
        const dx = nodes[i].x - nodes[j].x, dy = nodes[i].y - nodes[j].y;
        const d = Math.sqrt(dx * dx + dy * dy);
        if (d < 22) out.push({ a: i, b: j, d });
      }
    }
    return out;
  }, [nodes]);

  return (
    <div className="nodes-bg" aria-hidden="true" style={{
      position: "absolute", inset: 0, pointerEvents: "none",
      opacity, zIndex: 0,
    }}>
      <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none" style={{ display: "block" }}>
        {lines.map((l, i) => (
          <line key={i}
            x1={nodes[l.a].x} y1={nodes[l.a].y}
            x2={nodes[l.b].x} y2={nodes[l.b].y}
            stroke={color} strokeWidth="0.08" vectorEffect="non-scaling-stroke"
            style={{ animation: `shefaLinePulse 6s ease-in-out infinite`, animationDelay: `${(i % 5) * 0.6}s` }}
          />
        ))}
        {nodes.map((n, i) => (
          <circle key={i} cx={n.x} cy={n.y} r={n.r * 0.18}
            fill={color}
            style={{
              transformOrigin: "center",
              transformBox: "fill-box",
              animation: "shefaPulseDot 5s ease-in-out infinite",
              animationDelay: `${n.delay}s`,
            }}
          />
        ))}
      </svg>
    </div>
  );
}

// ---------- HEADER ----------
function HeaderDark() {
  const links = [
    { label: "What's included", href: "#included" },
    { label: "The 14 days",     href: "#process" },
    { label: "Automation",      href: "#automation" },
    { label: "Work",            href: "#work" },
    { label: "Pricing",         href: "#pricing" },
  ];
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const isMobile = useIsMobile();
  useShefaTheme();

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

  // Close menu on resize to desktop
  React.useEffect(() => { if (!isMobile) setMenuOpen(false); }, [isMobile]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <header style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
      background: scrolled || menuOpen ? "var(--header-glass)" : "transparent",
      backdropFilter: scrolled || menuOpen ? "blur(16px)" : "none",
      WebkitBackdropFilter: scrolled || menuOpen ? "blur(16px)" : "none",
      borderBottom: scrolled || menuOpen ? "1px solid var(--line)" : "1px solid transparent",
      transition: "background 240ms var(--ease-std), border 240ms",
    }}>
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        padding: isMobile ? "16px 20px" : "18px 32px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16,
      }}>
        <a href="#home" style={{ textDecoration: "none" }} onClick={closeMenu}>
          <ShefaWordmark size={isMobile ? 24 : 28} />
        </a>

        {isMobile ? (
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <ThemeToggle compact />
            <button
              onClick={() => setMenuOpen(o => !o)}
              aria-label={menuOpen ? "Close menu" : "Open menu"}
              style={{
                background: "transparent",
                border: "1px solid var(--line-strong)",
                borderRadius: 8, padding: "8px 10px",
                cursor: "pointer", color: "var(--text-muted)",
                display: "flex", alignItems: "center",
                lineHeight: 0,
              }}
            >
              {menuOpen ? (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <path d="M18 6L6 18M6 6l12 12"/>
                </svg>
              ) : (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <path d="M3 12h18M3 6h18M3 18h18"/>
                </svg>
              )}
            </button>
          </div>
        ) : (
          <nav style={{ display: "flex", gap: 28, alignItems: "center" }}>
            {links.map((l) => (
              <a key={l.label} href={l.href}
                 style={{ color: "var(--text-muted)", fontSize: 13.5, fontWeight: 500, textDecoration: "none", transition: "color 160ms" }}
                 onMouseEnter={(e) => e.currentTarget.style.color = "var(--text-strong)"}
                 onMouseLeave={(e) => e.currentTarget.style.color = "var(--text-muted)"}>
                {l.label}
              </a>
            ))}
            <ThemeToggle />
            <a href="#book" className="accent-grad" style={{
              background: "linear-gradient(135deg,#6C3BFF,#8A5CFF)",
              color: "#fff", textDecoration: "none",
              padding: "10px 18px", borderRadius: 10,
              fontWeight: 600, fontSize: 13,
              transition: "all 240ms var(--ease-std)",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.filter = "brightness(1.08)"; e.currentTarget.style.boxShadow = "0 0 24px rgba(108,59,255,0.45)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.filter = "brightness(1)"; e.currentTarget.style.boxShadow = "none"; }}>
              Plan your launch
            </a>
          </nav>
        )}
      </div>

      {/* Mobile dropdown */}
      {isMobile && menuOpen && (
        <div style={{
          padding: "8px 20px 28px",
          borderTop: "1px solid var(--line)",
        }}>
          {links.map((l) => (
            <a key={l.label} href={l.href} onClick={closeMenu} style={{
              display: "block",
              padding: "14px 0",
              borderBottom: "1px solid var(--line)",
              color: "var(--text)", textDecoration: "none",
              fontSize: 16, fontWeight: 500,
            }}>
              {l.label}
            </a>
          ))}
          <a href="#book" className="accent-grad" onClick={closeMenu} style={{
            display: "block", marginTop: 20, textAlign: "center",
            background: "linear-gradient(135deg,#6C3BFF,#8A5CFF)",
            color: "#fff", textDecoration: "none",
            padding: "14px 24px", borderRadius: 10,
            fontWeight: 600, fontSize: 15,
          }}>
            Plan your launch →
          </a>
        </div>
      )}
    </header>
  );
}

function HeaderLight({ activePath }) {
  const links = [
    { label: "Work", href: "./work.html" },
    { label: "Writing", href: "./blog.html" },
    { label: "Pricing", href: "./index.html#pricing" },
  ];
  useShefaTheme();
  return (
    <header style={{ background: "var(--header-glass)", borderBottom: "1px solid var(--line)", position: "sticky", top: 0, zIndex: 50, backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "16px 32px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
        <a href="./index.html" style={{ textDecoration: "none" }} aria-label="Shefa; home">
          <ShefaWordmark size={26} />
        </a>
        <nav style={{ display: "flex", alignItems: "center", gap: 24 }} aria-label="Primary navigation">
          {links.map((link) => (
            <a key={link.label} href={link.href} style={{ color: activePath === link.label ? "var(--accent)" : "var(--text-muted)", textDecoration: "none", fontSize: 14, fontWeight: 600 }}>
              {link.label}
            </a>
          ))}
          <ThemeToggle />
          <a href="./index.html#book" style={{ background: "linear-gradient(135deg,#6C3BFF,#8A5CFF)", color: "#fff", textDecoration: "none", padding: "10px 16px", borderRadius: 10, fontSize: 13, fontWeight: 700 }}>
            Plan your launch
          </a>
        </nav>
      </div>
    </header>
  );
}

// ---------- FOOTER ----------
function FooterDark() {
  const isMobile = useIsMobile();
  const cols = [
    { h: "Product", links: [
      { label: "What's included", href: "#included" },
      { label: "The 14 days",     href: "#process" },
      { label: "Pricing",         href: "#pricing" },
      { label: "FAQ",             href: "#faq" },
    ]},
    { h: "Studio", links: [
      { label: "Work",            href: "./work.html" },
      { label: "Writing",         href: "./blog.html" },
      { label: "About",           href: "#included" },
    ]},
    { h: "Contact", links: [
      { label: "hello@shefa.agency", href: "mailto:hello@shefa.agency" },
      { label: "Book a kick-off",    href: "#book" },
      { label: "Newsletter",         href: "./blog.html" },
    ]},
  ];
  return (
    <footer style={{ background: "var(--page)", borderTop: "1px solid var(--line)", padding: isMobile ? "48px 20px 24px" : "72px 32px 28px" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr 1fr" : "1.4fr 1fr 1fr 1fr",
          gap: isMobile ? 32 : 48,
          marginBottom: isMobile ? 40 : 56,
        }}>
          <div style={{ gridColumn: isMobile ? "1 / -1" : "auto" }}>
            <ShefaWordmark size={28} />
            <p style={{ color: "var(--text-faint)", fontSize: 14, lineHeight: 1.6, marginTop: 18, maxWidth: 320 }}>
              A connection of ideas, people and technology. Built to automate. Designed to scale.
            </p>
          </div>
          {cols.map((c) => (
            <div key={c.h}>
              <div className="accent-color" style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "#A78BFA", fontWeight: 700, marginBottom: 16 }}>
                {c.h}
              </div>
              <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 10 }}>
                {c.links.map((l) => (
                  <li key={l.label}>
                    <a href={l.href}
                      style={{ color: "var(--text)", textDecoration: "none", fontSize: 14, transition: "opacity 160ms" }}
                      onMouseEnter={(e) => e.currentTarget.style.opacity = "0.7"}
                      onMouseLeave={(e) => e.currentTarget.style.opacity = "1"}>
                      {l.label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          paddingTop: 28, borderTop: "1px solid var(--line)",
          fontSize: 12, color: "var(--text-faint)", flexWrap: "wrap", gap: 16,
        }}>
          <div>© 2026 Shefa<span className="accent-color" style={{ color: "#A78BFA" }}>;</span> Creative Agency. All rights reserved.</div>
          <div style={{ display: "flex", gap: 18 }}>
            <a href="mailto:hello@shefa.agency" style={{ color: "var(--text-muted)", textDecoration: "none" }}>Privacy</a>
            <a href="mailto:hello@shefa.agency" style={{ color: "var(--text-muted)", textDecoration: "none" }}>Terms</a>
            <a href="./index.html" style={{ color: "var(--text-muted)", textDecoration: "none" }}>shefa.agency</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function FooterLight() {
  return (
    <footer style={{ background: "var(--page-soft)", borderTop: "1px solid var(--line)", padding: "48px 32px 28px" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24, flexWrap: "wrap" }}>
        <div>
          <ShefaWordmark size={24} />
          <p style={{ color: "var(--text-faint)", fontSize: 13, margin: "12px 0 0" }}>Built to automate. Designed to scale.</p>
        </div>
        <nav style={{ display: "flex", gap: 18, flexWrap: "wrap" }} aria-label="Footer navigation">
          <a href="./index.html" style={{ color: "var(--text-muted)", textDecoration: "none", fontSize: 14 }}>Home</a>
          <a href="./work.html" style={{ color: "var(--text-muted)", textDecoration: "none", fontSize: 14 }}>Work</a>
          <a href="./blog.html" style={{ color: "var(--text-muted)", textDecoration: "none", fontSize: 14 }}>Writing</a>
          <a href="./index.html#book" style={{ color: "#6C3BFF", textDecoration: "none", fontSize: 14, fontWeight: 700 }}>Plan your launch</a>
        </nav>
      </div>
    </footer>
  );
}

// ---------- STICKY CTA BAR ----------
function StickyCta({ visible }) {
  const isMobile = useIsMobile();
  return (
    <div style={{
      position: "fixed",
      left: "50%",
      bottom: visible ? 20 : -100,
      transform: "translateX(-50%)",
      transition: "bottom 380ms var(--ease-std)",
      zIndex: 40,
      background: "var(--surface-glass)",
      backdropFilter: "blur(18px)",
      WebkitBackdropFilter: "blur(18px)",
      border: "1px solid rgba(138,92,255,0.34)",
      borderRadius: 999,
      padding: isMobile ? "10px 10px 10px 16px" : "10px 12px 10px 22px",
      display: "flex", alignItems: "center", gap: isMobile ? 10 : 18,
      boxShadow: "var(--shadow-card), 0 0 28px rgba(108,59,255,0.22)",
      maxWidth: "calc(100vw - 32px)",
    }}>
      <span className="accent-dot" style={{ width: 8, height: 8, borderRadius: 999, background: "#8A5CFF", boxShadow: "0 0 10px rgba(138,92,255,0.9)", flex: "none" }}></span>
      <span style={{ fontSize: isMobile ? 12 : 13.5, color: "var(--text)", whiteSpace: "nowrap" }}>
        <b style={{ color: "var(--text-strong)" }}>2 kick-off Mondays</b>{!isMobile && " open · June 2026"}
      </span>
      <a href="#book" className="accent-grad" style={{
        background: "linear-gradient(135deg,#6C3BFF,#8A5CFF)",
        color: "#fff", textDecoration: "none",
        padding: isMobile ? "9px 14px" : "10px 18px", borderRadius: 999,
        fontWeight: 600, fontSize: isMobile ? 12 : 13, whiteSpace: "nowrap",
        transition: "all 200ms",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.filter = "brightness(1.08)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.filter = "brightness(1)"; }}>
        {isMobile ? "Book now →" : "Plan your launch →"}
      </a>
    </div>
  );
}

// ---------- REVEAL ----------
function useReveal() {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); obs.disconnect(); } }),
      { threshold: 0.12, rootMargin: "0px 0px -60px 0px" }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, seen];
}

function Reveal({ children, delay = 0, y = 24, as = "div", style = {}, ...rest }) {
  const [ref, seen] = useReveal();
  const Tag = as;
  return (
    <Tag ref={ref} style={{
      transform: seen ? "translateY(0)" : `translateY(${y}px)`,
      opacity: seen ? 1 : 0,
      transition: `transform 700ms cubic-bezier(0.22, 1, 0.36, 1) ${delay}ms, opacity 700ms cubic-bezier(0.22, 1, 0.36, 1) ${delay}ms`,
      ...style,
    }} {...rest}>{children}</Tag>
  );
}

// ---------- SHARED EYEBROW ----------
function Eyebrow({ children }) {
  return (
    <div className="accent-color" style={{
      fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase",
      color: "#A78BFA", fontWeight: 700, marginBottom: 14,
      display: "inline-flex", alignItems: "center", gap: 10,
    }}>
      <span className="accent-dot" style={{ width: 6, height: 6, borderRadius: 999, background: "#8A5CFF" }}></span>
      {children}
    </div>
  );
}

Object.assign(window, {
  useIsMobile, useShefaTheme,
  ShefaMark, ShefaWordmark, NodesBg,
  ThemeToggle, HeaderDark, HeaderLight, FooterDark, FooterLight, StickyCta,
  useReveal, Reveal, Eyebrow,
});
