/**
 * nav.js — SkyRealms shared chrome
 * Layout: TrapppedMC-style hero (logo large + centered in hero)
 *         JailbreakMC-style nav (image icons, top-right, labels below)
 */
const Nav = (() => {

  const DISCORD_ICON = `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057c.001.022.015.04.033.055a19.93 19.93 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z"/></svg>`;

  const NAV_ITEMS = [
    { key: 'home',    label: 'Home',    href: '',        icon: 'home' },
    { key: 'bans',    label: 'Bans',    href: 'bans/',   icon: 'bans' },
    { key: 'store',   label: 'Store',   href: 'store/',  icon: 'store' },
    { key: 'staff',   label: 'Staff',   href: 'staff/',  icon: 'staff' },
    { key: 'discord', label: 'Discord', href: 'https://discord.gg/skyrealms', icon: 'discord', target: '_blank' },
  ];

  // Maps icon key → filename in assets/nav/
  const ICON_FILES = {
    home:    'home.png',
    bans:    'bans.png',
    store:   'store.png',
    staff:   'staff.png',
    discord: 'discord-3d.png',
  };

  function getDepth() {
    const parts = window.location.pathname.replace(/\/index\.html$/, '/').split('/').filter(Boolean);
    return parts.length;
  }

  function resolveHref(href, isExternal) {
    if (isExternal || href.startsWith('http')) return href;
    const prefix = getDepth() > 0 ? '../'.repeat(getDepth()) : '';
    return prefix + href;
  }

  function resolveAsset(path) {
    const prefix = getDepth() > 0 ? '../'.repeat(getDepth()) : '';
    return prefix + path;
  }

  function esc(s) {
    const d = document.createElement('div');
    d.textContent = String(s ?? '');
    return d.innerHTML;
  }

  function buildHeader(cfg) {
    const logoHref   = getDepth() > 0 ? '../'.repeat(getDepth()) : './';
    const discordUrl = cfg.discordUrl || 'https://discord.gg/skyrealms';
    const activeKey  = cfg.active || 'home';

    const navLinks = NAV_ITEMS.map(item => {
      const href = resolveHref(item.href, !!item.target);
      return `<a href="${href}" class="header-nav-link${item.key === activeKey ? ' active' : ''}"${item.target ? ` target="${item.target}"` : ''} data-icon="${item.icon}">
          <i class="icon icon-${item.icon}"></i>
          <span>${item.label}</span>
        </a>`;
    }).join('');

    return `
<header id="sr-header">

  <!-- Floating islands -->
  <div class="floating-island island-1">
    <svg viewBox="0 0 50 35" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="25" cy="20" rx="22" ry="10" fill="#5D4037"/>
      <rect x="10" y="8" width="30" height="12" rx="2" fill="#4CAF50"/>
      <ellipse cx="25" cy="8" rx="15" ry="5" fill="#66BB6A"/>
    </svg>
  </div>
  <div class="floating-island island-2">
    <svg viewBox="0 0 35 25" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="17" cy="15" rx="15" ry="7" fill="#5D4037"/>
      <rect x="5" y="6" width="24" height="9" rx="2" fill="#4CAF50"/>
      <ellipse cx="17" cy="6" rx="12" ry="4" fill="#66BB6A"/>
    </svg>
  </div>
  <div class="floating-island island-3">
    <svg viewBox="0 0 25 18" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="12" cy="11" rx="11" ry="5" fill="#5D4037"/>
      <rect x="3" y="5" width="18" height="6" rx="2" fill="#4CAF50"/>
      <ellipse cx="12" cy="5" rx="9" ry="3" fill="#66BB6A"/>
    </svg>
  </div>
  <div class="floating-island island-4">
    <svg viewBox="0 0 40 28" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="20" cy="18" rx="18" ry="8" fill="#5D4037"/>
      <rect x="6" y="7" width="28" height="11" rx="2" fill="#4CAF50"/>
      <ellipse cx="20" cy="7" rx="14" ry="4" fill="#66BB6A"/>
    </svg>
  </div>

  <!-- Top-right nav bar (JailbreakMC style) -->
  <nav class="header-nav">
    <div class="header-nav-inner">
      <div class="header-nav-links">
        ${navLinks}
      </div>
    </div>
  </nav>

  <!-- Big centered logo (TrapppedMC style) -->
  <div class="hero-logo-wrap">
    <a href="${logoHref}" class="hero-logo" id="hero-logo-el"></a>
    <p class="hero-tagline">The ultimate Skyblock experience</p>
  </div>

</header>

<!-- Discord bar + title + play-now -->
<div class="sr-above-content">
  <div class="p-body-inner">
    <a href="${esc(discordUrl)}" target="_blank" class="sr-discord-bar">
      <div class="sr-discord-icon">${DISCORD_ICON}</div>
      <div class="sr-discord-text">
        <h4>Join our Discord Server</h4>
        <p>community · support · giveaways · updates</p>
      </div>
    </a>
  </div>
</div>

<div id="sr-title-bar">
  <div class="p-body-inner">
    <div class="sr-title-main">
      <div class="sr-title-bar-left">
        <h1>${esc(cfg.pageTitle || 'SkyRealms')}</h1>
      </div>
    </div>
    <div class="sr-title-sidebar">
      <div class="sr-play-area">
        <div style="text-align:center">
          <div id="sr-play-btn" class="sr-play-btn" style="cursor:pointer">
            <span class="material-icons" style="font-size:18px">play_arrow</span>
            Play Now
          </div>
          <div class="sr-player-count" style="margin-top:8px">
            <b class="sr-js--playercount">—</b> players online
          </div>
        </div>
      </div>
    </div>
  </div>
</div>`;
  }

  function buildFooter() {
    return `
<footer class="p-footer">
  <div class="p-body-inner">
    <div class="p-footer-inner">
      <span>
        ${new Date().getFullYear()} &copy; <strong style="color:rgba(200,230,245,0.6)">SkyRealms</strong>. All Rights Reserved.
        <small>Not affiliated with Mojang AB.</small>
      </span>
    </div>
  </div>
</footer>`;
  }

  let _ip = 'play.skyrealms.net';

  function init(cfg = {}) {
    _ip = cfg.serverIp || _ip;

    const anchor = document.getElementById('page-content') || document.body.firstElementChild;
    const parent = anchor.parentNode;

    // Inject header
    const tmp = document.createElement('div');
    tmp.innerHTML = buildHeader(cfg);
    while (tmp.firstChild) parent.insertBefore(tmp.firstChild, anchor);

    // Resolve asset paths now that depth is known
    const heroLogo = document.getElementById('hero-logo-el');
    if (heroLogo) heroLogo.style.backgroundImage = `url("${resolveAsset('assets/logo.png')}")`;

    document.querySelectorAll('#sr-header .icon').forEach(el => {
      const key = [...el.classList].find(c => c.startsWith('icon-') && c !== 'icon')?.replace('icon-', '');
      const file = ICON_FILES[key];
      if (file) el.style.backgroundImage = `url("${resolveAsset('assets/nav/' + file)}")`;
    });

    // Inject footer
    const footTmp = document.createElement('div');
    footTmp.innerHTML = buildFooter();
    while (footTmp.firstChild) document.body.appendChild(footTmp.firstChild);

    // Copy IP on Play Now
    document.getElementById('sr-play-btn')?.addEventListener('click', () => {
      navigator.clipboard.writeText(_ip).then(() => {
        if (typeof Swal !== 'undefined') {
          Swal.fire({
            title: 'Copied!',
            html: `<span style="font-size:13px;color:#aac8e0">Join at <b style="color:white">${_ip}</b> in Minecraft</span>`,
            icon: 'success', timer: 2500, showConfirmButton: false, background: '#102030',
          });
        }
      }).catch(() => alert('Server IP: ' + _ip));
    });

    loadPlayerCount();
  }

  async function loadPlayerCount() {
    try {
      const r    = await fetch(`https://api.mcsrvstat.us/2/${encodeURIComponent(_ip)}`);
      const data = await r.json();
      if (data?.online) {
        document.querySelectorAll('.sr-js--playercount')
          .forEach(el => el.textContent = data.players?.online ?? 0);
      }
    } catch(e) {}
  }

  function showToast(msg) {
    if (typeof Swal !== 'undefined') {
      Swal.fire({ title: msg, toast: true, position: 'top-end', showConfirmButton: false, timer: 2500, background: '#102030', color: '#c8dff0' });
    }
  }

  return { init, showToast };
})();