// ─── Savuki Drilling — App Core (Router, Shell, Auth) ────────────────────
import { login, logout, getToken, getUser, saveAuth, clearAuth } from './api.js';
import { initDashboard } from './modules/dashboard.js';

// ── State ─────────────────────────────────────────────────────────────────
let currentUser = null;
let currentRoute = 'dashboard';

// ── Boot ──────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  const token = getToken();
  const user = getUser();

  if (token && user) {
    currentUser = user;
    bootApp(user);
  } else {
    showLogin();
  }
});

// ── Login ─────────────────────────────────────────────────────────────────
function showLogin() {
  document.getElementById('login-page').style.display = 'flex';
  document.getElementById('app').classList.remove('ready');

  // Wire button click — avoids the inline onsubmit="return false" on the form
  const btn = document.getElementById('login-btn');
  if (btn && !btn._loginWired) {
    btn._loginWired = true;
    btn.addEventListener('click', handleLogin);
    // Also support Enter key in password field
    document.getElementById('login-password')?.addEventListener('keydown', e => {
      if (e.key === 'Enter') handleLogin(e);
    });
  }
}

async function handleLogin(e) {
  if (e?.preventDefault) e.preventDefault();
  const username = document.getElementById('login-username').value.trim();
  const password = document.getElementById('login-password').value;
  const errEl = document.getElementById('login-error');
  const btn = document.getElementById('login-btn');

  errEl.classList.remove('visible');
  btn.disabled = true;
  btn.textContent = 'Signing in…';

  try {
    const data = await login(username, password);
    saveAuth(data.token, data.user);
    currentUser = data.user;
    document.getElementById('login-page').style.display = 'none';
    bootApp(data.user);
  } catch (err) {
    errEl.textContent = err.message;
    errEl.classList.add('visible');
    btn.disabled = false;
    btn.textContent = 'Sign In';
  }
}

// ── App Shell ─────────────────────────────────────────────────────────────
function bootApp(user) {
  const role = user.user_type.toLowerCase();

  // Fill topbar
  document.getElementById('user-name').textContent = user.username;
  document.getElementById('user-role').textContent = user.user_type;

  // Build sidebar navigation
  document.getElementById('sidebar-nav').innerHTML = buildNav(role);

  // Show shell
  document.getElementById('app').classList.add('ready');

  // Mobile hamburger
  document.getElementById('hamburger').addEventListener('click', toggleSidebar);
  document.getElementById('sidebar-overlay').addEventListener('click', closeSidebar);

  // Logo → dashboard
  document.getElementById('logo-home')?.addEventListener('click', e => {
    e.preventDefault();
    navigate('dashboard');
  });

  // Logout
  document.getElementById('logout-btn').addEventListener('click', handleLogout);

  // Nav click delegation
  document.getElementById('sidebar-nav').addEventListener('click', (e) => {
    const item = e.target.closest('.nav-item[data-route]');
    if (item) {
      closeSidebar();
      navigate(item.dataset.route);
    }
  });

  // Initial route
  navigate('dashboard');
}

// ── Navigation ────────────────────────────────────────────────────────────
const NAV = {
  dev: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Operations' },
    { route: 'jobcards', label: 'Jobcards', icon: 'jobcard' },
    { route: 'leads', label: 'Leads', icon: 'lead' },
    { route: 'assign', label: 'Assign', icon: 'assign' },
    { section: 'Pump' },
    { route: 'pump-install', label: 'Installations', icon: 'pump' },
    { route: 'pump-repair', label: 'Repairs', icon: 'repair' },
    { section: 'Stock' },
    { route: 'stock', label: 'Current Stock', icon: 'stock' },
    { route: 'stock-assign', label: 'Assign Stock', icon: 'assign' },
    { route: 'stock-return', label: 'Return Stock', icon: 'return' },
    { route: 'stock-booked', label: 'Booked Stock', icon: 'stock' },
    { section: 'Finance' },
    { route: 'invoices', label: 'Invoices', icon: 'invoice' },
    { section: 'Manage' },
    { route: 'assets', label: 'Assets', icon: 'truck' },
    { route: 'teams', label: 'Teams', icon: 'team' },
    { route: 'users', label: 'Users', icon: 'user' },
    { route: 'maps', label: 'Maps', icon: 'map' },
    { section: 'Reports' },
    { route: 'reports', label: 'Reports', icon: 'report' },
  ],
  test: 'dev',  // alias

  admin: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Operations' },
    { route: 'jobcards', label: 'Jobcards', icon: 'jobcard' },
    { route: 'leads', label: 'Leads', icon: 'lead' },
    { route: 'assign', label: 'Assign', icon: 'assign' },
    { section: 'Pump' },
    { route: 'pump-install', label: 'Installations', icon: 'pump' },
    { route: 'pump-repair', label: 'Repairs', icon: 'repair' },
    { section: 'Finance' },
    { route: 'invoices', label: 'Invoices', icon: 'invoice' },
    { section: 'Manage' },
    { route: 'assets', label: 'Assets', icon: 'truck' },
    { route: 'teams', label: 'Teams', icon: 'team' },
    { route: 'users', label: 'Users', icon: 'user' },
    { route: 'maps', label: 'Maps', icon: 'map' },
    { section: 'Reports' },
    { route: 'reports', label: 'Reports', icon: 'report' },
  ],

  dispatch: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Stock' },
    { route: 'stock', label: 'Current Stock', icon: 'stock' },
    { route: 'stock-assign', label: 'Assign Stock', icon: 'assign' },
    { route: 'stock-return', label: 'Return Stock', icon: 'return' },
    { route: 'stock-booked', label: 'Booked Stock', icon: 'stock' },
  ],

  workshop: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Stock' },
    { route: 'stock', label: 'Current Stock', icon: 'stock' },
    { route: 'stock-assign', label: 'Assign Stock', icon: 'assign' },
    { route: 'stock-return', label: 'Return Stock', icon: 'return' },
    { route: 'stock-booked', label: 'Booked Stock', icon: 'stock' },
  ],

  manager: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Operations' },
    { route: 'jobcards', label: 'Jobcards', icon: 'jobcard' },
    { section: 'Reports' },
    { route: 'reports', label: 'Reports', icon: 'report' },
  ],

  driver: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
  ],

  install: [
    { section: 'Main' },
    { route: 'dashboard', label: 'Dashboard', icon: 'home' },
    { section: 'Operations' },
    { route: 'pump-install', label: 'Installations', icon: 'pump' },
    { route: 'pump-repair', label: 'Repairs', icon: 'repair' },
    { route: 'stock-booked', label: 'My Stock', icon: 'stock' },
  ],
};

// SVG icons for nav items
function navIcon(name) {
  const icons = {
    home: `<path d="M3 12L12 3l9 9"/><path d="M9 21V9h6v12"/>`,
    jobcard: `<path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>`,
    lead: `<path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/>`,
    assign: `<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><polyline points="16 11 18 13 22 9"/>`,
    pump: `<path d="M3 3h6l3 9-3.5 2A11 11 0 0012 22h0a11 11 0 00-3.5-8L5 12 8 3H3z"/>`,
    repair: `<path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"/>`,
    stock: `<path d="M20 7H4a2 2 0 00-2 2v10a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2z"/><path d="M16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/>`,
    return: `<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/>`,
    invoice: `<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/>`,
    truck: `<rect x="1" y="3" width="15" height="13"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/>`,
    team: `<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/>`,
    user: `<path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/>`,
    map: `<polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/>`,
    report: `<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><polyline points="8 13 10 15 14 11"/>`,
  };
  return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    ${icons[name] || icons.home}
  </svg>`;
}

function buildNav(role) {
  const items = NAV[role] === 'dev' ? NAV.dev : (NAV[role] || NAV.driver);
  return items.map(item => {
    if (item.section) {
      return `<div class="nav-section">
        <span class="nav-section-label">${item.section}</span>`;
    }
    return `<div class="nav-item" data-route="${item.route}">
      ${navIcon(item.icon)}
      ${item.label}
    </div>`;
  }).join('') + '</div>'.repeat(items.filter(i => i.section).length);
}

// ── Navigation ────────────────────────────────────────────────────────────
let _routeParams = {};

export function navigate(route, params = {}) {
  _routeParams = params;
  currentRoute = route;

  // Update active nav item
  document.querySelectorAll('.nav-item[data-route]').forEach(el => {
    el.classList.toggle('active', el.dataset.route === route);
  });

  // Update topbar title
  const titles = {
    dashboard: 'Dashboard',
    jobcards: 'Jobcards',
    'jobcard-view': 'Jobcard Detail',
    'pump-install': 'Pump Installations',
    'pump-install-view': 'Installation Detail',
    'pump-repair': 'Pump Repairs',
    'pump-repair-view': 'Repair Detail',
    'stock': 'Current Stock',
    'stock-assign': 'Assign Stock',
    'stock-booked': 'Booked Stock',
    'stock-return': 'Return Stock',
    'stock-used': 'Used Stock',
    'teams': 'Teams',
    'users': 'Users',
    'maps': 'Jobcard Map',
    'assets': 'Assets',
    'invoices': 'Invoices',
    'invoice-create': 'New Invoice',
    'invoice-view': 'Invoice',
    leads: 'Leads',
    assign: 'Assign Jobcard',
    'pump-install': 'Pump Installations',
    'pump-repair': 'Pump Repairs',
    stock: 'Current Stock',
    'stock-assign': 'Assign Stock',
    'stock-return': 'Return Stock',
    'stock-booked': 'Booked Stock',
    invoices: 'Invoices',
    assets: 'Assets',
    teams: 'Teams',
    users: 'Users',
    maps: 'Maps',
    reports: 'Reports',
  };
  document.getElementById('page-title').textContent = titles[route] || route;

  // Route to module
  const role = currentUser?.user_type?.toLowerCase() || 'driver';
  const content = document.getElementById('view-content');
  const v = `?v=${Date.now()}`;   // cache-bust every navigation

  switch (route) {
    case 'dashboard':
      initDashboard(role);
      break;
    case 'leads':
      import(`./modules/leads.js${v}`).then(m => m.initLeads());
      break;
    case 'assign':
      import(`./modules/leads.js${v}`).then(m => m.initAssign());
      break;
    case 'jobcards':
      import(`./modules/leads.js${v}`).then(m => m.initJobcards());
      break;
    case 'jobcard-view':
      import(`./modules/jobcard-view.js${v}`).then(m => m.initJobcardView(_routeParams.id, role));
      break;
    case 'pump-install':
      import(`./modules/pumps.js${v}`).then(m => m.initInstalls(role));
      break;
    case 'pump-install-view':
      import(`./modules/pumps.js${v}`).then(m => m.initInstallView(_routeParams.id, role));
      break;
    case 'pump-repair':
      import(`./modules/pumps.js${v}`).then(m => m.initRepairs(role));
      break;
    case 'pump-repair-view':
      import(`./modules/pumps.js${v}`).then(m => m.initRepairView(_routeParams.id, role));
      break;
    case 'stock':
      import(`./modules/stock.js${v}`).then(m => m.initStock(role));
      break;
    case 'stock-assign':
      import(`./modules/stock.js${v}`).then(m => m.initAssignStock(role));
      break;
    case 'stock-booked':
      import(`./modules/stock.js${v}`).then(m => m.initBookedStock(role));
      break;
    case 'stock-return':
      import(`./modules/stock.js${v}`).then(m => m.initReturnStock(role));
      break;
    case 'stock-used':
      import(`./modules/stock.js${v}`).then(m => m.initUsedStock(role));
      break;
    case 'teams':
      import(`./modules/teams.js${v}`).then(m => m.initTeams(role));
      break;
    case 'users':
      import(`./modules/teams.js${v}`).then(m => m.initUsers(role));
      break;
    case 'reports':
      import(`./modules/reports.js${v}`).then(m => m.initReports(role));
      break;
    case 'maps':
      import(`./modules/maps.js${v}`).then(m => m.initMaps(role));
      break;
    case 'assets':
      import(`./modules/assets.js${v}`).then(m => m.initAssets(role));
      break;
    case 'invoices':
      import(`./modules/invoices.js${v}`).then(m => m.initInvoices(role));
      break;
    case 'invoice-create':
      import(`./modules/invoices.js${v}`).then(m => m.initCreateInvoice(role, _routeParams.jc_id, _routeParams.pump_record_id, _routeParams.pump_type));
      break;
    case 'invoice-view':
      import(`./modules/invoices.js${v}`).then(m => m.initInvoiceView(_routeParams.id, role));
      break;
    default:
      content.innerHTML = `
        <div class="page-header">
          <h1>${titles[route] || route}</h1>
        </div>
        <div class="card">
          <div class="card-body empty-state">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:48px;height:48px;margin:0 auto 1rem;opacity:.25">
              <path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>
            </svg>
            <p style="color:var(--text-muted);font-size:0.9rem">
              <strong>${titles[route] || route}</strong> module coming soon.
            </p>
          </div>
        </div>`;
  }
}

// ── Sidebar toggle (mobile) ───────────────────────────────────────────────
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('open');
  document.getElementById('sidebar-overlay').classList.toggle('open');
}
function closeSidebar() {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('sidebar-overlay').classList.remove('open');
}

// ── Logout ────────────────────────────────────────────────────────────────
async function handleLogout() {
  await logout();
  currentUser = null;
  document.getElementById('app').classList.remove('ready');
  document.getElementById('login-form').reset();
  document.getElementById('login-error').classList.remove('visible');
  document.getElementById('login-btn').disabled = false;
  document.getElementById('login-btn').textContent = 'Sign In';
  showLogin();
}

// ── Modal ─────────────────────────────────────────────────────────────────
export function openModal(title, bodyHtml, onConfirm, {
  confirmLabel = 'Save',
  confirmClass = 'btn-primary',
} = {}) {
  closeModal();
  const backdrop = document.createElement('div');
  backdrop.className = 'modal-backdrop';
  backdrop.id = 'modal-backdrop';
  backdrop.innerHTML = `
    <div class="modal" role="dialog" aria-modal="true">
      <div class="modal-header">
        <span class="modal-title">${title}</span>
        <button class="modal-close" id="modal-close-btn" aria-label="Close">✕</button>
      </div>
      <div class="modal-body">${bodyHtml}</div>
      <div class="modal-footer">
        <button class="btn btn-ghost" id="modal-cancel-btn">Cancel</button>
        <button class="btn ${confirmClass}" id="modal-confirm-btn">${confirmLabel}</button>
      </div>
    </div>`;
  document.body.appendChild(backdrop);

  const confirmBtn = document.getElementById('modal-confirm-btn');
  confirmBtn.addEventListener('click', async () => {
    confirmBtn.disabled = true;
    confirmBtn.textContent = 'Saving…';
    await onConfirm();
    confirmBtn.disabled = false;
    confirmBtn.textContent = confirmLabel;
  });
  document.getElementById('modal-close-btn')?.addEventListener('click', closeModal);
  document.getElementById('modal-cancel-btn')?.addEventListener('click', closeModal);
  backdrop.addEventListener('click', e => { if (e.target === backdrop) closeModal(); });
}

export function closeModal() {
  document.getElementById('modal-backdrop')?.remove();
}

// ── Toast ─────────────────────────────────────────────────────────────────
export function showToast(message, type = 'default', duration = 3500) {
  const container = document.getElementById('toast-container');
  const el = document.createElement('div');
  el.className = `toast ${type}`;
  el.textContent = message;
  container.appendChild(el);
  setTimeout(() => el.remove(), duration);
}

// ── Payment slip fallback ──────────────────────────────────────────────────
// If the slip is not found on the admin server, try the tech (driver app) server
const TECH_PAYMENTS_BASE = 'https://api.elegantwork.co.za/savuki_app/uploads/payments/';
window.checkPaySlip = function (e, link, filename) {
  e.preventDefault();
  const localUrl = '/uploads/payments/' + filename;
  const techUrl = TECH_PAYMENTS_BASE + filename;
  // Try local first — if 404 redirect to tech server
  fetch(localUrl, { method: 'HEAD' })
    .then(res => {
      window.open(res.ok ? localUrl : techUrl, '_blank');
    })
    .catch(() => {
      window.open(techUrl, '_blank');
    });
};