// ============================================================
// autoclient.io — shared primitives, chrome & router
// ============================================================
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- Tweaks context (shared across page scripts) ---------- */
const TweakCtx = React.createContext({ heroBg: "3D scene" });
window.TweakCtx = TweakCtx;

/* ---------- Icon (Lucide) ---------- */
function Icon({ name, size = 20, color, style, className }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const i = document.createElement("i");
      i.setAttribute("data-lucide", name);
      ref.current.appendChild(i);
      window.lucide.createIcons({ attrs: { width: size, height: size, "stroke-width": 1.75 } });
    }
  }, [name, size]);
  return <span ref={ref} className={className} style={Object.assign({ display: "inline-flex", color }, style || {})} />;
}

/* ---------- Logo / symbol ---------- */
function Logo({ negative = true, height = 28 }) {
  const src = negative ? "assets/autoclient-logo-negative.png" : "assets/autoclient-logo.png";
  return <img src={src} alt="autoclient" style={{ height, width: "auto", display: "block" }} />;
}
function SymbolMark({ size = 34 }) {
  return <img src="assets/autoclient-symbol.png" alt="" style={{ height: size, width: "auto", display: "block" }} />;
}

/* ---------- Button ---------- */
function Button({ variant = "primary", size, children, icon, iconLeft, onClick, href, style }) {
  const cls = `btn btn-${variant}${size === "sm" ? " btn-sm" : ""}${size === "lg" ? " btn-lg" : ""}`;
  const inner = (<>{iconLeft && <Icon name={iconLeft} size={16} />}{children}{icon && <Icon name={icon} size={16} />}</>);
  if (href) return <a className={cls} href={href} onClick={onClick} style={style}>{inner}</a>;
  return <button className={cls} onClick={onClick} style={style}>{inner}</button>;
}

/* ---------- Aura ---------- */
function Aura({ color = "#8784FD", size = 480, top, left, right, bottom, opacity = 0.5, drift }) {
  const cls = "aura" + (drift === 1 ? " aura-drift1" : drift === 2 ? " aura-drift2" : "");
  return <div className={cls} style={{ width: size, height: size, background: color, top, left, right, bottom, opacity }} />;
}

/* ---------- Overline (with optional leading tick) ---------- */
function Overline({ children, grad, dot, style }) {
  return (
    <span className={grad ? "overline-grad" : "overline"} style={Object.assign({ display: "inline-flex", alignItems: "center", gap: 10 }, style || {})}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--auto-coral)" }} />}
      {children}
    </span>
  );
}

/* ---------- reveal-on-scroll ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          const d = e.target.getAttribute("data-delay");
          if (d) e.target.style.transitionDelay = d + "ms";
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- count-up number ---------- */
function CountUp({ to, suffix = "", prefix = "", decimals = 0, dur = 1400, style, className }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const done = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting && !done.current) {
          done.current = true;
          const start = performance.now();
          const tick = (now) => {
            const p = Math.min(1, (now - start) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(to * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, dur]);
  return <span ref={ref} className={className} style={style}>{prefix}{val.toFixed(decimals)}{suffix}</span>;
}

/* ---------- Nav data ---------- */
function go(hash) { window.location.hash = hash; }

const SERVICE_GROUPS = [
  { heading: "Advertising", links: [
    { label: "Google Ads", hash: "#/services/google-ads", icon: "mouse-pointer-click" },
    { label: "Meta Ads", hash: "#/services/meta-ads", icon: "thumbs-up" },
    { label: "Paid Social", hash: "#/services/paid-social", icon: "megaphone" },
    { label: "TikTok Ads", hash: "#/services/tiktok-ads", icon: "music" },
    { label: "YouTube Ads", hash: "#/services/youtube-ads", icon: "play" },
    { label: "Instagram Ads", hash: "#/services/instagram-ads", icon: "camera" },
    { label: "Snapchat Ads", hash: "#/services/snapchat-ads", icon: "ghost" },
    { label: "Streaming TV & Roku", hash: "#/services/streaming-tv-ads", icon: "tv" },
    { label: "Spotify Ads", hash: "#/services/spotify-ads", icon: "volume-2" },
  ]},
  { heading: "Growth & Automation", links: [
    { label: "SEO & Local SEO", hash: "#/services/seo", icon: "search" },
    { label: "Email & SMS Marketing", hash: "#/services/email-marketing", icon: "mail" },
    { label: "Lead Generation", hash: "#/services/lead-generation", icon: "magnet" },
    { label: "Automation & AI", hash: "#/services/automation", icon: "workflow" },
  ]},
];
const INDUSTRY_LINKS = [
  { label: "Law Firms", hash: "#/industries/law-firms", icon: "scale", d: "Sign more qualified cases" },
  { label: "Medical & Dental", hash: "#/industries/medical", icon: "stethoscope", d: "Fill your calendar" },
  { label: "Ecommerce", hash: "#/industries/ecommerce", icon: "shopping-cart", d: "Scale profitable revenue" },
  { label: "Local Business", hash: "#/industries/local-business", icon: "store", d: "Own your neighborhood" },
];
const WORK_LINKS = [
  { label: "Projects", hash: "#/works", icon: "layout-grid", d: "Selected work across verticals" },
  { label: "Case Studies", hash: "#/case-studies", icon: "trending-up", d: "Results we can prove" },
];
// flat list for mobile + legacy references
const SERVICE_LINKS = SERVICE_GROUPS.flatMap((g) => g.links);

/* ---------- Nav dropdown link item ---------- */
function NavMenuItem({ s }) {
  return (
    <a href={s.hash} style={{ display: "flex", gap: 13, padding: "11px 13px", borderRadius: 12, transition: "background .15s", alignItems: s.d ? "flex-start" : "center" }}
      onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(135,132,253,0.12)")}
      onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
      <span style={{ width: 34, height: 34, borderRadius: 9, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(135,132,253,0.14)", color: "var(--auto-violet)", marginTop: s.d ? 1 : 0 }}>
        <Icon name={s.icon} size={17} />
      </span>
      <span>
        <span style={{ display: "block", fontSize: 14.5, fontWeight: 600 }}>{s.label}</span>
        {s.d && <span style={{ display: "block", fontSize: 12.5, color: "var(--fg-on-dark-3)", marginTop: 2 }}>{s.d}</span>}
      </span>
    </a>
  );
}

/* ---------- generic hover/click dropdown ---------- */
function NavDropdown({ label, width = 320, align = "center", children }) {
  const [open, setOpen] = useState(false);
  const timer = useRef(null);
  const openM = () => { clearTimeout(timer.current); setOpen(true); };
  const closeM = () => { timer.current = setTimeout(() => setOpen(false), 140); };
  const left = align === "center" ? "50%" : align === "left" ? 0 : "auto";
  const right = align === "right" ? 0 : "auto";
  const tx = align === "center" ? "translateX(-50%)" : "none";
  return (
    <div style={{ position: "relative" }} onMouseEnter={openM} onMouseLeave={closeM}>
      <button onClick={() => setOpen((o) => !o)} style={{
        display: "flex", alignItems: "center", gap: 6, background: "none", border: 0, cursor: "pointer",
        fontSize: 14.5, fontWeight: 500, color: open ? "var(--fg-on-dark-1)" : "var(--fg-on-dark-2)",
        padding: "9px 16px", transition: "color .15s",
      }}>
        {label}
        <Icon name="chevron-down" size={15} style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform .2s" }} />
      </button>
      <div style={{
        position: "absolute", top: "calc(100% + 10px)", left, right,
        transform: `${tx} translateY(${open ? 0 : 8}px)`, width,
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none",
        transition: "opacity .2s, transform .2s", zIndex: 100,
      }}>
        <div className="card" style={{ padding: 12, boxShadow: "var(--shadow-glow)", background: "rgba(46,42,43,0.96)", backdropFilter: "blur(20px)" }}>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ---------- Nav ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [mobile, setMobile] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    const onHash = () => setMobile(false);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const plain = (label, hash) => (
    <a key={label} href={hash} style={{ fontSize: 14.5, color: "var(--fg-on-dark-2)", fontWeight: 500, padding: "9px 16px", transition: "color .15s" }}
      onMouseEnter={(e) => (e.target.style.color = "var(--fg-on-dark-1)")}
      onMouseLeave={(e) => (e.target.style.color = "var(--fg-on-dark-2)")}>{label}</a>
  );

  return (
    <header style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 90,
      backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)",
      background: (scrolled || mobile) ? "rgba(26,23,24,0.82)" : "rgba(35,31,32,0)",
      borderBottom: `1px solid ${(scrolled || mobile) ? "var(--line-on-dark)" : "transparent"}`,
      transition: "background .3s, border-color .3s",
    }}>
      <div className="wrap-wide" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 74 }}>
        <a href="#/" aria-label="autoclient home"><Logo height={26} /></a>

        <nav style={{ display: "flex", gap: 2, alignItems: "center" }} className="nav-desktop">
          {plain("About", "#/about")}
          <NavDropdown label="Services" width={560} align="center">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              {SERVICE_GROUPS.map((g) => (
                <div key={g.heading}>
                  <div className="overline" style={{ padding: "4px 13px 8px", fontSize: 11 }}>{g.heading}</div>
                  {g.links.map((s) => <NavMenuItem key={s.label} s={s} />)}
                </div>
              ))}
            </div>
          </NavDropdown>
          <NavDropdown label="Industries" width={300} align="center">
            {INDUSTRY_LINKS.map((s) => <NavMenuItem key={s.label} s={s} />)}
          </NavDropdown>
          {/* Pricing hidden for now — restore: {plain("Pricing", "#/pricing")} */}
          <NavDropdown label="Work" width={300} align="center">
            {WORK_LINKS.map((s) => <NavMenuItem key={s.label} s={s} />)}
          </NavDropdown>
          {plain("Contact", "#/contact")}
        </nav>

        <div style={{ display: "flex", gap: 10, alignItems: "center" }} className="nav-cta">
          <Button variant="primary" size="sm" icon="arrow-right" href="#/contact">Start a Project</Button>
        </div>

        <button className="nav-burger" onClick={() => setMobile((m) => !m)} style={{ display: "none", background: "none", border: 0, color: "#fff", cursor: "pointer", padding: 8 }}>
          <Icon name={mobile ? "x" : "menu"} size={24} />
        </button>
      </div>

      {/* mobile menu */}
      <div className="nav-mobile" style={{ display: "none", overflow: "auto", maxHeight: mobile ? "78vh" : 0, transition: "max-height .35s var(--ease-out)" }}>
        <div className="wrap" style={{ padding: "8px 22px 26px", display: "flex", flexDirection: "column", gap: 2 }}>
          <a href="#/about" style={mobileLink}>About</a>
          {SERVICE_GROUPS.map((g) => (
            <React.Fragment key={g.heading}>
              <div className="overline" style={{ padding: "16px 4px 6px", fontSize: 11 }}>{g.heading}</div>
              {g.links.map((s) => <a key={s.label} href={s.hash} style={mobileLink}>{s.label}</a>)}
            </React.Fragment>
          ))}
          <div className="overline" style={{ padding: "16px 4px 6px", fontSize: 11 }}>Industries</div>
          {INDUSTRY_LINKS.map((s) => <a key={s.label} href={s.hash} style={mobileLink}>{s.label}</a>)}
          <div className="overline" style={{ padding: "16px 4px 6px", fontSize: 11 }}>More</div>
          {/* Pricing hidden for now — restore: <a href="#/pricing" style={mobileLink}>Pricing</a> */}
          <a href="#/works" style={mobileLink}>Projects</a>
          <a href="#/case-studies" style={mobileLink}>Case Studies</a>
          <a href="#/contact" style={mobileLink}>Contact</a>
          <Button variant="primary" icon="arrow-right" href="#/contact" style={{ marginTop: 18 }}>Start a Project</Button>
        </div>
      </div>
    </header>
  );
}
const mobileLink = { padding: "12px 4px", fontSize: 16, borderBottom: "1px solid var(--line-on-dark)", color: "var(--fg-on-dark-1)" };

/* ---------- FAQ accordion ---------- */
function FAQ({ items, light }) {
  const [open, setOpen] = useState(0);
  return (
    <div style={{ borderBottom: `1px solid ${light ? "var(--line-on-light)" : "var(--line-on-dark)"}` }}>
      {items.map((it, i) => {
        const isOpen = open === i;
        return (
          <div className="faq-item" key={i} style={{ borderColor: light ? "var(--line-on-light)" : "var(--line-on-dark)" }}>
            <button className="faq-q" onClick={() => setOpen(isOpen ? -1 : i)} style={{ color: light ? "var(--fg-on-light-1)" : "var(--fg-on-dark-1)" }}>
              {it.q}
              <span style={{ flexShrink: 0, width: 34, height: 34, borderRadius: 99, display: "flex", alignItems: "center", justifyContent: "center", border: `1px solid ${light ? "var(--line-on-light)" : "var(--line-on-dark)"}`, transition: "transform .3s, background .3s", transform: isOpen ? "rotate(45deg)" : "none", background: isOpen ? "var(--auto-gradient)" : "transparent", color: isOpen ? "#fff" : "inherit" }}>
                <Icon name="plus" size={17} />
              </span>
            </button>
            <div className="faq-a" style={{ maxHeight: isOpen ? 320 : 0, opacity: isOpen ? 1 : 0 }} className={`faq-a${isOpen ? " open" : ""}`}>
              <div className="faq-a-inner" style={{ color: light ? "var(--fg-on-light-2)" : "var(--fg-on-dark-2)" }}>{it.a}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ---------- Big CTA banner (single, consolidated CTA) ---------- */
function CtaBanner({ title, sub, primary = "Book a Call", primaryHref = "#/contact", small }) {
  return (
    <section className="sec" style={{ paddingTop: small ? 40 : 80 }}>
      <div className="wrap">
        <div className="reveal" style={{ position: "relative", overflow: "hidden", borderRadius: "var(--radius-xl)", border: "1px solid var(--line-on-dark)", background: "var(--bg-elevated)", padding: "84px 56px", textAlign: "center" }}>
          <Aura color="#8784FD" size={460} top={-200} left={-60} opacity={0.42} drift={1} />
          <Aura color="#FF6666" size={420} bottom={-220} right={-40} opacity={0.36} drift={2} />
          <div style={{ position: "relative", zIndex: 1 }}>
            <div style={{ display: "flex", justifyContent: "center", marginBottom: 26 }}><SymbolMark size={40} /></div>
            <h2 style={{ fontWeight: 300, fontSize: "clamp(2.4rem,4.6vw,4rem)", lineHeight: 1.06, letterSpacing: "-0.025em", margin: "0 auto", maxWidth: 760 }}>{title}</h2>
            {sub && <p style={{ fontSize: 18, lineHeight: 1.6, color: "var(--fg-on-dark-2)", maxWidth: 520, margin: "22px auto 0" }}>{sub}</p>}
            <div style={{ display: "flex", gap: 14, justifyContent: "center", marginTop: 38, flexWrap: "wrap" }}>
              <Button variant="primary" size="lg" icon="arrow-right" href={primaryHref}>{primary}</Button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const cols = [
    ["Services", [["Google Ads", "#/services/google-ads"], ["Paid Social", "#/services/paid-social"], ["SEO & Local SEO", "#/services/seo"], ["Email & SMS", "#/services/email-marketing"], ["Lead Generation", "#/services/lead-generation"], ["Automation & AI", "#/services/automation"]]],
    ["Industries", [["Law Firms", "#/industries/law-firms"], ["Medical & Dental", "#/industries/medical"], ["Ecommerce", "#/industries/ecommerce"], ["Local Business", "#/industries/local-business"]]],
    ["Company", [["About", "#/about"], ["Projects", "#/works"], ["Case Studies", "#/case-studies"], ["Contact", "#/contact"]]],
    ["Connect", [["LinkedIn", "https://www.linkedin.com/company/autoclient/"], ["info@autoclient.io", "mailto:info@autoclient.io"], ["(512) 817-2473", "tel:+15128172473"]]],
  ];
  return (
    <footer style={{ borderTop: "1px solid var(--line-on-dark)", padding: "72px 0 44px", position: "relative", overflow: "hidden" }}>
      <Aura color="#8784FD" size={500} bottom={-340} left={"30%"} opacity={0.16} />
      <div className="wrap-wide" style={{ position: "relative", display: "flex", justifyContent: "space-between", gap: 56, flexWrap: "wrap" }}>
        <div style={{ maxWidth: 320 }}>
          <Logo height={26} />
          <p style={{ fontSize: 14, lineHeight: 1.65, color: "var(--fg-on-dark-3)", marginTop: 20, maxWidth: 280 }}>
            Intelligent marketing &amp; AI solutions. We turn ad spend into a stream of clients for service companies, ecommerce, and local businesses.
          </p>
          <div style={{ marginTop: 22, fontSize: 13.5, color: "var(--fg-on-dark-3)", lineHeight: 1.7 }}>
            Austin, TX<br />(512) 817-2473
          </div>
        </div>
        <div style={{ display: "flex", gap: 64, flexWrap: "wrap" }}>
          {cols.map(([h, items]) => (
            <div key={h}>
              <div className="overline" style={{ marginBottom: 18 }}>{h}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {items.map(([t, href]) => <a key={t} href={href} target={href.startsWith("http") ? "_blank" : undefined} rel={href.startsWith("http") ? "noopener noreferrer" : undefined} style={{ fontSize: 14, color: "var(--fg-on-dark-2)", transition: "color .15s" }}
                  onMouseEnter={(e) => (e.target.style.color = "var(--fg-on-dark-1)")} onMouseLeave={(e) => (e.target.style.color = "var(--fg-on-dark-2)")}>{t}</a>)}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="wrap-wide" style={{ marginTop: 56, paddingTop: 26, borderTop: "1px solid var(--line-on-dark)", display: "flex", justifyContent: "space-between", color: "var(--fg-on-dark-3)", fontSize: 12.5, flexWrap: "wrap", gap: 12 }}>
        <span>© 2026 autoclient.io · all rights reserved</span>
        <span style={{ display: "flex", gap: 22 }}><a href="#/privacy" style={{ color: "inherit" }}>Privacy</a><a href="#/terms" style={{ color: "inherit" }}>Terms</a><span className="gt" style={{ fontWeight: 600 }}>autoclient</span></span>
      </div>
    </footer>
  );
}

Object.assign(window, { Icon, Logo, SymbolMark, Button, Aura, Overline, useReveal, CountUp, Nav, FAQ, CtaBanner, Footer, go, SERVICE_LINKS });
