/* ═══════════════════════════════════════════════════════════
   FICTION IGNITION — shared.js
   Navigation, auth modal, nav state — uses Auth from auth.js
   Load order: auth.js THEN shared.js
═══════════════════════════════════════════════════════════ */

'use strict';

// ── Helper: resolve image path relative to any page depth ─
function imgPath(filename) {
  // Works whether the page is at root or in a subdirectory
  const depth = location.pathname.split('/').filter(Boolean).length - 1;
  const prefix = depth > 0 ? '../'.repeat(depth) : '';
  return prefix + 'images/' + filename;
}

// ── Active nav link ───────────────────────────────────────
function setActiveNav() {
  const page = location.pathname.split('/').pop() || 'index.html';
  document.querySelectorAll('.navbar-links a, .mobile-nav a').forEach(a => {
    const href = (a.getAttribute('href') || '').split('/').pop();
    a.classList.toggle('active', href === page);
  });
}

// ── Update navbar for current auth state ─────────────────
function updateNavState() {
  const actions = document.getElementById('navbar-actions');
  if (!actions) return;

  if (Auth.isLoggedIn) {
    const u = Auth.user;
    const tier = Auth.tier;
    const tierLabels = { free:'Free', starter:'Starter', writer:'Writer', author_pro:'Author Pro' };
    const adminLink = Auth.isAdmin
      ? `<a href="/admin/" class="btn btn-sm" style="background:rgba(154,77,208,.15);color:#9a4dd0;border:1px solid rgba(154,77,208,.35);font-weight:600" title="Admin Dashboard">👑 Admin</a>`
      : '';
    actions.innerHTML = `
      <span class="fi-tier-badge tier-${tier}" title="Your current plan">${tierLabels[tier] || 'Free'}</span>
      <span class="nav-username">${escHtml(u.name.split(' ')[0])}</span>
      ${adminLink}
      <button class="btn btn-ghost btn-sm nav-signout-btn" onclick="handleSignOut()">Sign Out</button>
      <a href="app.html" class="btn btn-primary btn-sm">Open App</a>`;
  } else {
    actions.innerHTML = `
      <button class="btn btn-ghost btn-sm nav-ghost-signin" onclick="openModal('login')">Sign In</button>
      <a href="pricing.html" class="btn btn-primary btn-sm">Get Started</a>`;
  }
}

function handleSignOut() {
  Auth.logout();
  updateNavState();
  // If on a gated page, redirect home
  const page = location.pathname.split('/').pop();
  if (page === 'app.html') location.href = 'index.html';
  else location.reload();
}

function escHtml(str) {
  return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ── Mobile nav ────────────────────────────────────────────
function initMobileNav() {
  const btn = document.getElementById('hamburger-btn');
  const nav = document.getElementById('mobile-nav');
  if (!btn || !nav) return;
  btn.addEventListener('click', e => {
    e.stopPropagation();
    const open = nav.classList.toggle('open');
    btn.setAttribute('aria-expanded', String(open));
  });
  document.addEventListener('click', e => {
    if (!nav.contains(e.target) && !btn.contains(e.target)) nav.classList.remove('open');
  });
}

// ── Modal system ──────────────────────────────────────────
let _modalMode = 'login';

function openModal(mode = 'login') {
  _modalMode = mode;
  _renderModal(mode);
  const overlay = document.getElementById('auth-modal-overlay');
  overlay?.classList.add('open');
  document.body.style.overflow = 'hidden';
  // Focus first input after animation
  setTimeout(() => overlay?.querySelector('input')?.focus(), 240);
}

function closeModal() {
  document.getElementById('auth-modal-overlay')?.classList.remove('open');
  document.body.style.overflow = '';
}

function _renderModal(mode) {
  const overlay = document.getElementById('auth-modal-overlay');
  if (!overlay) return;
  const isLogin = mode === 'login';
  const icon = imgPath('FictionIgnitionIcon.png');

  overlay.innerHTML = `
    <div class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title-el">
      <button class="modal-close" onclick="closeModal()" aria-label="Close modal">&times;</button>

      <div class="modal-logo">
        <img src="${icon}" alt="Fiction Ignition" onerror="this.style.display='none'" />
      </div>

      <h2 class="modal-title" id="modal-title-el">${isLogin ? 'Welcome Back' : 'Create Account'}</h2>
      <p class="modal-subtitle">${isLogin
        ? 'Sign in to access your prompts and plan.'
        : 'Free forever. Upgrade anytime.'}</p>

      ${isLogin ? `
      <div class="demo-hint">
        <strong>Demo accounts:</strong><br>
        Writer tier: <code>demo@fictionignition.com</code> / <code>demo1234</code><br>
        Author Pro: <code>pro@fictionignition.com</code> / <code>pro1234</code>
      </div>` : ''}

      <div id="modal-error" class="modal-error-box" style="display:none" role="alert"></div>

      ${!isLogin ? `
      <div class="field-group">
        <label class="field-label" for="fi-name">Full Name</label>
        <input class="field-input" type="text" id="fi-name" placeholder="Your name" autocomplete="name" />
      </div>` : ''}

      <div class="field-group">
        <label class="field-label" for="fi-email">Email Address</label>
        <input class="field-input" type="email" id="fi-email" placeholder="you@example.com" autocomplete="email" />
      </div>

      <div class="field-group">
        <label class="field-label" for="fi-password">Password</label>
        <div class="field-password-wrap">
          <input class="field-input" type="password" id="fi-password"
            placeholder="${isLogin ? '••••••••' : 'Minimum 6 characters'}"
            autocomplete="${isLogin ? 'current-password' : 'new-password'}" />
          <button type="button" class="field-eye-btn" onclick="togglePasswordVis()" aria-label="Toggle password visibility" tabindex="-1">👁</button>
        </div>
      </div>

      <button class="btn btn-primary modal-submit-btn" id="modal-submit-btn" onclick="submitModal()">
        ${isLogin ? 'Sign In' : 'Create Free Account'}
      </button>

      <div class="form-divider">or</div>
      <div class="form-switch">
        ${isLogin
          ? `New to Fiction Ignition? <a href="#" onclick="openModal('register');return false;">Create a free account →</a>`
          : `Already have an account? <a href="#" onclick="openModal('login');return false;">Sign in →</a>`}
      </div>
    </div>`;

  // Enter key submits
  overlay.querySelectorAll('.field-input').forEach(inp => {
    inp.addEventListener('keydown', e => { if (e.key === 'Enter') submitModal(); });
  });
  // Backdrop click closes
  overlay.addEventListener('click', e => { if (e.target === overlay) closeModal(); });
}

function togglePasswordVis() {
  const inp = document.getElementById('fi-password');
  if (!inp) return;
  inp.type = inp.type === 'password' ? 'text' : 'password';
}

async function submitModal() {
  const btn   = document.getElementById('modal-submit-btn');
  const errEl = document.getElementById('modal-error');
  const email = document.getElementById('fi-email')?.value?.trim() || '';
  const pass  = document.getElementById('fi-password')?.value || '';

  if (!btn) return;
  const origText = btn.textContent;
  btn.disabled    = true;
  btn.textContent = 'Please wait…';
  if (errEl) errEl.style.display = 'none';

  try {
    if (_modalMode === 'login') {
      await Auth.login(email, pass);
    } else {
      const name = document.getElementById('fi-name')?.value?.trim() || '';
      await Auth.register(name, email, pass);
    }
    closeModal();
    updateNavState();
    if (typeof onAuthSuccess === 'function') onAuthSuccess(Auth.user);

  } catch (err) {
    if (errEl) {
      errEl.textContent   = String(err).replace('Error: ', '');
      errEl.style.display = 'block';
    }
    btn.disabled    = false;
    btn.textContent = origText;
  }
}

// ── Inject extra modal + nav styles ──────────────────────
(function injectStyles() {
  const s = document.createElement('style');
  s.textContent = `
    .nav-username {
      font-family: var(--font-ui);
      font-size: 0.85rem;
      color: rgba(255,255,255,0.8);
      font-weight: 500;
      margin: 0 0.15rem;
    }
    .nav-ghost-signin { color: rgba(255,255,255,0.8) !important; }
    .nav-ghost-signin:hover { color: #fff !important; }
    .nav-signout-btn { color: rgba(255,255,255,0.6) !important; }
    .nav-signout-btn:hover { color: #fff !important; }

    .modal-error-box {
      background: rgba(192,53,10,0.08);
      border: 1px solid rgba(192,53,10,0.3);
      border-radius: var(--r-sm);
      padding: 0.65rem 0.9rem;
      font-family: var(--font-ui);
      font-size: 0.82rem;
      color: var(--error, #c0350a);
      margin-bottom: 0.9rem;
    }
    .modal-submit-btn {
      width: 100%;
      justify-content: center;
      margin-top: 0.25rem;
      font-size: 1rem;
      padding: 0.82rem 1.5rem;
    }
    .field-password-wrap {
      position: relative;
    }
    .field-password-wrap .field-input {
      padding-right: 2.75rem;
    }
    .field-eye-btn {
      position: absolute; right: 0.75rem; top: 50%;
      transform: translateY(-50%);
      background: none; border: none;
      cursor: pointer; font-size: 0.95rem; opacity: 0.5;
      transition: opacity 0.15s;
    }
    .field-eye-btn:hover { opacity: 1; }
    code {
      font-family: 'Courier New', monospace;
      font-size: 0.82em;
      background: rgba(27,46,94,0.08);
      padding: 0.1em 0.35em;
      border-radius: 3px;
      color: var(--navy, #1b2e5e);
    }
  `;
  document.head.appendChild(s);
})();

// ── Boot ──────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
  setActiveNav();
  updateNavState();
  initMobileNav();
});

// ── Init: refresh auth from server on every page load ─────
// Re-runs after the DOMContentLoaded block to sync server session
(async function initAuth() {
  await Auth.refresh();
  updateNavState();
  if (typeof updateAppState === 'function') updateAppState();

  // Show verified banner if landing after email verification
  if (window._fiJustVerified) {
    const banner = document.createElement('div');
    banner.style.cssText = 'position:fixed;top:70px;left:50%;transform:translateX(-50%);background:#2e7d4a;color:#fff;padding:.75rem 1.5rem;border-radius:8px;font-family:var(--font-ui);font-size:.9rem;font-weight:600;z-index:300;box-shadow:0 4px 16px rgba(0,0,0,.2)';
    banner.textContent   = '✓ Email verified! You can now sign in.';
    document.body.appendChild(banner);
    setTimeout(() => banner.remove(), 5000);
    // Remove the query param
    history.replaceState({}, '', location.pathname);
  }
})();

// ── Override submitModal to handle register-then-verify flow ──
const _origSubmitModal = submitModal;
window.submitModal = async function() {
  // For register mode, show a different success message
  const btn   = document.getElementById('modal-submit-btn');
  const errEl = document.getElementById('modal-error');
  if (!btn) return;

  if (_modalMode !== 'register') { _origSubmitModal(); return; }

  const name  = document.getElementById('fi-name')?.value?.trim() || '';
  const email = document.getElementById('fi-email')?.value?.trim() || '';
  const pass  = document.getElementById('fi-password')?.value || '';
  const origText = btn.textContent;

  btn.disabled    = true;
  btn.textContent = 'Creating account…';
  if (errEl) errEl.style.display = 'none';

  try {
    await Auth.register(name, email, pass);
    // Show success in modal — email check required
    const overlay = document.getElementById('auth-modal-overlay');
    if (overlay) {
      overlay.querySelector('.modal').innerHTML = `
        <div style="text-align:center;padding:1rem 0">
          <div style="font-size:3rem;margin-bottom:1rem">📬</div>
          <h2 style="font-family:var(--font-display);color:var(--navy);font-size:1.5rem;margin-bottom:.75rem">Check your inbox!</h2>
          <p style="color:var(--muted);font-size:.95rem;line-height:1.75;max-width:320px;margin:0 auto 1.5rem">
            We've sent a verification link to <strong style="color:var(--navy)">${escHtml(email)}</strong>.
            Click the link to activate your account.
          </p>
          <button class="btn btn-primary" style="margin:0 auto" onclick="closeModal()">Got it!</button>
          <p style="font-size:.78rem;color:var(--muted);margin-top:1rem">Didn't get it? Check your spam folder.</p>
        </div>`;
    }
  } catch (err) {
    if (errEl) {
      errEl.textContent   = String(err).replace('Error: ', '');
      errEl.style.display = 'block';
    }
    btn.disabled    = false;
    btn.textContent = origText;
  }
};
