// Shared UI components
const { useState, useEffect, useRef } = React;

const ROUTES = ['home', 'services', 'cases', 'about', 'insights', 'contact'];

function useHashRoute() {
  const [route, setRoute] = useState(() => (window.location.hash.replace('#/', '') || 'home'));
  useEffect(() => {
    const onHash = () => {
      const r = window.location.hash.replace('#/', '') || 'home';
      setRoute(r);
      window.scrollTo({top: 0, behavior: 'instant'});
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const navigate = (r) => { window.location.hash = '#/' + r; };
  return [route, navigate];
}

function useScrolled(threshold = 80) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return scrolled;
}

function FadeUp({children, delay = 0, className = ''}) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => setVisible(true), delay); obs.disconnect(); }
    }, {threshold: 0.1});
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [delay]);
  return <div ref={ref} className={`fade-up ${visible ? 'in' : ''} ${className}`}>{children}</div>;
}

function CountUp({value, suffix = '', duration = 1800}) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        const start = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const ease = 1 - Math.pow(1 - p, 3);
          setN(Math.floor(value * ease));
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
        obs.disconnect();
      }
    }, {threshold: 0.5});
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [value, duration]);
  return <span ref={ref}>{n}{suffix}</span>;
}

function Logo({onDark = false}) {
  return (
    <a className="nav-logo" href="#/home" style={{color: onDark ? 'white' : 'var(--dark-text)'}}>
      <img src="assets/mantaga-logo.png" alt="Mantaga" className="nav-logo-img" />
      <span>MANTAGA</span>
    </a>
  );
}

function Nav({route, navigate, dark = false}) {
  const scrolled = useScrolled(60);
  const [open, setOpen] = useState(false);
  const navClass = dark
    ? (scrolled ? 'nav nav-dark-solid' : 'nav nav-transparent')
    : (scrolled ? 'nav nav-solid' : 'nav nav-transparent');
  const onDark = dark && !scrolled;
  const linkColor = onDark ? 'rgba(255,255,255,0.85)' : 'var(--dark-text)';
  const links = [
    ['services', 'Services'],
    ['cases', 'Case Studies'],
    ['about', 'About'],
    ['insights', 'Insights'],
    ['contact', 'Contact'],
  ];
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  return (
    <nav className={navClass}>
      <div className="container nav-inner">
        <Logo onDark={onDark} />
        <div className="nav-links">
          {links.map(([k, label]) => (
            <a key={k} href={`#/${k}`}
               className={route === k ? 'active' : ''}
               style={{color: linkColor}}>{label}</a>
          ))}
          <a href="#/contact" className="btn btn-primary" style={{padding: '10px 20px', fontSize: 13}}>
            Get Your Readiness Score
          </a>
        </div>
        <button className="nav-mobile-toggle" onClick={() => setOpen(!open)}
                aria-label={open ? 'Close menu' : 'Open menu'}
                style={{color: onDark ? 'white' : 'var(--dark-text)'}}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            {open ? <><path d="M18 6L6 18"/><path d="M6 6l12 12"/></> : <><path d="M3 6h18"/><path d="M3 12h18"/><path d="M3 18h18"/></>}
          </svg>
        </button>
      </div>
      <div className={`nav-mobile-drawer ${open ? 'open' : ''}`} onClick={() => setOpen(false)}>
        <div className="nav-mobile-panel" onClick={e => e.stopPropagation()}>
          <div className="nav-mobile-links">
            {links.map(([k, label]) => (
              <a key={k} href={`#/${k}`} onClick={() => setOpen(false)}
                 className={route === k ? 'active' : ''}>{label}</a>
            ))}
            <a href="#/contact" onClick={() => setOpen(false)} className="btn btn-primary" style={{marginTop: 16, justifyContent: 'center', width: '100%'}}>
              Get Your Readiness Score
            </a>
          </div>
        </div>
      </div>
    </nav>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Logo onDark={true} />
            <p style={{marginTop: 20, maxWidth: 320, fontSize: 14.5, lineHeight: 1.6}}>
              The UAE's specialist FMCG q-commerce consultancy.
            </p>
            <div style={{display: 'flex', gap: 12, marginTop: 24}}>
              {[
                {label: 'LinkedIn', href: 'https://www.linkedin.com/company/mantaga/', icon: <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M20.5 2h-17A1.5 1.5 0 0 0 2 3.5v17A1.5 1.5 0 0 0 3.5 22h17a1.5 1.5 0 0 0 1.5-1.5v-17A1.5 1.5 0 0 0 20.5 2zM8 19H5v-9h3zM6.5 8.25A1.75 1.75 0 1 1 8.3 6.5a1.78 1.78 0 0 1-1.8 1.75zM19 19h-3v-4.74c0-1.42-.6-1.93-1.38-1.93A1.74 1.74 0 0 0 13 14.19a.66.66 0 0 0 0 .14V19h-3v-9h2.9v1.3a3.11 3.11 0 0 1 2.7-1.4c1.55 0 3.36.86 3.36 3.66z"/></svg>},
                {label: 'Instagram', href: 'https://www.instagram.com/mantagasolutions/', icon: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg>}
              ].map(s => (
                <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.label} title={s.label} style={{
                  width: 36, height: 36, borderRadius: 8, background: 'rgba(255,255,255,0.06)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'rgba(255,255,255,0.78)', transition: 'background 0.2s, color 0.2s'
                }} onMouseEnter={e => {e.currentTarget.style.background = 'var(--coral)'; e.currentTarget.style.color = 'white';}} onMouseLeave={e => {e.currentTarget.style.background = 'rgba(255,255,255,0.06)'; e.currentTarget.style.color = 'rgba(255,255,255,0.78)';}}>{s.icon}</a>
              ))}
            </div>
          </div>
          <div>
            <h5>Pages</h5>
            <ul>
              <li><a href="#/services">Services</a></li>
              <li><a href="#/cases">Case Studies</a></li>
              <li><a href="#/about">About</a></li>
              <li><a href="#/insights">Insights</a></li>
              <li><a href="#/contact">Contact</a></li>
            </ul>
          </div>
          <div>
            <h5>Resources</h5>
            <ul>
              <li><a href="#/contact">Q-Commerce Readiness Score</a></li>
              <li><a href="#/insights">The Mantaga Memo</a></li>
              <li><a href="#/contact">Onboarding Checklist</a></li>
            </ul>
          </div>
          <div>
            <h5>Contact</h5>
            <ul>
              <li>sales@mantaga.com</li>
              <li>Dubai, UAE</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Mantaga. All rights reserved.</div>
          <div><a href="#" style={{marginRight: 16}}>Privacy Policy</a><a href="#">Terms</a></div>
        </div>
      </div>
    </footer>
  );
}

// SVG icon set
const Icon = {
  rocket: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>,
  file: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="15" y2="17"/></svg>,
  chart: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>,
  package: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M16.5 9.4l-9-5.19"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
  pie: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></svg>,
  briefcase: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>,
  target: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
  arrow: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/></svg>,
};

// Hero abstract visual
function HeroVisual() {
  return (
    <div style={{position: 'absolute', right: 0, top: 0, bottom: 0, width: '50%', pointerEvents: 'none', overflow: 'hidden'}}>
      <svg viewBox="0 0 600 800" preserveAspectRatio="xMidYMid slice" style={{width: '100%', height: '100%'}}>
        <defs>
          <linearGradient id="grad1" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#E8604C" stopOpacity="0.3"/>
            <stop offset="100%" stopColor="#16213e" stopOpacity="0"/>
          </linearGradient>
          <linearGradient id="grad2" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#16213e" stopOpacity="0.6"/>
            <stop offset="100%" stopColor="#E8604C" stopOpacity="0.1"/>
          </linearGradient>
        </defs>
        <circle cx="500" cy="200" r="180" fill="url(#grad1)"/>
        <circle cx="350" cy="500" r="220" fill="url(#grad2)"/>
        {/* concentric arcs */}
        {[120, 200, 280, 360, 440].map((r,i) => (
          <circle key={i} cx="480" cy="400" r={r} fill="none" stroke="rgba(232,96,76,0.08)" strokeWidth="1" strokeDasharray="2 6"/>
        ))}
      </svg>
    </div>
  );
}

Object.assign(window, {useHashRoute, useScrolled, FadeUp, CountUp, Nav, Footer, Logo, Icon, HeroVisual});
