// Shared UI primitives + small layout helpers.
// Exports to window so each page-script can use them.

// Path router — minimal. Every page is a real URL (scripts/build.mjs writes an HTML file for
// each), and clicks on internal links are turned into history pushes so the app stays loaded.
function useRoute() {
  const [route, setRoute] = React.useState(currentRoute);
  React.useEffect(() => {
    const onPop = () => setRoute(currentRoute());
    const onGo = () => { setRoute(currentRoute()); window.scrollTo(0, 0); };
    window.addEventListener('popstate', onPop);
    window.addEventListener('routechange', onGo);
    document.addEventListener('click', interceptLinkClick);
    return () => {
      window.removeEventListener('popstate', onPop);
      window.removeEventListener('routechange', onGo);
      document.removeEventListener('click', interceptLinkClick);
    };
  }, []);
  return route;
}

function currentRoute() {
  return parseRoute(window.location.pathname, window.location.search);
}

function parseRoute(pathname, search) {
  const segments = pathname.split('/').filter(Boolean).map(decodeURIComponent);
  const query = Object.fromEntries(new URLSearchParams(search));
  return { path: '/' + segments.join('/'), segments, query };
}

function go(path) {
  window.history.pushState(null, '', path);
  window.dispatchEvent(new Event('routechange'));
}

// Plain left-clicks on same-site page links navigate in-app. Files (CV, sitemap), new-tab
// clicks and in-page #anchors fall through to the browser.
function interceptLinkClick(e) {
  if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
  const a = e.target.closest('a[href]');
  if (!a || a.target || a.hasAttribute('download')) return;
  const url = new URL(a.href);
  if (url.origin !== window.location.origin || /\.[a-z0-9]+$/i.test(url.pathname)) return;
  if (url.pathname === window.location.pathname && url.search === window.location.search && url.hash) return;
  e.preventDefault();
  go(url.pathname + url.search + url.hash);
}

// ── Nav ───────────────────────────────────────────────
function Nav({ route, onTheme }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => { setMenuOpen(false); }, [route.path]);

  const links = [
    { to: '/', label: 'Home' },
    { to: '/writing', label: 'Writing' },
    { to: '/papers', label: 'Papers' },
    { to: '/about', label: 'About' },
  ];

  return (
    <>
      <header className="nav">
        <a className="nav-brand" href="/">
          <img src="/icon-192.png" alt="" width="28" height="28" />
          adithyav.dev
        </a>
        <div className="nav-end">
          <nav className="nav-links">
            {links.map((l) => (
              <a key={l.to} href={l.to.replace(/\/?$/, '/')} className={isActive(route, l.to) ? 'active' : ''}>
                {l.label}
              </a>
            ))}
          </nav>
          <button className="icon-btn" onClick={onTheme} title="Toggle light / dark" aria-label="Toggle light / dark">
            ◐
          </button>
          <button className="icon-btn nav-mobile-toggle" onClick={() => setMenuOpen(!menuOpen)} aria-label="Menu">
            {menuOpen ? '✕' : '≡'}
          </button>
        </div>
      </header>
      {menuOpen && (
        <div className="mobile-menu">
          {links.map((l) => (
            <a key={l.to} href={l.to.replace(/\/?$/, '/')}>{l.label}</a>
          ))}
          <a href="/Adithya-Venkateswaran-CV.pdf" target="_blank" rel="noopener">CV ↓</a>
        </div>
      )}
    </>
  );
}

function isActive(route, to) {
  if (to === '/') return route.path === '/' || route.path === '';
  return route.path === to || route.path.startsWith(to + '/');
}

// ── Footer ───────────────────────────────────────────
function Foot() {
  return (
    <footer className="foot">
      <div>© {new Date().getFullYear()} {SITE.fullName}</div>
      <nav>
        <a href={`https://github.com/${CONTACT.github}`} target="_blank" rel="noopener">GitHub</a>
        <a href={`https://gitlab.com/${CONTACT.gitlab}`} target="_blank" rel="noopener">GitLab</a>
        <a href={`https://linkedin.com/in/${CONTACT.linkedin}`} target="_blank" rel="noopener">LinkedIn</a>
        <a href={`mailto:${CONTACT.email}`}>Email</a>
        <a href="/feed.xml">RSS</a>
        <span className="dev-only-inline mono" style={{ color: 'var(--sk-carrot-strong)' }}>dev: {BUILD ? BUILD.hash : 'local'}</span>
      </nav>
    </footer>
  );
}

// Date ranges in data.js are written several ways ("2025-11 → present", "2022-11 — 2025-11",
// "2021-2022"); they are all shown in one form, with a spaced en dash. Projects without dates
// give an empty string.
function fmtWindow(w) {
  if (!w) return '';
  return w.replace(/\s*[→—–]\s*/, ' – ').replace(/^(\d{4})-(\d{4})$/, '$1 – $2');
}

// ── Code window with character-by-character typing animation ────
function CodeWindow({ file = 'adithya.tsx', lines, loop = true, style }) {
  const reduced = useReducedMotion();
  const fullText = React.useMemo(() => lines.map(linesToString).join('\n'), [lines]);
  const [typed, setTyped] = React.useState(reduced ? fullText : '');

  React.useEffect(() => {
    if (reduced) { setTyped(fullText); return; }
    let cancelled = false;
    let cursor = 0;
    const CHARS_PER_FRAME = 2.4; // ~145 chars/sec at 60fps
    let raf;
    let restartId;

    function step() {
      if (cancelled) return;
      cursor += CHARS_PER_FRAME;
      const i = Math.min(Math.floor(cursor), fullText.length);
      setTyped(fullText.slice(0, i));
      if (i >= fullText.length) {
        if (loop) {
          restartId = setTimeout(() => {
            if (cancelled) return;
            cursor = 0;
            setTyped('');
            raf = requestAnimationFrame(step);
          }, 3600);
        }
        return;
      }
      raf = requestAnimationFrame(step);
    }
    raf = requestAnimationFrame(step);

    return () => {
      cancelled = true;
      if (raf) cancelAnimationFrame(raf);
      if (restartId) clearTimeout(restartId);
    };
  }, [fullText, loop, reduced]);

  return (
    <div className="codewin" style={style}>
      <div className="titlebar">
        <span className="dot" style={{ background: 'var(--sk-carrot-strong)' }} />
        <span className="dot" style={{ background: 'var(--sk-amber-strong)' }} />
        <span className="dot" style={{ background: 'var(--sk-leaf-strong)' }} />
        <span className="filename">{file}</span>
      </div>
      <div className="lines">
        {renderTypedLines(lines, typed)}
      </div>
    </div>
  );
}

function linesToString(line) {
  return line.t.map((t) => t.s).join('');
}

function renderTypedLines(lines, typed) {
  const target = typed.length;
  // First pass: figure out which line the cursor sits on.
  let consumed = 0;
  let cursorLine = -1;
  for (let i = 0; i < lines.length; i++) {
    const lineLen = lineLength(lines[i]);
    if (target <= consumed + lineLen) { cursorLine = i; break; }
    consumed += lineLen + 1; // +1 for newline
  }
  if (cursorLine === -1) cursorLine = lines.length - 1;

  // Second pass: render each line, slicing tokens against `target`.
  consumed = 0;
  return lines.map((line, i) => {
    const tokens = [];
    let tokConsumed = consumed;
    for (let j = 0; j < line.t.length; j++) {
      const tok = line.t[j];
      const tokStart = tokConsumed;
      const tokEnd = tokConsumed + tok.s.length;
      if (target >= tokEnd) {
        tokens.push(<span key={j} className={`tok-${tok.c}`}>{tok.s}</span>);
      } else if (target > tokStart) {
        tokens.push(<span key={j} className={`tok-${tok.c}`}>{tok.s.slice(0, target - tokStart)}</span>);
      }
      tokConsumed = tokEnd;
    }
    const lineEl = (
      <div className="line" key={i}>
        <span className="ln">{i + 1}</span>
        <span>
          {tokens}
          {i === cursorLine ? <span className="cursor" /> : null}
        </span>
      </div>
    );
    consumed += lineLength(line) + 1;
    return lineEl;
  });
}

function lineLength(line) {
  let n = 0;
  for (let i = 0; i < line.t.length; i++) n += line.t[i].s.length;
  return n;
}

function useReducedMotion() {
  const [reduced, setReduced] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    setReduced(mq.matches);
    const fn = () => setReduced(mq.matches);
    mq.addEventListener('change', fn);
    return () => mq.removeEventListener('change', fn);
  }, []);
  return reduced;
}

// Sudo mode's git ribbon: the commit the site was built from (BUILD, from scripts/build.mjs).
function buildRibbon() {
  if (!BUILD) return '● built outside a git checkout';
  const tree = BUILD.clean ? 'clean working tree' : 'uncommitted changes';
  return `● ${BUILD.branch}  ${BUILD.hash} · ${BUILD.date} · “${BUILD.subject}” · ${tree}`;
}

// How long ago an ISO time was, the way git prints it: "7h ago", "3d ago".
function timeAgo(iso) {
  const mins = Math.max(0, Math.round((Date.now() - new Date(iso)) / 60000));
  if (mins < 60) return `${mins}m ago`;
  if (mins < 48 * 60) return `${Math.round(mins / 60)}h ago`;
  return `${Math.round(mins / 1440)}d ago`;
}

Object.assign(window, {
  useRoute, parseRoute, go,
  Nav, Foot,
  buildRibbon, timeAgo,
  fmtWindow,
  CodeWindow,
  useReducedMotion,
});
