---
import Default from '@astrojs/starlight/components/Header.astro';
import Search from 'virtual:starlight/components/Search';

/**
 * Three branches:
 *   - Splash pages           → custom marketing <header class="nav">
 *   - Docs pages (rest)      → mockup's <header class="doc-header"> with
 *                              brand-mark, primary doc-nav, search-inline,
 *                              lang-switcher pills (per docs-page-mockup.html)
 *   - Anything weird         → Starlight Default (fallback safety net)
 */
const route = Astro.locals.starlightRoute;
const isSplash = route?.entry?.data?.template === 'splash';
const isDocs = !!route?.entry && !isSplash;

const currentLocale = route?.locale ?? 'en';
const localeLabels = { en: 'EN', de: 'DE', ja: 'JA', es: 'ES', fr: 'FR' } as const;
const supportedLocales = Object.keys(localeLabels) as Array<keyof typeof localeLabels>;

// Swap the leading /xx/ segment of the current path to switch language.
const currentPath = Astro.url.pathname;
function localizedPath(target: string): string {
	if (currentPath.startsWith(`/${currentLocale}/`)) {
		return currentPath.replace(`/${currentLocale}/`, `/${target}/`);
	}
	return `/${target}/`;
}

// The five primary nav targets — kept in sync with the splash header.
const docNav: Array<{ label: string; href: string; current?: boolean }> = [
	{ label: 'Docs',     href: `/${currentLocale}/start/installation/` },
	{ label: 'MMVC',     href: `/${currentLocale}/core/architecture/` },
	{ label: 'AI module',href: `/${currentLocale}/ai/module/overview/` },
	{ label: 'CLI',      href: `/${currentLocale}/start/quick-start/` },
	{ label: 'Showcase', href: `/${currentLocale}/showcase/` },
];
---

{isSplash ? (
  <header class="nav" id="nav">
    <div class="container nav-row">
      <a class="brand" href="/en/" aria-label="Nibiru — home">
        <img class="brand-mark nav-logo" src="/img/nibiru-lotus.png" alt="" width="60" height="36" />
        <span class="brand-name">Nibiru</span>
        <span class="nav-version"><span class="dot"></span>v0.9.2</span>
      </a>
      <nav class="nav-links" aria-label="Primary">
        <a href="/en/core/architecture/">MMVC</a>
        <a href="/en/ai/oracle/">Mission Control</a>
        <a href="/en/start/quick-start/">Code</a>
        <a href="/en/start/installation/">Install</a>
        <a href="/en/start/what-is-nibiru/">Docs</a>
      </nav>
      <div class="nav-cta">
        <a class="btn btn-ghost btn-icon-only" href="https://github.com/alllinux/Nibiru" aria-label="GitHub">
          <svg class="ico" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 0 0 5.47 7.59c.4.07.55-.17.55-.38v-1.36c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.18-.89-1.18-.73-.5.05-.49.05-.49.81.06 1.24.83 1.24.83.72 1.24 1.89.88 2.35.67.07-.52.28-.88.51-1.08-1.78-.2-3.65-.89-3.65-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.13 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.11.16 1.93.08 2.13.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/>
          </svg>
        </a>
        <a class="btn btn-solid" href="#download">Download</a>
      </div>
    </div>
  </header>
) : isDocs ? (
  <header class="doc-header">
    <div class="doc-header-row">
      <a class="brand" href={`/${currentLocale}/`} aria-label="Nibiru — home">
        <img class="brand-mark" src="/img/nibiru-lotus.png" alt="" width="50" height="30" />
        <span class="brand-name">Nibiru<em> docs</em></span>
        <span class="nav-version"><span class="dot"></span>v0.9.2</span>
      </a>
      <nav class="doc-nav" aria-label="Primary">
        {docNav.map((item) => (
          <a href={item.href} aria-current={Astro.url.pathname.startsWith(item.href) ? 'page' : undefined}>{item.label}</a>
        ))}
      </nav>
      <div class="doc-header-tools">
        <Search />
        <div class="lang-switcher" aria-label="Language">
          {supportedLocales.map((loc) => (
            <a href={localizedPath(loc)} aria-current={loc === currentLocale ? 'true' : undefined}>{localeLabels[loc]}</a>
          ))}
        </div>
      </div>
    </div>
  </header>
) : (
  <Default {...Astro.props}>
    <slot />
  </Default>
)}

<script is:inline>
(function () {
  // The mockup's nibiru-scene.js owns nav-condense on splash pages.
  // For non-splash pages we still tag the document so the docs nav can
  // shrink the same way.
  if (document.querySelector('header.nav')) return;
  const root = document.documentElement;
  const onScroll = function () {
    if (window.scrollY > 24) root.setAttribute('data-nav-condensed', '');
    else                     root.removeAttribute('data-nav-condensed');
  };
  window.addEventListener('scroll', onScroll, { passive: true });
  onScroll();
})();

(function () {
  // The Oracle launcher must live at document.body level — not inside <header>.
  // The header has `backdrop-filter` which makes it a containing block for
  // position:fixed descendants, so a button rendered inside it would anchor
  // to the header (top-right) instead of the viewport (bottom-right).
  if (document.getElementById('oracle-launcher')) return;

  const launcher = document.createElement('button');
  launcher.id = 'oracle-launcher';
  launcher.type = 'button';
  launcher.setAttribute('aria-label', 'Open Nibiru Oracle (AI assistant)');
  launcher.title = 'Ask the Oracle';

  const panel = document.createElement('aside');
  panel.id = 'oracle-panel';
  panel.setAttribute('role', 'dialog');
  panel.setAttribute('aria-label', 'Nibiru Oracle');
  panel.innerHTML = `
    <header>
      <div>
        <h3>Nibiru Oracle</h3>
        <div class="oracle-subtitle">Trained on the framework itself</div>
      </div>
      <button class="oracle-close" type="button" aria-label="Close">✕</button>
    </header>
    <div id="oracle-messages">
      <div class="oracle-msg system">
        Ask anything about Nibiru — routing, modules, the CLI, real-world examples.
      </div>
    </div>
    <form id="oracle-form" autocomplete="off">
      <textarea name="q" placeholder="How do I create a new module?" rows="1" required></textarea>
      <button type="submit">Send</button>
    </form>
  `;

  document.body.appendChild(launcher);
  document.body.appendChild(panel);

  const closeBtn  = panel.querySelector('.oracle-close');
  const form      = panel.querySelector('#oracle-form');
  const input     = form.querySelector('textarea');
  const submitBtn = form.querySelector('button[type="submit"]');
  const list      = panel.querySelector('#oracle-messages');
  const history   = [];

  function track(event, data) {
    if (typeof window.umami?.track === 'function') {
      try { window.umami.track(event, data || {}); } catch (e) {}
    }
  }

  function open() {
    panel.classList.add('is-open');
    setTimeout(() => input.focus(), 80);
    track('oracle-open');
  }
  function close() { panel.classList.remove('is-open'); }

  launcher.addEventListener('click', () =>
    panel.classList.contains('is-open') ? close() : open()
  );
  closeBtn.addEventListener('click', close);
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); });

  function renderMarkdown(md) {
    md = md.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    md = md.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, code) =>
      `<pre><code class="lang-${lang}">${code}</code></pre>`);
    md = md.replace(/`([^`\n]+?)`/g, '<code>$1</code>');
    md = md.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
    md = md.replace(/\*([^*]+)\*/g, '<em>$1</em>');
    md = md.replace(/\n\n+/g, '</p><p>');
    md = md.replace(/\n/g, '<br/>');
    return '<p>' + md + '</p>';
  }

  function append(role, text, sources) {
    const el = document.createElement('div');
    el.className = 'oracle-msg ' + role;
    if (role === 'assistant') {
      el.innerHTML = renderMarkdown(text);
      if (sources && sources.length) {
        const cites = document.createElement('div');
        cites.style.marginTop = '0.55rem';
        cites.style.fontSize = '0.75rem';
        cites.innerHTML = '<span style="opacity:0.7">Sources: </span>' +
          sources.map((s, i) => `<a class="oracle-cite" href="${s.url}">${i + 1}. ${s.title}</a>`).join(' ');
        el.appendChild(cites);
      }
    } else {
      el.textContent = text;
    }
    list.appendChild(el);
    list.scrollTop = list.scrollHeight;
    return el;
  }

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const q = input.value.trim();
    if (!q) return;
    append('user', q);
    history.push({ role: 'user', content: q });
    input.value = '';
    submitBtn.disabled = true;
    track('oracle-question', {
      lang: (document.documentElement.lang || 'en').slice(0, 2),
      turn: history.filter((m) => m.role === 'user').length,
    });
    const placeholder = append('assistant', 'Consulting the docs…');
    try {
      const res = await fetch('/api/oracle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: history }),
      });
      if (!res.ok) {
        const t = await res.text();
        placeholder.innerHTML = renderMarkdown(`The Oracle is silent: ${t || res.statusText}`);
        return;
      }
      const data = await res.json();
      placeholder.remove();
      append('assistant', data.answer || '(no response)', data.sources || []);
      history.push({ role: 'assistant', content: data.answer });
    } catch (err) {
      placeholder.innerHTML = renderMarkdown(`Connection lost: ${err.message}`);
    } finally {
      submitBtn.disabled = false;
      input.focus();
    }
  });

  input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      form.requestSubmit();
    }
  });
})();
</script>
