/* ATC Shared Component Library
   Load order: tweaks-panel.jsx → components.jsx → apex-visual.jsx → app.jsx / platform.jsx
   All exports available via window.ATC.
*/
const { useState, useEffect, useRef, useCallback } = React;

/* ============================================================
   HOOKS
   ============================================================ */

const useReveal = () => {
  useEffect(() => {
    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.1, rootMargin: '0px 0px -80px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
};

/* Touch-enabled carousel — measures actual card width so nav snaps correctly
   even when card width is a fraction of the container ("1/3 peek" effect). */
const useCarousel = (itemCount) => {
  const [idx, setIdx] = useState(0);
  const [perView, setPerView] = useState(() =>
    typeof window !== 'undefined' && window.innerWidth < 720 ? 1 : window.innerWidth < 1100 ? 2 : 3
  );
  const [dragOffset, setDragOffset] = useState(0);
  const wrapRef = useRef(null);
  const trackRef = useRef(null);
  const [cardW, setCardW] = useState(404);
  const touchState = useRef({ startX: 0, currentX: 0, dragging: false });

  useEffect(() => {
    const measure = () => {
      const w = window.innerWidth;
      setPerView(w < 720 ? 1 : w < 1100 ? 2 : 3);
      const firstCard = trackRef.current?.firstElementChild;
      if (firstCard) setCardW(firstCard.offsetWidth + 24);
    };
    measure();
    window.addEventListener('resize', measure);
    const ro = new ResizeObserver(measure);
    if (trackRef.current?.firstElementChild) ro.observe(trackRef.current.firstElementChild);
    return () => { window.removeEventListener('resize', measure); ro.disconnect(); };
  }, [itemCount]);

  const max = Math.max(0, itemCount - perView);
  const safeIdx = Math.min(idx, max);

  const goTo = useCallback((newIdx) => {
    setIdx(Math.max(0, Math.min(max, newIdx)));
    setDragOffset(0);
  }, [max]);

  const handleTouchStart = useCallback((e) => {
    const touch = e.touches[0];
    touchState.current = { startX: touch.clientX, currentX: touch.clientX, dragging: true };
    setDragOffset(0);
  }, []);

  const handleTouchMove = useCallback((e) => {
    if (!touchState.current.dragging) return;
    const touch = e.touches[0];
    touchState.current.currentX = touch.clientX;
    setDragOffset(touch.clientX - touchState.current.startX);
  }, []);

  const handleTouchEnd = useCallback(() => {
    if (!touchState.current.dragging) return;
    const delta = touchState.current.currentX - touchState.current.startX;
    const threshold = cardW * 0.25;
    if (delta < -threshold && idx < max) goTo(idx + 1);
    else if (delta > threshold && idx > 0) goTo(idx - 1);
    else setDragOffset(0);
    touchState.current.dragging = false;
  }, [cardW, idx, max, goTo]);

  return {
    wrapRef, trackRef, idx: safeIdx, max, cardW, dragOffset,
    next: () => goTo(safeIdx + 1),
    prev: () => goTo(safeIdx - 1),
    handlers: { onTouchStart: handleTouchStart, onTouchMove: handleTouchMove, onTouchEnd: handleTouchEnd },
  };
};

/* ============================================================
   PRIMITIVES
   ============================================================ */

/* Counts up from 0 to `to` on first scroll-enter, cubic ease-out. */
const Counter = ({ to, suffix = '', duration = 1800 }) => {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            setVal(Math.round(to * (1 - Math.pow(1 - t, 3))));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{val.toLocaleString()}{suffix && <span className="suffix">{suffix}</span>}</span>;
};

/* Mobile-only fixed bottom bar with hamburger + primary CTA. */
const FloatingBar = ({ onMenuClick, onDemoClick }) => (
  <div className="floating-bar">
    <button type="button" className="floating-bar-btn" onClick={onMenuClick} aria-label="Open menu">
      <svg width="18" height="14" viewBox="0 0 18 14" fill="none" xmlns="http://www.w3.org/2000/svg">
        <rect width="18" height="2" rx="1" fill="currentColor" />
        <rect y="6" width="18" height="2" rx="1" fill="currentColor" />
        <rect y="12" width="18" height="2" rx="1" fill="currentColor" />
      </svg>
    </button>
    <button type="button" className="btn btn-primary" onClick={onDemoClick}>Get Started</button>
  </div>
);

/* Standard two-part section opener: large h2 left, supporting copy right. */
const SectionHeader = ({ title, subtitle, className = '' }) => (
  <div className={`section-header reveal${className ? ' ' + className : ''}`}>
    <h2 className="display">{title}</h2>
    {subtitle && <p className="right">{subtitle}</p>}
  </div>
);

/* ============================================================
   CONTACT MODAL
   ============================================================ */

const SOLUTIONS = [
  {
    section: 'Platforms',
    items: [
      { id: 'apex-go', label: 'Apex Go' },
      { id: 'apex-bridge', label: 'Apex Bridge' },
      { id: 'ava', label: 'AVA' },
      { id: 'historian', label: 'Historian' },
      { id: 'athena-ai', label: 'Athena AI' },
    ]
  },
  {
    section: 'Solutions',
    items: [
      { id: 'curio', label: 'Curio' },
      { id: 'sentinel', label: 'Sentinel' },
      { id: 'verify', label: 'Verify' },
      { id: 'certiflow', label: 'Certiflow' },
      { id: 'docreference', label: 'DocReference' },
      { id: 'insightscore', label: 'InsightScore' },
      { id: 'testcraft', label: 'TestCraft' },
    ]
  },
  {
    section: 'Services',
    items: [
      { id: 'agentic-ai', label: 'Agentic AI' },
      { id: 'machine-learning', label: 'Machine Learning' },
      { id: 'data-analytics', label: 'Data & Analytics' },
      { id: 'general-inquiry', label: 'General Inquiry' },
    ]
  }
];

const ContactModal = ({ open, onClose }) => {
  const emptyForm = { name: '', email: '', phone: '', phoneCode: '+60', company: '', solutions: [], message: '' };
  const [form, setForm] = useState(emptyForm);
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [apiError, setApiError] = useState('');
  const [sending, setSending] = useState(false);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  useEffect(() => {
    if (!open) setTimeout(() => {
      setSubmitted(false); setForm(emptyForm); setErrors({}); setApiError('');
    }, 250);
  }, [open]);

  /* Keep modal height in sync with the soft keyboard on mobile. */
  useEffect(() => {
    const vv = window.visualViewport;
    if (!vv || !open) return;
    const modal = document.querySelector('.modal');
    if (!modal) return;
    const update = () => { modal.style.height = vv.height + 'px'; };
    vv.addEventListener('resize', update);
    vv.addEventListener('scroll', update);
    update();
    return () => {
      vv.removeEventListener('resize', update);
      vv.removeEventListener('scroll', update);
      modal.style.height = '';
    };
  }, [open]);

  const toggleSolution = (id) => setForm(f => ({
    ...f,
    solutions: f.solutions.includes(id) ? f.solutions.filter(s => s !== id) : [...f.solutions, id],
  }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Valid email required';
    if (!form.phone.trim()) e.phone = 'Required';
    if (!form.company.trim()) e.company = 'Required';
    if (form.solutions.length === 0) e.solutions = 'Please select at least one area of interest';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const isFormReady = form.name.trim() && form.email.trim() &&
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    setApiError('');
    if (!validate()) {
      setTimeout(() => {
        const firstError = document.querySelector('.modal-form-scroll .field.error');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 0);
      return;
    }
    setSending(true);
    try {
      const res = await fetch('https://us-central1-aitecl-ai.cloudfunctions.net/sendContact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) { setApiError(data.error || 'Something went wrong. Please try again.'); return; }
      setSubmitted(true);
    } catch {
      setApiError('Something went wrong. Please try again or email us directly at edward@aitecl.com.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div className={`modal-overlay ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={(ev) => ev.stopPropagation()}>
        <button type="button" className="modal-close" onClick={onClose} aria-label="Close">✕</button>
        {!submitted ? (
          <>
            <h3>Let's Talk</h3>
            <p className="sub">Tell us what you're working on and we'll line up the right team member..</p>
            <form onSubmit={handleSubmit} noValidate>
              <div className="modal-form-scroll">
                <div className="field-row">
                  <div className={`field ${errors.name ? 'error' : ''}`}>
                    <label>Name <span style={{ color: 'var(--accent)' }}>*</span></label>
                    <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                    {errors.name && <div className="err">{errors.name}</div>}
                  </div>
                  <div className={`field ${errors.email ? 'error' : ''}`}>
                    <label>Work email <span style={{ color: 'var(--accent)' }}>*</span></label>
                    <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                    {errors.email && <div className="err">{errors.email}</div>}
                  </div>
                </div>
                <div className={`field ${errors.phone ? 'error' : ''}`}>
                  <label>Mobile number <span style={{ color: 'var(--accent)' }}>*</span></label>
                  <div className="phone-field-wrap">
                    <select
                      title="Country code"
                      value={form.phoneCode}
                      onChange={(e) => setForm({ ...form, phoneCode: e.target.value })}
                      className="phone-code-select"
                    >
                      <option value="+60">MY +60</option>
                      <option value="+65">SG +65</option>
                      <option value="+971">AE +971</option>
                      <option value="+61">AU +61</option>
                      <option value="+55">BR +55</option>
                      <option value="+86">CN +86</option>
                      <option value="+33">FR +33</option>
                      <option value="+852">HK +852</option>
                      <option value="+91">IN +91</option>
                      <option value="+62">ID +62</option>
                      <option value="+81">JP +81</option>
                      <option value="+82">KR +82</option>
                      <option value="+49">DE +49</option>
                      <option value="+52">MX +52</option>
                      <option value="+63">PH +63</option>
                      <option value="+966">SA +966</option>
                      <option value="+66">TH +66</option>
                      <option value="+44">UK +44</option>
                      <option value="+1">US +1</option>
                      <option value="+84">VN +84</option>
                    </select>
                    <input type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                  </div>
                  {errors.phone && <div className="err">{errors.phone}</div>}
                </div>
                <div className={`field ${errors.company ? 'error' : ''}`}>
                  <label>Company <span style={{ color: 'var(--accent)' }}>*</span></label>
                  <input value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })} />
                  {errors.company && <div className="err">{errors.company}</div>}
                </div>
                <div className={`field ${errors.solutions ? 'error' : ''}`}>
                  <label>Solutions of interest <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--text-3)' }}>(select all that apply)</span></label>
                  {errors.solutions && <div className="err">{errors.solutions}</div>}
                  <div className="solutions-accordion">
                    {SOLUTIONS.map((section) => (
                      <div key={section.section} className="solutions-section">
                        <div className="solutions-section-header">
                          <span>{section.section}</span>
                          <span className="section-count">{section.items.filter(i => form.solutions.includes(i.id)).length}/{section.items.length}</span>
                        </div>
                        <div className="solutions-section-items">
                          {section.items.map(s => (
                            <label key={s.id} className={`solution-chip ${form.solutions.includes(s.id) ? 'selected' : ''}`}>
                              <input type="checkbox" checked={form.solutions.includes(s.id)} onChange={() => toggleSolution(s.id)} />
                              <span className="chip-label">{s.label}</span>
                            </label>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="field">
                  <label>Anything else? <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--text-3)' }}>(optional)</span></label>
                  <textarea rows="3" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
                </div>
                {apiError && <div className="api-error">{apiError}</div>}
              </div>
              <div className="submit-row">
                <button
                  type="submit"
                  className={`btn btn-primary ${!isFormReady ? 'btn-disabled-submit' : ''}`}
                  disabled={sending}
                  onClick={() => { if (!isFormReady) { validate(); setTimeout(() => { const el = document.querySelector('.modal-form-scroll .field.error'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' }); }, 0); } }}
                >
                  {sending ? (
                    <>
                      <span className="btn-spinner" />
                      Sending Message …
                    </>
                  ) : 'Send Message →'}
                </button>
                <span style={{ fontSize: 12, color: 'var(--text-3)' }}>We reply within 1 business day.</span>
              </div>
            </form>
          </>
        ) : (
          <div className="success">
            <div className="check">✓</div>
            <h3 style={{ textAlign: 'center' }}>Message sent</h3>
            <p className="sub" style={{ textAlign: 'center' }}>
              A member of our team will reach out to <strong style={{ color: 'var(--text)' }}>{form.email}</strong> within 1 business day.
            </p>
            <div style={{ textAlign: 'center', marginTop: 24 }}>
              <button type="button" className="btn btn-ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

/* ============================================================
   NAV
   ============================================================ */

const NAV_ANCHORS = ['solutions', 'platforms', 'tech'];

const useActiveSection = () => {
  const [active, setActive] = useState('');
  useEffect(() => {
    const update = () => {
      const viewCenter = window.scrollY + window.innerHeight * 0.4;
      let best = null;
      let bestDist = Infinity;
      NAV_ANCHORS.forEach((id) => {
        const el = document.getElementById(id);
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const absTop = window.scrollY + rect.top;
        if (absTop <= viewCenter && viewCenter - absTop < bestDist) {
          bestDist = viewCenter - absTop;
          best = id;
        }
      });
      setActive(best || '');
    };
    window.addEventListener('scroll', update, { passive: true });
    update();
    return () => window.removeEventListener('scroll', update);
  }, []);
  return active;
};

/* homeUrl — href for the logo link (default '/')
   showProductsNav — show Products link (default false)
   showPlatformNav — show Platform link (default false)
   activeSection — which nav item is currently active */
const Nav = ({ onDemoClick, homeUrl = 'index.html', showProductsNav = false, showPlatformNav = false, activeSection = '' }) => {
  const [scrolled, setScrolled] = useState(false);
  const active = useActiveSection();
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const current = activeSection || active;
  const isIndexPage = window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname === '';
  const indexUrl = window.location.origin + (isIndexPage ? '' : '/index.html');

  const handleNavClick = (e, href) => {
    if (href.startsWith('#') && !isIndexPage) {
      e.preventDefault();
      window.location.href = indexUrl + href;
    }
  };

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href={homeUrl} className="logo">
          <img src="/assets/atc-mark.png" alt="ATC" />
          <span className="logo-text">ATC</span>
        </a>
        <div className="nav-links">
          {(showPlatformNav || showProductsNav) && <a className={`nav-link ${current === 'solutions' ? 'active' : ''}`} href={isIndexPage ? '#solutions' : '/solutions/'} onClick={(e) => { if (!isIndexPage && !e.shiftKey && !e.ctrlKey && !e.metaKey) return; handleNavClick(e, isIndexPage ? '#solutions' : '/solutions/'); }}>Solutions</a>}
          {(showPlatformNav || showProductsNav) && <a className={`nav-link ${current === 'platforms' ? 'active' : ''}`} href={isIndexPage ? '#platforms' : '/platforms/'} onClick={(e) => { if (!isIndexPage && !e.shiftKey && !e.ctrlKey && !e.metaKey) return; handleNavClick(e, isIndexPage ? '#platforms' : '/platforms/'); }}>Platforms</a>}
          <a className={`nav-link ${current === 'tech' ? 'active' : ''}`} href="#tech" onClick={(e) => handleNavClick(e, '#tech')}>Technology</a>
          {showProductsNav && <a className={`nav-link ${current === 'about' ? 'active' : ''}`} href={isIndexPage ? '#about' : '/about-us.html'} onClick={(e) => { if (!isIndexPage && !e.shiftKey && !e.ctrlKey && !e.metaKey) return; handleNavClick(e, isIndexPage ? '#about' : '/about-us.html'); }}>About</a>}
          <button type="button" className="btn btn-primary nav-cta" onClick={onDemoClick}>Get Started →</button>
        </div>
      </div>
    </nav>);
};

/* ============================================================
   MOBILE MENU
   ============================================================ */

/* products  — array of { id, name } for the Solutions submenu
   platforms — array of { id, name } for the Platforms submenu
   showHowItWorks — show "How It Works" link (default false)
   showCoverage — show "Coverage" link (default false)
   showFaq — show "FAQs" link pointing to homepage (default false) */
const MobileMenu = ({ open, onClose, onDemoClick, products = [], platforms = [], showHowItWorks = false, showCoverage = false, showFaq = false, showAbout = false }) => {
  const scrollLockRef = useRef(false);
  const [productsOpen, setProductsOpen] = useState(false);
  const [platformsOpen, setPlatformsOpen] = useState(false);

  useEffect(() => {
    if (open) {
      scrollLockRef.current = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = scrollLockRef.current || '';
    }
    return () => { document.body.style.overflow = scrollLockRef.current || ''; };
  }, [open]);

  const isIndexPage = window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname === '';
  const indexUrl = window.location.origin + (isIndexPage ? '' : '/index.html');

  const handleLinkClick = (e, href) => {
    e.preventDefault();
    onClose();
    const isAnchorOnly = href.startsWith('#');
    setTimeout(() => {
      if (isAnchorOnly) {
        const el = document.querySelector(href);
        if (el) el.scrollIntoView({ behavior: 'smooth' });
      } else {
        window.location.href = href;
      }
    }, 200);
  };

  return (
    <div className={`mobile-menu-overlay ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="mobile-menu-panel" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="mobile-menu-close" onClick={onClose} aria-label="Close menu">✕</button>
        <div className="mobile-menu-links">
          {showHowItWorks && (
            <button type="button" className="mobile-menu-link" onClick={(e) => handleLinkClick(e, '#how-it-works')}>How It Works</button>
          )}
          {platforms.length > 0 && (
            <div className="mobile-menu-item">
              <div className="mobile-menu-link mobile-menu-expandable">
                <button type="button" className="mobile-menu-label-btn" onClick={(e) => handleLinkClick(e, '#platforms')}>Platforms</button>
                <button type="button" className="mobile-menu-caret-btn" onClick={() => setPlatformsOpen(p => !p)} aria-expanded={platformsOpen ? "true" : "false"} aria-label={platformsOpen ? 'Collapse platforms' : 'Expand platforms'}>
                  <svg className={`mobile-menu-chevron ${platformsOpen ? 'open' : ''}`} width="12" height="8" viewBox="0 0 12 8" fill="none"><path d="M1 1L6 6L11 1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              {platformsOpen && (
                <div className="mobile-submenu">
                  {platforms.map(p => (
                    <button key={p.id} className="mobile-submenu-link" onClick={(e) => handleLinkClick(e, '#' + p.id)}>{p.name}</button>
                  ))}
                </div>
              )}
            </div>
          )}
          {products.length > 0 && (
            <div className="mobile-menu-item">
              <div className="mobile-menu-link mobile-menu-expandable">
                <button type="button" className="mobile-menu-label-btn" onClick={(e) => handleLinkClick(e, '#solutions')}>Solutions</button>
                <button type="button" className="mobile-menu-caret-btn" onClick={() => setProductsOpen(p => !p)} aria-expanded={productsOpen ? "true" : "false"} aria-label={productsOpen ? 'Collapse solutions' : 'Expand solutions'}>
                  <svg className={`mobile-menu-chevron ${productsOpen ? 'open' : ''}`} width="12" height="8" viewBox="0 0 12 8" fill="none"><path d="M1 1L6 6L11 1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              {productsOpen && (
                <div className="mobile-submenu">
                  {products.map(p => (
                    <button key={p.id} className="mobile-submenu-link" onClick={(e) => handleLinkClick(e, '#' + p.id)}>{p.name}</button>
                  ))}
                </div>
              )}
            </div>
          )}
          {showCoverage && (
            <button type="button" className="mobile-menu-link" onClick={(e) => handleLinkClick(e, '#coverage')}>Coverage</button>
          )}
          {showFaq && (
            <button type="button" className="mobile-menu-link" onClick={(e) => handleLinkClick(e, '#faq')}>FAQs</button>
          )}
          {showAbout && (
            <button type="button" className="mobile-menu-link" onClick={(e) => handleLinkClick(e, '/about-us.html')}>About</button>
          )}
        </div>
        <div className="mobile-menu-cta">
          <button type="button" className="btn btn-primary mobile-menu-cta" onClick={() => { onClose(); onDemoClick(); }}>Get Started →</button>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   PAGE-LEVEL SECTIONS
   ============================================================ */

/* heading  — text on line 1 of the h2
   accent   — accent-coloured text on line 2
   sub      — paragraph below the heading (string or JSX)
   actions  — [{ label, variant?, onClick?, href? }]  variant defaults to 'primary' */
const FinalCTA = ({ heading, accent, sub, actions = [] }) => (
  <section className="final-cta">
    <div className="final-cta-bg" />
    <div className="container">
      <div className="final-cta-inner reveal">
        <h2>{heading}<br /><span className="accent">{accent}</span></h2>
        {sub && <p>{sub}</p>}
        <div className="actions">
          {actions.map((a, i) =>
            a.href
              ? <a key={i} className={`btn btn-${a.variant || 'primary'}`} href={a.href}>{a.label}</a>
              : <button key={i} className={`btn btn-${a.variant || 'primary'}`} onClick={a.onClick}>{a.label}</button>
          )}
        </div>
      </div>
    </div>
  </section>
);

/* cols     — [{ heading, links: [{ label, href }] }]
   footerId — optional id attribute on <footer> */
const Footer = ({ cols = [], footerId }) => (
  <footer className="footer" {...(footerId ? { id: footerId } : {})}>
    <div className="container">
      <div className="footer-grid">
        <div className="footer-brand">
          <a href="/" className="logo">
            <img src="/assets/atc-mark.png" alt="ATC" />
            <span className="logo-text">ATC</span>
          </a>
          <p>AI Tech Cloud. Enterprise AI engineering & automation. We build the future of AI for the systems that already run the world.</p>
        </div>
        {cols.map((col, i) => (
          <div key={i} className="footer-col">
            <h5>{col.heading}</h5>
            <ul>
              {col.links.map((l, j) => <li key={j}><a href={l.href}>{l.label}</a></li>)}
            </ul>
            {col.subHeading && col.subLinks && (
              <>
                <h5 style={{ marginTop: '2.5rem' }}>{col.subHeading}</h5>
                <ul>
                  {col.subLinks.map((l, j) => <li key={j}><a href={l.href}>{l.label}</a></li>)}
                </ul>
              </>
            )}
          </div>
        ))}
      </div>
      <div className="footer-bottom">
        <div>© 2026 AI Tech Cloud · ATC. All rights reserved.</div>
        <div className="legal">
          <a href="#">Privacy</a>
          <a href="#">Terms</a>
          <a href="#">Cookies</a>
        </div>
      </div>
    </div>
  </footer>
);

/* ============================================================
   EXPORTS
   ============================================================ */

window.ATC = {
  /* hooks */
  useReveal, useCarousel,
  /* primitives */
  Counter, FloatingBar, SectionHeader,
  /* nav */
  Nav, MobileMenu,
  /* modal */
  SOLUTIONS, ContactModal,
  /* page sections */
  FinalCTA, Footer,
};
