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

// ===================================================================
// Icon
// ===================================================================
const Icon = ({ name, size = 14 }) => {
  const stroke = 'currentColor';
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke, strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'arrow-right': return <svg {...props}><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>;
    case 'arrow-up-right': return <svg {...props}><path d="M7 17 17 7"/><path d="M7 7h10v10"/></svg>;
    case 'play': return <svg {...props}><polygon points="5 3 19 12 5 21 5 3" fill="currentColor" stroke="none"/></svg>;
    case 'play-line': return <svg {...props}><polygon points="5 3 19 12 5 21 5 3"/></svg>;
    case 'grid': return <svg {...props}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>;
    case 'list': return <svg {...props}><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="4" cy="6" r="1" fill="currentColor"/><circle cx="4" cy="12" r="1" fill="currentColor"/><circle cx="4" cy="18" r="1" fill="currentColor"/></svg>;
    case 'pin': return <svg {...props}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0Z"/><circle cx="12" cy="10" r="3"/></svg>;
    case 'mail': return <svg {...props}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 5L2 7"/></svg>;
    case 'phone': return <svg {...props}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>;
    case 'check': return <svg {...props}><polyline points="20 6 9 17 4 12"/></svg>;
    case 'star': return <svg {...props}><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" fill="currentColor" stroke="none"/></svg>;
    case 'instagram': return <svg {...props}><rect x="2" y="2" width="20" height="20" rx="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>;
    case 'vimeo': return <svg {...props} viewBox="0 0 24 24"><path d="M22 6.7c-.1 2-1.5 4.7-4.2 8.2C15 18.6 12.5 20.4 10.5 20.4c-1.2 0-2.3-1.1-3.1-3.4l-1.7-6.3C5 8.3 4.4 7.1 3.7 7.1c-.2 0-.6.2-1.4.7l-.8-1.1c2.2-2 4.4-4.2 5.6-4.3 1.5-.2 2.5.9 2.9 3.1.4 2.5.7 4 .9 4.7.5 2 1 3 1.6 3 .5 0 1.2-.7 2.2-2.2.9-1.5 1.5-2.6 1.6-3.5.2-1.4-.4-2.1-1.7-2.1-.6 0-1.3.1-2 .4 1.3-4.2 3.7-6.2 7.4-6.1 2.6.1 3.9 1.9 4 5.3z" fill="currentColor" stroke="none"/></svg>;
    case 'linkedin': return <svg {...props}><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/></svg>;
    case 'pause': return <svg {...props}><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>;
    case 'plus': return <svg {...props}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>;
    case 'close': return <svg {...props}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>;
    case 'alert': return <svg {...props}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>;
    default: return null;
  }
};

// ===================================================================
// Cursor — custom blue dot with hover labels
// ===================================================================
function CustomCursor() {
  const ref = useRef(null);
  const labelRef = useRef('');
  useEffect(() => {
    // Skip on touch devices and when user prefers no fine pointer
    if (typeof window === 'undefined') return;
    const isTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
    const fine = window.matchMedia && window.matchMedia('(pointer: fine)').matches;
    if (isTouch || !fine) return;
    const cursor = ref.current;
    let raf = 0, x = 0, y = 0;
    const move = (e) => {
      x = e.clientX; y = e.clientY;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        cursor.style.left = x + 'px';
        cursor.style.top = y + 'px';
      });
    };
    const over = (e) => {
      const t = e.target.closest('[data-hover]');
      if (t) {
        cursor.classList.add('is-hover');
        cursor.setAttribute('data-label', t.getAttribute('data-hover'));
      } else {
        cursor.classList.remove('is-hover');
        cursor.setAttribute('data-label', '');
      }
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseover', over);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseover', over); cancelAnimationFrame(raf); };
  }, []);
  return <div ref={ref} className="vf-cursor" data-label=""/>;
}

// ===================================================================
// Video modal — reuses .vf-player shell, embeds an iframe.
// Used by WatchReelButton and (when playing) the WorkPlayer.
// ===================================================================
function VideoModal({ url, title, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    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;
    };
  }, [onClose]);
  const src = url.includes('?') ? url : `${url}?autoplay=1&title=0&byline=0&portrait=0`;
  return (
    <div className="vf-player" role="dialog" aria-modal="true" aria-label={title || 'Video player'} onClick={onClose}>
      <div className="vf-video-shell" onClick={(e) => e.stopPropagation()}>
        <button className="vf-video-close" type="button" onClick={onClose} aria-label="Close" data-hover="Close">
          <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
            <path d="M3 3 L13 13 M13 3 L3 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
        </button>
        <iframe
          className="vf-video-frame"
          src={src}
          title={title || 'Valley Films reel'}
          allow="autoplay; fullscreen; picture-in-picture"
          allowFullScreen
          frameBorder="0"
        />
      </div>
    </div>
  );
}

// ===================================================================
// Watch reel button — opens the studio reel in the same WorkPlayer
// modal that production tiles use, so the player chrome is consistent.
// ===================================================================
const REEL_WORK = {
  id: '__reel__',
  title: 'Valley Films Reel',
  client: 'Valley Films',
  type: 'Showreel',
  tags: ['Showreel'],
  videoUrl: REEL_URL,
  description: 'A selection of recent commercial, brand and documentary work, cut by the Valley Films team.',
};

function WatchReelButton({ className = 'btn-ghost', children }) {
  const [open, setOpen] = useState(false);
  return (
    <React.Fragment>
      <button className={className} type="button" data-hover="Play" onClick={() => setOpen(true)}>
        {children || <><Icon name="play-line" size={11}/> Watch reel</>}
      </button>
      {open && <WorkPlayer work={REEL_WORK} onClose={() => setOpen(false)}/>}
    </React.Fragment>
  );
}

// ===================================================================
// Nav
// ===================================================================
function Nav({ page, isRentals, rentalsSection }) {
  const isLight = page === 'contact' || page === 'rentals';
  const active = (p) => page === p ? 'active' : '';
  const activeSub = (s) => isRentals && rentalsSection === s ? 'active' : '';
  const filmsLogo = isLight ? 'assets/logo-black.png' : 'assets/logo-white.png';
  const rentalsLogo = 'assets/rentals-logo-blue.png';
  const [menuOpen, setMenuOpen] = useState(false);

  // Close the mobile drawer whenever the active page (or rentals sub-page) changes.
  useEffect(() => { setMenuOpen(false); }, [page, rentalsSection]);

  // While the drawer is open: lock body scroll and listen for Escape.
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <nav className={`nav ${isLight ? 'is-light' : ''} ${isRentals ? 'is-rentals' : ''} ${menuOpen ? 'is-open' : ''}`}>
      <a className="brand" href={isRentals ? '/rentals' : '/'} data-hover="Home" aria-label={isRentals ? 'Valley Rentals home' : 'Valley Films home'} onClick={closeMenu}>
        {isRentals ? (
          <img className="brand-logo brand-full" src={rentalsLogo} alt="Valley Rentals"/>
        ) : (
          <img className="brand-logo brand-full" src={filmsLogo} alt="Valley Films"/>
        )}
      </a>
      <button
        type="button"
        className="nav-burger"
        aria-label={menuOpen ? 'Close menu' : 'Open menu'}
        aria-expanded={menuOpen}
        aria-controls="primary-nav"
        onClick={() => setMenuOpen((o) => !o)}
      >
        <span aria-hidden="true"/>
        <span aria-hidden="true"/>
        <span aria-hidden="true"/>
      </button>
      <div id="primary-nav" className="menu">
        {isRentals ? (
          <React.Fragment>
            <a className={!rentalsSection ? 'active' : ''} href="/rentals" data-hover="View" onClick={closeMenu}>Home</a>
            <a className={activeSub('equipment')} href="/rentals/equipment" data-hover="View" onClick={closeMenu}>Equipment</a>
            <a className={activeSub('contact')} href="/rentals/contact" data-hover="View" onClick={closeMenu}>Contact</a>
            <a className={`menu-cta ${activeSub('open-account')}`} href="/rentals/open-account" data-hover="View" onClick={closeMenu}>Open Account</a>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <a className={active('home')} href="/" data-hover="View" onClick={closeMenu}>Home</a>
            <a className={active('services')} href="/services" data-hover="View" onClick={closeMenu}>Services</a>
            <a className={active('about')} href="/about" data-hover="View" onClick={closeMenu}>About</a>
            <a className={`menu-cta ${active('contact')}`} href="/contact" data-hover="Send" onClick={closeMenu}>Contact</a>
          </React.Fragment>
        )}
      </div>
    </nav>
  );
}

Object.assign(window, { Icon, CustomCursor, VideoModal, WatchReelButton, REEL_WORK, Nav });
