/* global React */
const { useState, useEffect, useRef, useCallback, useMemo } = React;

/* ============================================================
   Router — history API, supports back/forward
   ============================================================ */
function useHashRoute() {
  const [route, setRoute] = useState(() => window.location.pathname || '/');
  useEffect(() => {
    const onPop = () => {
      const r = window.location.pathname || '/';
      setRoute(r);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  const navigate = useCallback((path) => {
    history.pushState(null, '', path);
    window.dispatchEvent(new PopStateEvent('popstate'));
  }, []);
  return [route, navigate];
}

function Link({ to, children, className, ...rest }) {
  const onClick = (e) => {
    e.preventDefault();
    history.pushState(null, '', to);
    window.dispatchEvent(new PopStateEvent('popstate'));
  };
  return <a href={to} onClick={onClick} className={className} {...rest}>{children}</a>;
}

/* ============================================================
   Reveal on scroll
   ============================================================ */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -60px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ============================================================
   Animated counter
   ============================================================ */
function Counter({ value, suffix = '', prefix = '', duration = 1600, decimals = 0 }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setN(value * eased);
            if (t < 1) requestAnimationFrame(tick);
            else setN(value);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [value, duration]);

  const formatted = decimals > 0 ? n.toFixed(decimals) : Math.round(n).toLocaleString();
  return <span ref={ref}>{prefix}{formatted}{suffix}</span>;
}

/* ============================================================
   Icons (inline SVG)
   ============================================================ */
const Icon = {
  Arrow: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" className="arrow">
      <path d="M3.5 8H12.5M12.5 8L8.5 4M12.5 8L8.5 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  ArrowUpRight: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M4 10L10 4M10 4H5M10 4V9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Plus: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 2.5V11.5M2.5 7H11.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  ),
  X: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 3L11 11M11 3L3 11" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  ),
  Linkedin: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="currentColor">
      <path d="M3.6 4.5a1.4 1.4 0 1 1 0-2.8 1.4 1.4 0 0 1 0 2.8zM2.3 5.6h2.5v8.1H2.3V5.6zm4.4 0h2.4v1.1h0c.3-.6 1.1-1.3 2.4-1.3 2.5 0 3 1.6 3 3.8v4.5h-2.5V9.7c0-1 0-2.2-1.4-2.2-1.4 0-1.6 1-1.6 2.1v4.1H6.7V5.6z"/>
    </svg>
  ),
  Mail: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <rect x="2" y="3.5" width="12" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.3"/>
      <path d="M2.5 4.5L8 8.5L13.5 4.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    </svg>
  ),
  Voice: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="M11 2v8M11 14v.1"/>
      <path d="M6 8v3a5 5 0 0010 0V8"/>
      <path d="M11 18v2M8 20h6" strokeLinejoin="round"/>
    </svg>
  ),
  Chat: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 11a8 8 0 0114-5.3M19 11a8 8 0 01-12 7L3 19l1-4"/>
    </svg>
  ),
  Mesh: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="4" cy="4" r="1.5"/>
      <circle cx="18" cy="4" r="1.5"/>
      <circle cx="4" cy="18" r="1.5"/>
      <circle cx="18" cy="18" r="1.5"/>
      <circle cx="11" cy="11" r="1.5"/>
      <path d="M5 5l5 5M17 5l-5 5M5 17l5-6M17 17l-5-6" strokeLinecap="round"/>
    </svg>
  ),
  Shield: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <path d="M11 2L3 5v6c0 5 4 8 8 9 4-1 8-4 8-9V5l-8-3z"/>
      <path d="M8 11l2 2 4-4" strokeLinecap="round"/>
    </svg>
  ),
  Diagram: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="3" y="3" width="6" height="6" rx="1"/>
      <rect x="13" y="3" width="6" height="6" rx="1"/>
      <rect x="3" y="13" width="6" height="6" rx="1"/>
      <rect x="13" y="13" width="6" height="6" rx="1"/>
      <path d="M9 6h4M9 16h4M6 9v4M16 9v4" strokeLinecap="round"/>
    </svg>
  ),
  Spark: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <path d="M11 3v4M11 15v4M3 11h4M15 11h4M5.5 5.5l2.5 2.5M14 14l2.5 2.5M16.5 5.5L14 8M8 14l-2.5 2.5"/>
    </svg>
  ),
  Layers: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <path d="M11 2l9 5-9 5-9-5 9-5z"/>
      <path d="M2 12l9 5 9-5M2 17l9 5 9-5"/>
    </svg>
  ),
  Bank: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <path d="M2 8L11 3l9 5"/>
      <path d="M3 8v10M19 8v10M7 11v5M11 11v5M15 11v5M2 18h18"/>
    </svg>
  ),
  Plane: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <path d="M2 12l18-7-7 17-3-7-8-3z"/>
    </svg>
  ),
  Truck: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <rect x="2" y="6" width="10" height="9" rx="1"/>
      <path d="M12 9h4l4 3v3h-8M7 18a2 2 0 100-4 2 2 0 000 4zM17 18a2 2 0 100-4 2 2 0 000 4z"/>
    </svg>
  ),
  Headphones: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 14v-3a8 8 0 0116 0v3"/>
      <path d="M3 14v3a2 2 0 002 2h1v-7H5a2 2 0 00-2 2zM19 14v3a2 2 0 01-2 2h-1v-7h1a2 2 0 012 2z"/>
    </svg>
  ),
  Globe: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="11" cy="11" r="9"/>
      <path d="M2 11h18M11 2c2.5 3 2.5 15 0 18M11 2c-2.5 3-2.5 15 0 18"/>
    </svg>
  ),
  Lock: () => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <rect x="4" y="10" width="14" height="9" rx="1"/>
      <path d="M7 10V7a4 4 0 018 0v3"/>
    </svg>
  ),
  Check: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M2.5 7.5L5.5 10.5L11.5 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
};

/* ============================================================
   Top Nav
   ============================================================ */
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    { to: '/', label: 'Home' },
    { to: '/about', label: 'About' },
    { to: '/services', label: 'Services' },
    { to: '/use-cases', label: 'Use Cases' },
    { to: '/contact', label: 'Contact' },
  ];
  const active = (to) => to === '/' ? route === '/' : route.startsWith(to);
  return (
    <header className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <Link to="/" className="brand">
          <span className="brand-mark">
            <img src="assets/latticore-logo.png" alt="" />
          </span>
          <img src="uploads/Logotext.png" alt="Latticore AI" className="brand-logotext" />
        </Link>
        <nav className="nav-links">
          {links.map((l) => (
            <Link key={l.to} to={l.to} className={`nav-link ${active(l.to) ? 'active' : ''}`}>
              {l.label}
            </Link>
          ))}
        </nav>
        <div className="nav-cta">
          <Link to="/contact" className="btn btn-primary">
            Start a conversation <Icon.Arrow />
          </Link>
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   Footer
   ============================================================ */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-brand-row">
              <img src="assets/latticore-logo.png" alt="" className="footer-brand-icon" />
              <img src="uploads/Logotext.png" alt="Latticore AI" className="footer-brand-logotext" />
            </div>
            <p className="footer-tagline">
              End-to-end Agentic AI and CRM solutions for intelligent customer operations.
            </p>
          </div>
          <div>
            <h4>Navigate</h4>
            <ul>
              <li><Link to="/">Home</Link></li>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/services">Services</Link></li>
              <li><Link to="/use-cases">Use Cases</Link></li>
              <li><Link to="/contact">Contact</Link></li>
            </ul>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              <li><Link to="/services">Agentic AI</Link></li>
              <li><Link to="/services">CRM Solutions</Link></li>
              <li><Link to="/services">Delivery approach</Link></li>
              <li><Link to="/use-cases">Case studies</Link></li>
            </ul>
          </div>
          <div>
            <h4>Connect</h4>
            <ul>
              <li><a href="mailto:info@latticoreai.com">info@latticoreai.com</a></li>
              <li><a href="https://www.linkedin.com/company/latticore-ai/" target="_blank" rel="noreferrer">LinkedIn ↗</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Latticore AI. All rights reserved.</span>
          <span>Designed for executive transformation.</span>
        </div>
      </div>
    </footer>
  );
}

/* Expose */
Object.assign(window, {
  useHashRoute, Link, useReveal, Counter, Icon, Nav, Footer,
});
