// ─── Host25Cent v2.0 — Unified Application ──────────────────────────
// ONE website: top nav with dropdowns. Same for public, client, admin.

const App = {
  state: { user: null, page: '' },

  async init() {
    this.bindEvents();
    await this.checkAuth();
    this.route();
  },

  bindEvents() {
    // Use hashchange for ALL navigation
    window.addEventListener('hashchange', () => this.route());

    // Only intercept clicks that need special handling
    document.addEventListener('click', e => {
      // Dropdown toggles
      const toggle = e.target.closest('.dropdown-toggle');
      if (toggle) {
        e.preventDefault();
        const id = toggle.dataset.target;
        const menu = document.getElementById(id);
        if (menu) {
          document.querySelectorAll('.dropdown-menu.open').forEach(m => {
            if (m.id !== id) m.classList.remove('open');
          });
          menu.classList.toggle('open');
        }
        return;
      }
      // Close dropdowns on outside click
      if (!e.target.closest('.dropdown')) {
        document.querySelectorAll('.dropdown-menu.open').forEach(m => m.classList.remove('open'));
      }
      // Mobile menu: hamburger → open drawer + overlay
      if (e.target.closest('#nav-toggle')) {
        document.getElementById('mobile-menu')?.classList.add('open');
        document.getElementById('mobile-overlay')?.classList.add('open');
        document.body.style.overflow = 'hidden';
        return;
      }
      // Mobile menu: close button → close drawer + overlay
      if (e.target.closest('[data-close-mobile]')) {
        document.getElementById('mobile-menu')?.classList.remove('open');
        document.getElementById('mobile-overlay')?.classList.remove('open');
        document.body.style.overflow = '';
        return;
      }
      // Mobile menu: clicking a link inside → navigate + close
      const mobileLink = e.target.closest('#mobile-menu a[href^="#"]');
      if (mobileLink) {
        document.getElementById('mobile-menu')?.classList.remove('open');
        document.getElementById('mobile-overlay')?.classList.remove('open');
        document.body.style.overflow = '';
        // The hash change will trigger route()
        return;
      }
      // Mobile menu: clicking the dark overlay → close
      if (e.target.closest('#mobile-overlay')) {
        document.getElementById('mobile-menu')?.classList.remove('open');
        document.getElementById('mobile-overlay')?.classList.remove('open');
        document.body.style.overflow = '';
        return;
      }
    });
  },

  async checkAuth() {
    const res = await this.api('profile');
    if (res.success) {
      this.state.user = res.data;
      document.body.classList.add('logged-in');
      document.body.classList.remove('logged-out');
    } else {
      document.body.classList.add('logged-out');
      document.body.classList.remove('logged-in');
    }
  },

  async api(route, method = 'GET', data = null) {
    const url = `api/index.php?route=${route}`;
    const opts = { method, cache: 'no-store' };
    if (data) opts.body = new URLSearchParams(data);
    try {
      const res = await fetch(url, opts);
      return await res.json();
    } catch { return { success: false, message: 'Network error' }; }
  },

  route() {
    const hash = window.location.hash.slice(1) || 'home';
    if (hash === this.state.page) return; // prevent double render
    this.state.page = hash;
    this.render();
  },

  async render() {
    const u = this.state.user;
    const p = this.state.page;
    const loggedIn = !!u;
    const admin = u?.role === 'admin';

    const sel = pg => p === pg || p.startsWith(pg + '-') || p.startsWith(pg + '/') ? ' class="active"' : '';

    // Nav links — standard href hashes so clicks work naturally
    const navLeft = loggedIn ? `
      <a href="#dashboard"${sel('dashboard')}>Dashboard</a>
      <div class="dropdown">
        <a href="#" class="dropdown-toggle${(sel('services')||sel('domains')||sel('hosting'))}" data-target="drop-services">Hosting <i class="fas fa-chevron-down" style="font-size:.6rem;margin-left:.25rem"></i></a>
        <div class="dropdown-menu" id="drop-services">
          <a href="#services">My Services</a>
          <a href="#domains">My Domains</a>
          <div class="dropdown-divider"></div>
          <a href="#hosting">Order Hosting</a>
        </div>
      </div>
      <div class="dropdown">
        <a href="#" class="dropdown-toggle${sel('billing')}" data-target="drop-billing">Billing <i class="fas fa-chevron-down" style="font-size:.6rem;margin-left:.25rem"></i></a>
        <div class="dropdown-menu" id="drop-billing">
          <a href="#billing">My Invoices</a>
        </div>
      </div>
      <div class="dropdown">
        <a href="#" class="dropdown-toggle${sel('tickets')}" data-target="drop-support">Support <i class="fas fa-chevron-down" style="font-size:.6rem;margin-left:.25rem"></i></a>
        <div class="dropdown-menu" id="drop-support">
          <a href="#tickets">My Tickets</a>
          <a href="#new-ticket">Open Ticket</a>
          <div class="dropdown-divider"></div>
          <a href="#knowledge">Knowledgebase</a>
        </div>
      </div>
    ` : `
      <a href="#home"${sel('home')}>Home</a>
      <a href="#hosting"${sel('hosting')}>Hosting</a>
      <a href="#domains-sc"${sel('domains-sc')}>Domains</a>
      <a href="#knowledge"${sel('knowledge')}>FAQ</a>
      <a href="#status"${sel('status')}>Uptime</a>
      <a href="#contact"${sel('contact')}>Contact</a>
    `;

    const navRight = loggedIn ? `
      <div class="dropdown">
        <div class="nav-user dropdown-toggle" data-target="drop-user">
          <div class="nav-avatar">${u?.fname ? u.fname[0].toUpperCase() : 'U'}</div>
          <span>${u?.fname || 'User'}</span>
          <i class="fas fa-chevron-down" style="font-size:.6rem;color:var(--gray-400);margin-left:.25rem"></i>
        </div>
        <div class="dropdown-menu dropdown-menu-right" id="drop-user">
          <a href="#dashboard">Dashboard</a>
          <a href="#profile">Profile</a>
          ${admin ? `
          <div class="dropdown-divider"></div>
          <div style="padding:.4rem 1rem .2rem;font-size:.7rem;text-transform:uppercase;color:var(--gray-400);font-weight:600">Admin</div>
          <a href="#admin-orders">Orders</a>
          <a href="#admin-invoices">Invoices</a>
          <a href="#admin-users">Users</a>
          <a href="#admin-products">Products</a>
          <a href="#admin-servers">Servers</a>
          <a href="#admin-coupons">Coupons</a>
          <a href="#admin-registrars">Registrars</a>
          <a href="#admin-tlds">Free Domain TLDs</a>
          <a href="#admin-tickets">Tickets</a>
          <a href="#admin-news">News</a>
          ` : ''}
          <div class="dropdown-divider"></div>
          <a href="#logout" style="color:var(--danger)">Logout</a>
        </div>
      </div>
    ` : `
      <a href="#login" class="btn btn-sm btn-ghost">Log In</a>
      <a href="#register" class="btn btn-sm btn-primary">Sign Up</a>
    `;

    // Mobile links
    const mobileLinks = loggedIn ? `
      <a href="#dashboard">Dashboard</a>
      <div class="mobile-section">Hosting</div>
      <a href="#services">My Services</a>
      <a href="#domains">My Domains</a>
      <a href="#hosting">Order Hosting</a>
      <div class="mobile-section">Billing</div>
      <a href="#billing">Invoices</a>
      <div class="mobile-section">Support</div>
      <a href="#tickets">My Tickets</a>
      <a href="#new-ticket">Open Ticket</a>
      <a href="#profile">Profile</a>
      ${admin ? `
      <div class="mobile-section">Admin</div>
      <a href="#admin-orders">Orders</a>
      <a href="#admin-invoices">Invoices</a>
      <a href="#admin-users">Users</a>
      <a href="#admin-products">Products</a>
      <a href="#admin-servers">Servers</a>
      <a href="#admin-coupons">Coupons</a>
      <a href="#admin-registrars">Registrars</a>
      <a href="#admin-tlds">Free Domain TLDs</a>
      <a href="#admin-tickets">Tickets</a>
      <a href="#admin-news">News</a>
      ` : ''}
      <div class="mobile-divider"></div>
      <a href="#logout" style="color:var(--danger)">Logout</a>
    ` : `
      <a href="#home">Home</a>
      <a href="#hosting">Hosting Plans</a>
      <a href="#domains-sc">Domain Checker</a>
      <a href="#knowledge">Knowledgebase</a>
      <a href="#status">Network Status</a>
      <a href="#contact">Contact</a>
      <div class="mobile-divider"></div>
      <a href="#login">Log In</a>
      <a href="#register">Sign Up</a>
    `;

    const footer = `
      <footer class="footer">
        <div class="footer-inner">
          <div class="footer-grid">
            <div class="footer-col"><h4>Company</h4><a href="#contact">About Us</a><a href="#contact">Contact Us</a></div>
            <div class="footer-col"><h4>Hosting</h4><a href="#hosting">Web Hosting</a><a href="#hosting">Reseller Hosting</a><a href="#hosting">VPS Hosting</a></div>
            <div class="footer-col"><h4>Domains</h4><a href="#domains-sc">Domain Registration</a><a href="#domains-sc">.com Domains</a></div>
            <div class="footer-col"><h4>Support</h4><a href="${loggedIn?'#tickets':'#login'}">Client Area</a><a href="${loggedIn?'#new-ticket':'#login'}">Submit Ticket</a><a href="#knowledge">Knowledgebase</a></div>
            <div class="footer-col footer-col-wide"><h4>Host25Cent</h4><p style="color:var(--gray-500);font-size:.875rem">Gentle Cir, Gaithersburg, MD 20886, USA<br>+1 401 402 0325<br>sales@host25cent.com</p></div>
          </div>
          <div class="footer-bottom">
            <div class="footer-bottom-links"><a href="#">Terms of Service</a><a href="#">Privacy Policy</a></div>
            <div class="footer-copyright">&copy; ${new Date().getFullYear()} <a href="https://host25cent.com/">Host25Cent</a>. All Rights Reserved.</div>
          </div>
        </div>
      </footer>`;

    document.getElementById('app').innerHTML = `
      <nav class="nav">
        <div class="nav-inner">
          <a href="${loggedIn?'#dashboard':'#home'}" class="nav-logo"><img src="img/logo_light.png" alt="Host25Cent">Host25Cent</a>
          <div class="nav-menu">${navLeft}</div>
          <div class="nav-right">${navRight}<button class="nav-toggle" id="nav-toggle" aria-label="Menu"><i class="fas fa-bars"></i></button></div>
        </div>
      </nav>
      <div class="mobile-menu-overlay" id="mobile-overlay"></div>
      <div class="mobile-menu" id="mobile-menu">
        <div class="mobile-menu-header">
          <div class="mobile-menu-logo"><img src="img/logo_light.png" alt="Host25Cent" height="28">Host25Cent</div>
          <button class="mobile-close" data-close-mobile aria-label="Close"><i class="fas fa-times"></i></button>
        </div>
        <div class="mobile-menu-links">${mobileLinks}</div>
      </div>
      <div class="page" id="page-content"><div class="spinner-wrap"><div class="spinner"></div></div></div>
      ${footer}
    `;

    this.$content = document.getElementById('page-content');
    await this.loadPage(p);
  },

  async loadPage(page) {
    const c = this.$content;
    if (!c) return;

    // Handle special pages
    if (page.startsWith('service-')) { await Services.detail(page.replace('service-', '')); return; }
    if (page.startsWith('ticket-')) { await Support.view(parseInt(page.replace('ticket-', ''))); return; }
    if (page.startsWith('checkout-')) { await Checkout.render(page.replace('checkout-', '')); return; }
    if (page.startsWith('invoice-')) { await Billing.detail(page.replace('invoice-', '')); return; }
    if (page === 'logout') { await this.logout(); return; }

    c.innerHTML = '<div class="spinner-wrap"><div class="spinner"></div></div>';

    try {
      if (page === 'dashboard') await Dashboard.render(this);
      else if (page === 'services') await Services.render(this);
      else if (page === 'billing') await Billing.render(this);
      else if (page === 'domains') await Domains.render(this);
      else if (page === 'tickets') await Support.render(this);
      else if (page === 'new-ticket') await Support.renderNew(this);
      else if (page === 'profile') await Profile.render(this);
      else if (page === 'home') await Public.home(this);
      else if (page === 'hosting') await Public.hosting(this);
      else if (page === 'domains-sc') await Public.domainChecker(this);
      else if (page === 'knowledge') await Public.knowledge(this);
      else if (page === 'status') await Public.status(this);
      else if (page === 'contact') await Public.contact(this);
      else if (page === 'login') await Auth.login(this);
      else if (page === 'register') await Auth.register(this);
      else if (page === 'forgot') await Auth.forgot(this);
      else if (page.startsWith('admin-')) await Admin.render(page, this);
      else c.innerHTML = '<div class="empty"><i class="fas fa-search"></i><p>Page not found</p></div>';
    } catch(e) {
      c.innerHTML = `<div class="empty"><i class="fas fa-exclamation-triangle"></i><p>Error loading page</p></div>`;
    }
  },

  async logout() {
    await this.api('auth/logout');
    this.state.user = null;
    this.state.page = 'home';
    window.location.hash = 'home';
    await this.render();
  },

  showLoading() { if (this.$content) this.$content.innerHTML = '<div class="spinner-wrap"><div class="spinner"></div></div>'; },
  hideLoading() {},
  navigate(page) { window.location.hash = page; },
  escape(str) { const d = document.createElement('div'); d.textContent = str; return d.innerHTML; },
  statusLabel(s) { return {1:'Active',2:'Suspended',3:'Cancelled',0:'Pending'}[s]||'Unknown'; },
  statusClass(s) { return {1:'badge badge-active',2:'badge badge-suspended',3:'badge badge-cancelled',0:'badge badge-pending'}[s]||'badge badge-pending'; },
  invLabel(s) { return {1:'Paid',2:'Hold',3:'Refunded',4:'Cancelled',0:'Unpaid'}[s]||'Unknown'; },
  invClass(s) { return {1:'badge badge-paid',2:'badge badge-unpaid',3:'badge badge-refunded',4:'badge badge-cancelled',0:'badge badge-unpaid'}[s]||'badge badge-unpaid'; },
  ticketLabel(s) { return {0:'Open',1:'Answered',2:'Closed'}[s]||'Unknown'; },
  ticketClass(s) { return {0:'badge badge-pending',1:'badge badge-active',2:'badge badge-cancelled'}[s]||'badge badge-pending'; },
  showMessage(msg, type = 'info') {
    const el = document.createElement('div');
    el.className = `alert alert-${type}`;
    el.textContent = msg;
    this.$content?.prepend(el);
    setTimeout(() => el.remove(), 5000);
  }
};

document.addEventListener('DOMContentLoaded', () => App.init());