// Chrome.jsx — Nav, Footer, Reel modal. Shared across all pages and both directions.
const { useState: useStateChrome, useEffect: useEffectChrome } = React;

// useIsMobile — exposed on window so every page/component can react to viewport.
// Breakpoint: phones and small tablets ≤ 768px width.
function useIsMobile(breakpoint = 768) {
  const query = `(max-width: ${breakpoint}px)`;
  const [match, setMatch] = useStateChrome(() =>
    typeof window !== 'undefined' && typeof window.matchMedia === 'function'
      ? window.matchMedia(query).matches
      : false
  );
  useEffectChrome(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
    const mq = window.matchMedia(query);
    const onChange = (e) => setMatch(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', onChange);
    else mq.addListener(onChange);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', onChange);
      else mq.removeListener(onChange);
    };
  }, [query]);
  return match;
}
window.useIsMobile = useIsMobile;

// Minimal sun/moon icon set — pure SVG, no font dependency.
function SunIcon({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
    </svg>);

}
function MoonIcon({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>);

}

function Nav({ onNavigate, current, variant = 'light', theme = 'light', onToggleTheme, hidden = false }) {
  const items = [
  { id: 'home', label: 'main' },
  { id: 'work', label: 'work' },
  { id: 'about', label: 'about' },
  // { id: 'play', label: 'play' },  // hidden — page kept; nav entry restorable
  ];

  const dark = variant === 'dark';
  const isMobile = useIsMobile();
  return (
    <div style={{
      position: 'sticky', top: 16, zIndex: 30,
      display: 'flex', justifyContent: 'center',
      padding: isMobile ? '0 12px' : '0 24px',
      pointerEvents: 'none',
      marginBottom: -76,
      opacity: hidden ? 0 : 1,
      transform: hidden ? 'translateY(-12px)' : 'translateY(0)',
      transition: 'opacity 380ms cubic-bezier(0.2,0.6,0.2,1), transform 380ms cubic-bezier(0.2,0.6,0.2,1)',
    }}>
    <nav style={{
        pointerEvents: hidden ? 'none' : 'auto',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'space-between',
        gap: isMobile ? 14 : 26,
        padding: isMobile ? '6px 8px 6px 12px' : '7px 10px 7px 16px',
        borderRadius: 999,
        background: dark ? 'rgba(10,11,13,0.55)' : 'rgba(255,255,255,0.62)',
        backdropFilter: 'blur(22px) saturate(180%)',
        WebkitBackdropFilter: 'blur(22px) saturate(180%)',
        border: `1px solid ${dark ? 'rgba(255,255,255,0.14)' : 'rgba(10,11,13,0.08)'}`,
        boxShadow: dark ?
        '0 6px 24px rgba(0,0,0,0.45), 0 1px 0 rgba(255,255,255,0.06) inset' :
        '0 6px 24px rgba(10,11,13,0.10), 0 1px 0 rgba(255,255,255,0.7) inset',
        fontFamily: "'PP Neue Montreal', 'Geist', system-ui, sans-serif",
        color: dark ? '#fff' : '#0a0b0d',
        maxWidth: isMobile ? 'calc(100vw - 24px)' : 'none',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 12 : 20 }}>
        <div onClick={() => onNavigate('home')}
          style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer' }}>
          <img src="site/assets/Akaliko_Square_Small.gif"
            alt=""
            style={{ width: 20, height: 20, display: 'block' }} />
          {!isMobile && (
            <span style={{ fontFamily: "'PP Neue Montreal', 'Geist', system-ui, sans-serif", fontSize: 12, letterSpacing: '-0.01em', fontWeight: 500 }}>
              akaliko8
            </span>
          )}
        </div>
        <div style={{ display: 'flex', gap: isMobile ? 12 : 19 }}>
          {items.map((it) =>
            <a key={it.id}
            onClick={() => onNavigate(it.id)}
            style={{
              fontSize: 11, fontWeight: 500, cursor: 'pointer',
              color: current === it.id ? '#0052ff' : 'inherit',
              transition: 'color 120ms cubic-bezier(0.2,0.6,0.2,1)',
              textTransform: 'lowercase'
            }}>
              {it.label}
            </a>
            )}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 7, alignItems: 'center' }}>
        <button onClick={onToggleTheme}
          aria-label={theme === 'dark' ? 'switch to light' : 'switch to dark'}
          title={theme === 'dark' ? 'switch to light' : 'switch to dark'}
          style={{
            width: 26, height: 26, borderRadius: '50%',
            border: `1px solid ${dark ? 'rgba(255,255,255,0.20)' : 'rgba(10,11,13,0.18)'}`,
            background: 'transparent',
            color: dark ? '#fff' : '#0a0b0d',
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background 200ms cubic-bezier(0.2,0.6,0.2,1), border-color 200ms'
          }}
          onMouseEnter={(e) => {e.currentTarget.style.background = dark ? 'rgba(255,255,255,0.08)' : 'rgba(10,11,13,0.06)';}}
          onMouseLeave={(e) => {e.currentTarget.style.background = 'transparent';}}>
          {theme === 'dark' ? <SunIcon size={12} /> : <MoonIcon size={12} />}
        </button>
        {current === 'home' && (
        <button className="ak-btn ak-btn--lower"
          onClick={() => onNavigate('reel')}
          style={{
            padding: '7px 13px', fontSize: 11,
            background: dark ? '#fff' : '#0a0b0d',
            borderColor: dark ? '#fff' : '#0a0b0d',
            color: dark ? '#0a0b0d' : '#fff',
            display: 'inline-flex', alignItems: 'center', gap: 5
          }}>
          <span className="ak-icon" style={{ fontSize: 12 }}>play_arrow</span>
          play reel
        </button>
        )}
      </div>
    </nav>
    </div>);

}

function ContactBtn({ onNavigate, dark }) {
  const [hover, setHover] = useStateChrome(false);
  const blue = '#0052ff';
  return (
    <button className="ak-btn ak-btn--lower"
    onClick={() => onNavigate('contact')}
    onMouseEnter={() => setHover(true)}
    onMouseLeave={() => setHover(false)}
    style={{
      padding: '10px 18px', fontSize: 13,
      background: hover ? blue : 'transparent',
      borderColor: blue,
      color: hover ? '#fff' : dark ? '#fff' : blue,
      display: 'inline-flex', alignItems: 'center', gap: 6
    }}>
      get in touch <span className="ak-arrow-target">↗</span>
    </button>);

}

function Footer({ onNavigate }) {
  const isMobile = useIsMobile();
  return (
    <footer style={{
      background: 'var(--ak-bg)', color: 'var(--ak-fg)',
      borderTop: '1px solid var(--ak-line)',
      padding: isMobile ? '36px 20px 20px' : '96px 32px 32px',
      fontFamily: "'PP Neue Montreal', 'Geist', system-ui, sans-serif"
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr 1fr' : '2fr 1fr 1fr 1fr',
          gap: isMobile ? 14 : 48,
          padding: isMobile ? '0 0 20px' : '0 0 48px'
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: isMobile ? 6 : 12, gridColumn: isMobile ? '1 / -1' : 'auto', marginBottom: isMobile ? 4 : 0 }}>
          <img src="site/assets/akaliko-logo.png"
            alt=""
            style={{ width: 36, height: 36, display: 'block' }} />
            <div style={{ fontFamily: "'PP Neue Montreal', 'Geist', system-ui, sans-serif", fontSize: 24, letterSpacing: '-0.02em' }}>
              akaliko8
            </div>
            <div style={{ fontSize: 13, color: 'var(--ak-fg-2)', maxWidth: 280, lineHeight: 1.5 }}>
              new media · creative direction<br />
              New York / Bangkok
            </div>
          </div>
          <FooterCol heading="navigate" items={[
          { label: 'main', onClick: () => onNavigate('home') },
          { label: 'work', onClick: () => onNavigate('work') },
          { label: 'about', onClick: () => onNavigate('about') },
          // { label: 'play', onClick: () => onNavigate('play') },  // hidden — page kept
          ]
          } />
          <FooterCol heading="elsewhere" items={SITE.social.map((s) => ({ label: s.label + ' ↗', href: s.href, external: true }))} />
          <FooterCol heading="contact" items={[
          { label: 'get in touch', onClick: () => onNavigate('contact') },
          { label: SITE.bookingStatus, muted: true }]
          } />
        </div>

        <div style={{
          paddingTop: 24,
          borderTop: '1px solid var(--ak-line)',
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          gap: isMobile ? 8 : 0,
          justifyContent: 'space-between',
          fontFamily: "'JetBrains Mono', SFMono-Regular, Menlo, monospace",
          fontSize: 11,
          color: 'var(--ak-fg-2)',
          letterSpacing: '0.04em'
        }}>
          <div>© {SITE.fullName} · {SITE.yearStart}—{SITE.yearNow}</div>
          <div>v8.0 · last touched {SITE.yearNow}</div>
        </div>
      </div>
    </footer>);

}

function FooterCol({ heading, items }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: isMobile ? 4 : 8 }}>
      <div style={{
        fontSize: 11, fontWeight: 700, letterSpacing: '0.14em',
        textTransform: 'uppercase', color: 'var(--ak-fg-2)',
        marginBottom: isMobile ? 2 : 4
      }}>
        {heading}
      </div>
      {items.map((it, i) =>
      <a key={i}
      href={it.href}
      onClick={it.onClick}
      target={it.external ? '_blank' : undefined}
      rel={it.external ? 'noopener noreferrer' : undefined}
      style={{
        fontSize: 14,
        color: it.muted ? 'var(--ak-fg-2)' : 'var(--ak-fg)',
        cursor: it.onClick || it.href ? 'pointer' : 'default',
        textTransform: 'lowercase',
        textDecoration: 'none'
      }}>
          {it.label}
        </a>
      )}
    </div>);

}

function ReelOverlay({ onClose }) {
  const VIDEO_ID = 'OpSnYqQXM2M';
  const iframeRef = window.React.useRef(null);

  useEffectChrome(() => {
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // Listen for YouTube IFrame API postMessage events. When playerState === 0
  // (ENDED), close the overlay automatically.
  useEffectChrome(() => {
    const iframe = iframeRef.current;
    if (!iframe) return;

    // Subscribe to onStateChange events from the embed.
    const subscribe = () => {
      try {
        iframe.contentWindow.postMessage(
          JSON.stringify({ event: 'listening', id: 1, channel: 'widget' }),
          '*'
        );
        iframe.contentWindow.postMessage(
          JSON.stringify({ event: 'command', func: 'addEventListener', args: ['onStateChange'] }),
          '*'
        );
      } catch (e) {/* iframe not yet ready */}
    };

    const onMessage = (e) => {
      if (typeof e.data !== 'string') return;
      let data;
      try {data = JSON.parse(e.data);} catch {return;}
      if (data.event === 'onReady') {
        subscribe();
      }
      // YT.PlayerState.ENDED === 0
      if (data.event === 'onStateChange' && data.info === 0) {
        onClose();
      }
    };

    window.addEventListener('message', onMessage);
    // Also try subscribing on load, in case onReady is missed.
    const t = setTimeout(subscribe, 800);
    return () => {
      window.removeEventListener('message', onMessage);
      clearTimeout(t);
    };
  }, [onClose]);

  // enablejsapi=1 lets us receive state events; autoplay=1 + mute=0 plays with
  // sound (allowed because this opens in response to a user click).
  const SI = 'YiUEkOtuk5T089sP';
  const src = `https://www.youtube.com/embed/${VIDEO_ID}` +
  `?si=${SI}` +
  `&autoplay=1&mute=0&controls=1&rel=0&modestbranding=1` +
  `&playsinline=1&enablejsapi=1`;

  return (
    <div onClick={onClose}
    style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(10,11,13,0.94)',
      backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 48,
      animation: 'akFadeIn 200ms cubic-bezier(0.2,0.6,0.2,1)'
    }}>
      <div onClick={(e) => e.stopPropagation()}
      style={{
        width: '100%', maxWidth: 1200, aspectRatio: '16/9',
        background: '#000', borderRadius: 16,
        position: 'relative', overflow: 'hidden',
        boxShadow: '0 40px 120px rgba(0,0,0,0.6)'
      }}>
        <iframe
          ref={iframeRef}
          src={src}
          title="YouTube video player"
          frameBorder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          referrerPolicy="strict-origin-when-cross-origin"
          allowFullScreen
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            border: 0
          }} />
        {/* meta */}
        <div style={{
          position: 'absolute', top: 16, left: 16,
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 11, color: 'rgba(255,255,255,0.7)',
          letterSpacing: '0.12em', textTransform: 'uppercase',
          pointerEvents: 'none',
          textShadow: '0 1px 4px rgba(0,0,0,0.6)'
        }}>
          reel · {SITE.yearNow} · {SITE.reelDuration}
        </div>
        <button onClick={onClose}
        style={{
          position: 'absolute', top: 12, right: 12,
          width: 40, height: 40, borderRadius: '50%',
          background: 'rgba(0,0,0,0.55)', color: '#fff',
          border: '1px solid rgba(255,255,255,0.18)',
          cursor: 'pointer', fontSize: 16,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 2
        }}>
          ✕
        </button>
      </div>
    </div>);

}

window.Nav = Nav;
window.Footer = Footer;
window.ReelOverlay = ReelOverlay;