/* Shared header, footer, reveal-on-scroll, FAQ accordion */

const NAV = {
  platform: {
    eyebrow: "Platform",
    title: "One coordinated system for performance.",
    desc: "Six products sharing the same data layer, attribution, and audience graph — so every channel knows what the others are doing.",
    items: [
      { label: "Overview",           desc: "The complete platform",           href: "pages/platform-overview" },
      { label: "DSP",                desc: "Programmatic without black boxes", href: "pages/platform-dsp" },
      { label: "Measurement",        desc: "Know what's really working",       href: "pages/platform-measurement" },
      { label: "Reporting",          desc: "Reports that drive decisions",     href: "pages/platform-reporting" },
      { label: "Retargeting Cloud",  desc: "Bring back buyers",                href: "pages/platform-retargeting" },
      { label: "Affiliate Network",  desc: "Performance partnerships",         href: "pages/platform-affiliate" },
      { label: "How It Works",       desc: "From zero to scale",               href: "pages/platform-how-it-works" },
    ]
  },
  solutions: {
    eyebrow: "Solutions",
    title: "Built for the way performance teams operate.",
    desc: "Tailored playbooks by audience and by outcome — from growth-stage e-commerce to global agency portfolios.",
    items: [
      { label: "For Advertisers",        desc: "Grow your customer base",     href: "pages/solutions-advertisers" },
      { label: "For Publishers",         desc: "Maximize ad revenue",         href: "pages/solutions-publishers" },
      { label: "For Affiliates",         desc: "Monetize your traffic",       href: "pages/solutions-affiliates" },
      { label: "For Agencies",           desc: "Manage client campaigns",     href: "pages/solutions-agencies" },
      { label: "Customer Acquisition",   desc: "Scale new customer growth",   href: "pages/solutions-customer-acquisition" },
      { label: "Conversion Optimization",desc: "Improve campaign performance",href: "pages/solutions-conversion-optimization" },
      { label: "ROI Improvement",        desc: "Maximize return on ad spend", href: "pages/solutions-roi-improvement" },
      { label: "Retention",              desc: "Re-engage existing customers",href: "pages/solutions-retention" },
      { label: "Brand Awareness",        desc: "Build brand recognition",     href: "pages/solutions-brand-awareness" },
    ]
  },
  capabilities: {
    eyebrow: "Capabilities",
    title: "The technical surface area.",
    desc: "Granular capabilities powering campaigns across every major performance channel.",
    items: [
      { label: "Audience Targeting",        desc: "Precision segmentation",       href: "pages/capabilities-audience-targeting" },
      { label: "Offer Management",          desc: "Dynamic offer optimization",   href: "pages/capabilities-offer-management" },
      { label: "Brand Safety",              desc: "Protect your reputation",      href: "pages/capabilities-brand-safety" },
      { label: "Creative Optimization",     desc: "Dynamic creative testing",     href: "pages/capabilities-creative-optimization" },
      { label: "Answer Engine Optimization",desc: "AEO for modern search",        href: "pages/capabilities-answer-engine-optimization" },
      { label: "Programmatic",              desc: "Automated media buying",       href: "pages/capabilities-programmatic" },
      { label: "Fraud Prevention",          desc: "Advanced detection",           href: "pages/capabilities-fraud-prevention" },
      { label: "Measurement & Attribution", desc: "Multi-touch attribution",      href: "pages/capabilities-measurement-attribution" },
      { label: "Marketplace & E-Commerce",  desc: "Unified marketplace",          href: "pages/capabilities-marketplace" },
    ]
  }
};

function Caret() {
  return (
    <svg className="caret" viewBox="0 0 12 12" fill="none">
      <path d="M2.5 4.5L6 8l3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}
function Arrow({ className = "arr" }) {
  return (
    <svg className={className} width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function Mega({ data, open, basePath }) {
  const prefix = basePath || "";
  return (
    <div className={`mega ${open ? "open" : ""}`} role="region" aria-hidden={!open}>
      <div className="container">
        <div className="mega-grid">
          <div className="mega-header">
            <span className="eyebrow eyebrow-dot">{data.eyebrow}</span>
            <h3>{data.title}</h3>
            <p>{data.desc}</p>
          </div>
          <div className="mega-items">
            {data.items.map((it, i) => {
              const href = it.href.startsWith("#") ? it.href : (prefix + it.href);
              return (
                <a key={i} className="mega-item" href={href}>
                  <div className="mega-title">
                    <span>{it.label}</span>
                    <Arrow className="mega-arr" />
                  </div>
                  <div className="mega-desc">{it.desc}</div>
                </a>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function SearchOverlay({ open, onClose, basePath }) {
  const [query, setQuery] = React.useState("");
  const prefix = basePath || "";
  
  if (!open) return null;

  // Flatten NAV for search
  const allItems = [];
  Object.values(NAV).forEach(cat => {
    cat.items.forEach(it => {
      allItems.push({ ...it, category: cat.eyebrow });
    });
  });

  const filtered = query.length > 1 
    ? allItems.filter(it => 
        it.label.toLowerCase().includes(query.toLowerCase()) || 
        it.desc.toLowerCase().includes(query.toLowerCase())
      )
    : [];
  
  return (
    <div className="search-overlay" onClick={onClose}>
      <div className="search-modal" onClick={e => e.stopPropagation()}>
        <div className="search-input-wrap">
          <svg width="20" height="20" viewBox="0 0 14 14" fill="none" style={{opacity: 0.5}}>
            <circle cx="6" cy="6" r="4.25" stroke="currentColor" strokeWidth="1.5"/>
            <path d="M9 9l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
          <input 
            autoFocus 
            className="search-input" 
            placeholder="Search platform, solutions, or capabilities..." 
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <div className="search-esc" onClick={onClose}>ESC</div>
        </div>
        <div className="search-body">
          {!query ? (
            <div className="search-empty">
              <div className="mono" style={{fontSize: 11, marginBottom: 16, opacity: 0.5}}>RECENT SEARCHES</div>
              <div className="search-hints">
                <a href={prefix + "pages/platform-dsp"} onClick={onClose}>DSP Overview</a>
                <a href={prefix + "pages/capabilities-measurement-attribution"} onClick={onClose}>Multi-touch Attribution</a>
                <a href={prefix + "pages/solutions-advertisers"} onClick={onClose}>For Advertisers</a>
              </div>
            </div>
          ) : (
            <div className="search-results">
              <div className="mono" style={{fontSize: 11, marginBottom: 16, opacity: 0.5}}>
                {filtered.length > 0 ? "RESULTS" : "NO RESULTS FOUND"}
              </div>
              {filtered.map((it, i) => (
                <a key={i} href={prefix + it.href} className="search-item" onClick={onClose}>
                  <div>
                    <div style={{fontSize: 12, opacity: 0.5, marginBottom: 2}}>{it.category}</div>
                    <div style={{fontSize: 16, fontWeight: 500}}>{it.label}</div>
                    <div style={{fontSize: 13, opacity: 0.6}}>{it.desc}</div>
                  </div>
                  <Arrow className="search-item-arr" />
                </a>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function CookieConsent({ basePath = "" }) {
  const [visible, setVisible] = React.useState(false);
  const [showModal, setShowModal] = React.useState(false);
  const [prefs, setPrefs] = React.useState({ essential: true, analytics: true, ads: true });

  React.useEffect(() => {
    const consent = localStorage.getItem("auctera_consent");
    let showTimer, hideTimer;
    if (!consent) {
      showTimer = setTimeout(() => {
        setVisible(true);
        hideTimer = setTimeout(() => setVisible(false), 8000);
      }, 1500);
    }
    return () => { clearTimeout(showTimer); clearTimeout(hideTimer); };
  }, []);

  const save = (newPrefs) => {
    localStorage.setItem("auctera_consent", JSON.stringify(newPrefs));
    setVisible(false);
    setShowModal(false);
  };

  if (!visible && !showModal) return null;

  return (
    <>
      <div className="cookie-consent">
        <div className={`cookie-banner ${visible ? 'active' : ''}`}>
          <div className="cookie-content">
            <p>
              We use third-party cookies to measure website performance, analytics, personalize content and ads for you. 
              Read our <a href={basePath + "pages/company-cookies"}>cookie policy</a> for more details.
            </p>
          </div>
          <div className="cookie-actions">
            <button className="btn btn-ghost btn-sm" onClick={() => setShowModal(true)}>Customize</button>
            <button className="btn btn-ghost btn-sm" onClick={() => save({essential:true, analytics:false, ads:false})}>Decline</button>
            <button className="btn btn-ochre btn-sm" onClick={() => save({essential:true, analytics:true, ads:true})}>Accept all</button>
          </div>
        </div>
      </div>

      {showModal && (
        <div className="cookie-modal-overlay">
          <div className="cookie-modal">
            <h3>Cookie Settings</h3>
            <p>We use cookies to optimize your experience and analyze our traffic. Customize your preferences below.</p>
            
            <div className="cookie-option">
              <div>
                <div className="cookie-option-label">Essential Cookies</div>
                <div className="cookie-option-desc">Required for the site to function. Cannot be disabled.</div>
              </div>
              <div className="mono" style={{color: "var(--ochre)"}}>ALWAYS ON</div>
            </div>

            <div className="cookie-option">
              <div>
                <div className="cookie-option-label">Analytics & Performance</div>
                <div className="cookie-option-desc">Help us understand how visitors interact with the site.</div>
              </div>
              <input type="checkbox" checked={prefs.analytics} onChange={e => setPrefs({...prefs, analytics: e.target.checked})} />
            </div>

            <div className="cookie-option">
              <div>
                <div className="cookie-option-label">Personalized Ads</div>
                <div className="cookie-option-desc">Used to deliver more relevant advertisements to you.</div>
              </div>
              <input type="checkbox" checked={prefs.ads} onChange={e => setPrefs({...prefs, ads: e.target.checked})} />
            </div>

            <div style={{marginTop: 32, display: "flex", gap: 12}}>
              <button className="btn btn-ochre" style={{flex: 1}} onClick={() => save(prefs)}>Save settings</button>
              <button className="btn btn-ghost" onClick={() => setShowModal(false)}>Close</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function Header({ basePath = "", active = "" }) {
  const [open, setOpen] = React.useState(null);
  const [isSearchOpen, setIsSearchOpen] = React.useState(false);
  const ref = React.useRef(null);
  const prefix = basePath;

  React.useEffect(() => {
    const onDoc = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(null);
    };
    const onKey = (e) => { 
      if (e.key === "Escape") {
        setOpen(null);
        setIsSearchOpen(false);
      }
    };
    document.addEventListener("click", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("click", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, []);

  const toggle = (k) => setOpen(o => o === k ? null : k);

  return (
    <>
      <CookieConsent basePath={prefix} />
      <header className="site-header" ref={ref} style={{position: "sticky"}}>
        <div className="container bar">
        <a className="brand" href={prefix || "/"}>
          <img src={prefix + "uploads/auctera_logo.png"} alt="Auctera" style={{ height: 28, width: "auto" }} />
        </a>
        <nav className="nav-primary">
          <button className={open === "platform" ? "open" : ""} onClick={(e)=>{e.stopPropagation(); toggle("platform");}}>
            Platform <Caret />
          </button>
          <button className={open === "solutions" ? "open" : ""} onClick={(e)=>{e.stopPropagation(); toggle("solutions");}}>
            Solutions <Caret />
          </button>
          <button className={open === "capabilities" ? "open" : ""} onClick={(e)=>{e.stopPropagation(); toggle("capabilities");}}>
            Capabilities <Caret />
          </button>
          <a href={prefix + "pages/case-studies"} className="hide-md">Case Studies</a>
          <a href={prefix + "pages/blog"} className="hide-md">Blog</a>
          <a href={prefix + "pages/company-about"} className="hide-md">Company</a>
        </nav>
        <div className="nav-utility">
          <div className="search-trigger hide-md" onClick={() => setIsSearchOpen(true)}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <circle cx="6" cy="6" r="4.25" stroke="currentColor" strokeWidth="1.5"/>
              <path d="M9 9l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
            <span>Search</span>
          </div>
          <a className="login-link hide-md" href={prefix + "pages/login"}>Login</a>
          <a className="btn btn-ghost" href={prefix + "pages/contact"}>Contact sales <Arrow /></a>
        </div>
      </div>
      <Mega data={NAV.platform} open={open === "platform"} basePath={prefix} />
      <Mega data={NAV.solutions} open={open === "solutions"} basePath={prefix} />
      <Mega data={NAV.capabilities} open={open === "capabilities"} basePath={prefix} />
      <SearchOverlay open={isSearchOpen} onClose={() => setIsSearchOpen(false)} basePath={prefix} />
    </header>
    </>
  );
}

function Footer({ basePath = "" }) {
  const prefix = basePath;
  return (
    <footer className="site-footer">
      <div className="container">
        <p className="foot-lede">
          Scale without risk.<br/>Settle on outcomes.
        </p>
        <div className="foot-grid">
          <div>
            <div className="brand" style={{marginBottom: 20}}>
              <img src={prefix + "uploads/auctera_logo.png"} alt="Auctera" style={{ height: 24, width: "auto", filter: "brightness(0) invert(1)" }} />
            </div>
            <p style={{color: "rgba(246,242,236,.6)", fontSize: 14, maxWidth: 320, margin: 0}}>
              The unified performance marketing platform. DSP, affiliate network, retargeting, measurement and reporting — one coordinated system.
            </p>
            {/* Trust Badges */}
            <div className="footer-trust" style={{ marginTop: 40, paddingTop: 24, borderTop: "1px solid rgba(255,255,255,0.1)" }}>
              <div className="mono" style={{ marginBottom: 20, color: "rgba(246,242,236,0.8)", fontSize: 11, letterSpacing: "0.1em" }}>CERTIFICATIONS & COMPLIANCE</div>
              <div className="mono" style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px 16px", color: "rgba(246,242,236,.6)", fontSize: 11, letterSpacing: "0.15em"}}>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>GDPR NATIVE</span>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>SOC 2 TYPE II</span>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>ISO 27001</span>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>IAB TECH LAB</span>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>TAG CERTIFIED</span>
                <span><span className="tick" style={{color: "var(--ochre)", marginRight: 8}}>◆</span>CCPA READY</span>
              </div>
            </div>
          </div>
          <div>
            <h5>Platform</h5>
            <ul>
              <li><a href={prefix + "pages/platform-overview"}>Overview</a></li>
              <li><a href={prefix + "pages/platform-dsp"}>DSP</a></li>
              <li><a href={prefix + "pages/platform-measurement"}>Measurement</a></li>
              <li><a href={prefix + "pages/platform-reporting"}>Reporting</a></li>
              <li><a href={prefix + "pages/platform-retargeting"}>Retargeting Cloud</a></li>
              <li><a href={prefix + "pages/platform-affiliate"}>Affiliate Network</a></li>
              <li><a href={prefix + "pages/platform-how-it-works"}>How It Works</a></li>
            </ul>
          </div>
          <div>
            <h5>Solutions</h5>
            <ul>
              <li><a href={prefix + "pages/solutions-advertisers"}>For Advertisers</a></li>
              <li><a href={prefix + "pages/solutions-publishers"}>For Publishers</a></li>
              <li><a href={prefix + "pages/solutions-affiliates"}>For Affiliates</a></li>
              <li><a href={prefix + "pages/solutions-agencies"}>For Agencies</a></li>
              <li><a href={prefix + "pages/solutions-customer-acquisition"}>Customer Acquisition</a></li>
              <li><a href={prefix + "pages/solutions-roi-improvement"}>ROI Improvement</a></li>
            </ul>
          </div>
          <div>
            <h5>Capabilities</h5>
            <ul>
              <li><a href={prefix + "pages/capabilities-audience-targeting"}>Audience Targeting</a></li>
              <li><a href={prefix + "pages/capabilities-brand-safety"}>Brand Safety</a></li>
              <li><a href={prefix + "pages/capabilities-creative-optimization"}>Creative Optimization</a></li>
              <li><a href={prefix + "pages/capabilities-programmatic"}>Programmatic</a></li>
              <li><a href={prefix + "pages/capabilities-fraud-prevention"}>Fraud Prevention</a></li>
              <li><a href={prefix + "pages/capabilities-measurement-attribution"}>Measurement & Attribution</a></li>
            </ul>
          </div>
          <div>
            <h5>Company</h5>
            <ul>
              <li><a href={prefix + "pages/company-about"}>About</a></li>
              <li><a href="#">Careers</a></li>
              <li><a href="#">Press</a></li>
              <li><a href={prefix + "pages/case-studies"}>Case Studies</a></li>
              <li><a href={prefix + "pages/blog"}>Blog</a></li>
              <li><a href={prefix + "pages/contact"}>Contact Sales</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 Auctera LLC — New York · Dubai · Singapore</span>
          <span style={{display: "flex", gap: 24}}>
            <a href={prefix + "pages/company-privacy"}>Privacy</a>
            <a href={prefix + "pages/company-terms"}>Terms</a>
            <a href={prefix + "pages/company-security"}>Security</a>
            <a href={prefix + "pages/company-cookies"}>Cookies</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* Reveal on scroll hook */
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal, .reveal-stagger");
    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 -5% 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* FAQ accordion component */
function FAQ({ items }) {
  const [open, setOpen] = React.useState(0);
  return (
    <div className="faq">
      {items.map((it, i) => (
        <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{it.q}</span>
            <span className="plus">+</span>
          </button>
          <div className="faq-a"><div className="faq-a-inner">{it.a}</div></div>
        </div>
      ))}
    </div>
  );
}

/* Expose globals for multi-file Babel */
Object.assign(window, { Header, Footer, FAQ, Arrow, Caret, useReveal, CookieConsent });
