// Shared page chrome for all four pages. Consumes window.Theme for
// persistence logic; components here are browser-only (JSX).
//
// The whole file is wrapped in an IIFE so it contributes NO top-level bindings.
// Files here share one global scope, and `const {...} = React` at top level only
// survives today because Babel-standalone's default `env` preset downlevels
// const to var. Adding data-presets="react" or data-type="module" would turn a
// duplicate destructure into a fatal redeclaration SyntaxError. The body is left
// un-indented deliberately, to keep this a two-line diff.
(function () {
const { useState, useEffect, useRef, useCallback } = React;

// Returns 'dark'/'light' only when the visitor made an explicit choice.
function storedChoice() {
  try {
    const v = localStorage.getItem(window.Theme.STORAGE_KEY);
    return (v === 'dark' || v === 'light') ? v : null;
  } catch (e) { return null; }
}

function systemPrefersDark() {
  return !!(window.matchMedia
    && window.matchMedia('(prefers-color-scheme: dark)').matches);
}

function useTheme() {
  const [theme, setTheme] = useState(() => {
    if (typeof window === 'undefined') return 'light';
    return window.Theme.resolveTheme(storedChoice(), systemPrefersDark());
  });
  const [explicit, setExplicit] = useState(
    () => typeof window !== 'undefined' && storedChoice() !== null);

  const toggle = useCallback(() => {
    setExplicit(true);
    setTheme((prev) => {
      const next = prev === 'dark' ? 'light' : 'dark';
      window.Theme.applyTheme(next, document.documentElement, window.localStorage);
      return next;
    });
  }, []);

  // Only PIN data-theme when there is an explicit choice. With nothing stored
  // the attribute must stay absent, or it shadows theme.css's
  // `@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) }`
  // and the system preference stops being the default. The inline no-flash
  // script in <head> follows the same rule, so the two agree.
  useEffect(() => {
    const root = document.documentElement;
    if (explicit) root.setAttribute('data-theme', theme);
    else root.removeAttribute('data-theme');
  }, [theme, explicit]);

  // Follow the OS live while no explicit choice is stored, so an auto-dark
  // visitor whose OS flips at sunset does not have to reload.
  useEffect(() => {
    if (explicit || typeof window === 'undefined' || !window.matchMedia) return;
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = (e) => setTheme(e.matches ? 'dark' : 'light');
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, [explicit]);

  return [theme, toggle];
}

function ThemeToggle() {
  const [theme, toggle] = useTheme();
  const isDark = theme === 'dark';
  return (
    <button
      type="button"
      className="chrome-toggle"
      onClick={toggle}
      aria-label={isDark ? 'Switch to light theme' : 'Switch to dark theme'}
      title={isDark ? 'Switch to light theme' : 'Switch to dark theme'}
    >
      <i className={`ti ${isDark ? 'ti-sun' : 'ti-moon'}`} aria-hidden="true" />
    </button>);

}

const BRAND_NAME = 'Hamza Tahir';
const BRAND_KEEP = [1, 9]; // the 'a' of Hamza and the 'i' of Tahir

function BrandMark() {
  const segs = window.Brand.splitBrand(BRAND_NAME, BRAND_KEEP);
  return (
    <a className="chrome-brand" href="Syed%20Hamza%20Tahir%20-%20Home.html" aria-label={BRAND_NAME}>
      <span className="chrome-mark" aria-hidden="true">00</span>
      <span className="chrome-word">
        {segs.map((s, i) =>
          <span key={i} className={s.keep ? 'cw-keep' : 'cw-fill'}>{s.text}</span>
        )}
      </span>
    </a>);

}

function Frame() {
  return (
    <div className="chrome-frame" aria-hidden="true">
      <span className="cf-v cf-l" /><span className="cf-v cf-r" />
      <span className="cf-h cf-t" /><span className="cf-h cf-b" />
      <i className="cf-tick cf-tl" /><i className="cf-tick cf-tr" />
      <i className="cf-tick cf-bl" /><i className="cf-tick cf-br" />
    </div>);

}

const NAV_EMAIL = 'syedhamzatahir1001@gmail.com';
const NAV_ITEMS = [
  { label: 'Home', href: 'Syed%20Hamza%20Tahir%20-%20Home.html' },
  { label: 'Work', href: 'AI Portfolio.html' },
  { label: 'Blog', href: 'Writing.html' }
];

// Every page aligns its nav to --wrap-x, the same content inset the page body
// uses, so there is no per-page variant any more. This used to take a `framed`
// prop that swapped in .chrome-nav-plain for the unframed pages, back when they
// centred their content in a 92%/1180px column instead.
function Nav({ active }) {
  const [open, setOpen] = useState(false);
  const triggerRef = useRef(null);
  const sheetRef = useRef(null);

  // Escape closes and returns focus to the trigger.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') { setOpen(false); if (triggerRef.current) triggerRef.current.focus(); }
    };
    const onDown = (e) => {
      if (sheetRef.current && !sheetRef.current.contains(e.target)
        && triggerRef.current && !triggerRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onDown);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onDown);
    };
  }, [open]);

  // Move focus into the sheet when it opens.
  useEffect(() => {
    if (open && sheetRef.current) {
      const first = sheetRef.current.querySelector('a');
      if (first) first.focus();
    }
  }, [open]);

  return (
    <header className="chrome-nav">
      <BrandMark />
      <nav className="cn-links" aria-label="Primary navigation">
        {NAV_ITEMS.map((i) =>
          <a key={i.label} href={i.href}
            aria-current={i.label === active ? 'page' : undefined}>{i.label}</a>
        )}
      </nav>
      <div className="cn-right">
        <a className="cn-contact" href={'mailto:' + NAV_EMAIL} data-barba-prevent>Contact</a>
        <ThemeToggle />
        <button type="button" className="cn-burger" ref={triggerRef}
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open} aria-controls="cn-sheet"
          aria-label={open ? 'Close menu' : 'Open menu'}>
          <i className={`ti ${open ? 'ti-x' : 'ti-menu-2'}`} aria-hidden="true" />
        </button>
      </div>
      <div id="cn-sheet" ref={sheetRef}
        className={`cn-sheet${open ? ' is-open' : ''}`} aria-hidden={!open}>
        {NAV_ITEMS.map((i) =>
          <a key={i.label} href={i.href} tabIndex={open ? 0 : -1}
            aria-current={i.label === active ? 'page' : undefined}
            onClick={() => setOpen(false)}>{i.label}</a>
        )}
      </div>
    </header>);

}

window.Chrome = { useTheme, ThemeToggle, BrandMark, Frame, Nav };
})();
