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

// ----- Lucide icon helper -----
// Uses the documented `<i data-lucide="...">` + `lucide.createIcons()` pattern
// so we work with whatever shape the UMD bundle ships.
function Icon({ name, size = 20, stroke = 1.75, color }) {
  const ref = React.useRef(null);
  useEffect(() => {
    if (window.lucide && window.lucide.createIcons && ref.current) {
      window.lucide.createIcons({ icons: window.lucide.icons, nameAttr: 'data-lucide', attrs: {} });
    }
  });
  return (
    <span ref={ref} style={{ display: 'inline-flex', color, lineHeight: 0 }}>
      <i data-lucide={name} style={{ width: size, height: size, strokeWidth: stroke }} />
    </span>
  );
}

// ----- Logo (inline SVG so brand fonts apply) -----
function Logo({ height = 30 }) {
  const w = (height / 80) * 360;
  return (
    <svg width={w} height={height} viewBox="0 0 360 80" xmlns="http://www.w3.org/2000/svg" aria-label="Rio Grande Websites">
      <text x="0" y="46" style={{ fontFamily: "'Cormorant Garamond', Georgia, serif", fontStyle: 'italic', fontWeight: 500, fontSize: 44, fill: 'var(--rg-charcoal, #2B2B2B)', letterSpacing: '-0.01em' }}>Rio Grande</text>
      <text x="2" y="68" style={{ fontFamily: "var(--font-sans), system-ui, sans-serif", fontWeight: 600, fontSize: 11, letterSpacing: '0.32em', fill: 'var(--rg-clay-700, #A55B45)', textTransform: 'uppercase' }}>WEBSITES</text>
      <circle cx="200" cy="20" r="5" fill="var(--rg-turq-500, #49B8B1)" />
    </svg>
  );
}

// ----- Eyebrow -----
function Eyebrow({ children }) {
  return <span className="eyebrow">{children}</span>;
}

// ----- Buttons -----
function Button({ children, variant = 'primary', icon, onClick }) {
  return (
    <button className={`btn btn-${variant}`} onClick={onClick}>
      {children}
      {icon && <Icon name={icon} size={16} />}
    </button>
  );
}

// ----- Nav -----
function Nav({ page, setPage }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 64);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // Close on Escape; lock body scroll while open
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [menuOpen]);
  // Close menu when navigating to a new page
  const go = (k) => { setPage(k); setMenuOpen(false); };
  const items = [
    ['home', 'Home'], ['services', 'Services'],
    ['about', 'About'], ['contact', 'Contact'],
  ];
  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="nav-brand" onClick={() => go('home')}>
          <Logo />
        </div>
        <div className="nav-links">
          {items.map(([k, label]) => (
            <a key={k} className={`nav-link ${page === k ? 'active' : ''}`} onClick={(e) => { e.preventDefault(); go(k); }}>
              {label}
            </a>
          ))}
        </div>
        <a className="nav-cta" onClick={() => go('contact')}>
          Start a project
          <Icon name="arrow-up-right" size={14} stroke={2.25} />
        </a>
        <button
          type="button"
          className="nav-toggle"
          aria-label={menuOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={menuOpen}
          aria-controls="mobile-drawer"
          onClick={() => setMenuOpen((v) => !v)}
        >
          <Icon name={menuOpen ? 'x' : 'menu'} size={22} stroke={2} />
        </button>
      </nav>
      <div
        id="mobile-drawer"
        className={`nav-drawer ${menuOpen ? 'open' : ''}`}
        aria-hidden={!menuOpen}
      >
        <div className="nav-drawer-inner">
          <ul className="nav-drawer-links">
            {items.map(([k, label]) => (
              <li key={k}>
                <a
                  className={page === k ? 'active' : ''}
                  onClick={(e) => { e.preventDefault(); go(k); }}
                  tabIndex={menuOpen ? 0 : -1}
                >
                  {label}
                </a>
              </li>
            ))}
          </ul>
          <a className="nav-drawer-cta" onClick={() => go('contact')} tabIndex={menuOpen ? 0 : -1}>
            Start a project
            <Icon name="arrow-up-right" size={16} stroke={2.25} />
          </a>
        </div>
      </div>
    </>
  );
}

// ----- Footer -----
function Footer({ setPage }) {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div className="footer-brand">
          <Logo height={40} />
          <p>A local web team in Las Cruces, New Mexico. Clean, modern, affordable websites for small businesses and individuals.</p>
        </div>
        <div>
          <h5>Studio</h5>
          <ul>
            <li><a onClick={() => setPage('about')}>About</a></li>
            <li><a onClick={() => setPage('services')}>Services</a></li>
            <li><a onClick={() => setPage('contact')}>Contact</a></li>
          </ul>
        </div>
        <div>
          <h5>Services</h5>
          <ul>
            <li><a onClick={() => setPage('services')}>Design &amp; development</a></li>
            <li><a onClick={() => setPage('services')}>Hosting</a></li>
            <li><a onClick={() => setPage('services')}>Landing pages</a></li>
            <li><a onClick={() => setPage('services')}>Maintenance</a></li>
          </ul>
        </div>
        <div>
          <h5>Contact</h5>
          <ul>
            <li><a href="mailto:riograndeweb22@gmail.com">riograndeweb22@gmail.com</a></li>
            <li><a>Las Cruces, NM</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Rio Grande Websites · Las Cruces, <em>NM</em>.</span>
        <span>All rights reserved.</span>
      </div>
    </footer>
  );
}

// ----- Image plate -----
function ImagePlate({ src, ratio = '4/5', radius = 'var(--r-2xl)', shift }) {
  return (
    <div style={{
      aspectRatio: ratio,
      borderRadius: radius,
      backgroundImage: `url(${src})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      boxShadow: 'var(--shadow-md)',
      transform: shift,
    }} />
  );
}

// ----- Reveal-on-scroll -----
// Adds .is-visible the first time the element crosses ~15% into view.
// Once visible, we stop observing — reveals never re-fire on re-scroll.
function useReveal(options = {}) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) { el.classList.add('is-visible'); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          el.classList.add('is-visible');
          io.unobserve(el);
        }
      });
    }, { threshold: options.threshold ?? 0.15, rootMargin: options.rootMargin ?? '0px 0px -8% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, as: Tag = 'div', stagger = false, className = '', ...rest }) {
  const ref = useReveal();
  const cls = [stagger ? 'reveal-stagger' : 'reveal', className].filter(Boolean).join(' ');
  return <Tag ref={ref} className={cls} {...rest}>{children}</Tag>;
}

// ----- Marquee — duplicate group inline so the -50% loop is seamless -----
function Marquee({ items }) {
  const Group = ({ ariaHidden }) => (
    <div className="marquee-group" aria-hidden={ariaHidden ? 'true' : undefined}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <span>{it}</span>
          <span className="dot" aria-hidden="true" />
        </React.Fragment>
      ))}
    </div>
  );
  return (
    <div className="clients" role="region" aria-label="What we build for">
      <div className="marquee">
        <Group />
        <Group ariaHidden />
      </div>
    </div>
  );
}

// expose
Object.assign(window, { Icon, Logo, Eyebrow, Button, Nav, Footer, ImagePlate, Reveal, useReveal, Marquee });
