import { clearSession, getStoredClient, getToken } from './auth.js';
import {
  fetchIncidents,
  fetchNotifications,
  fetchProfile,
  fetchUnreadCount,
  markNotificationsRead,
} from './api.js';
import { renderLogin } from './views/login.js';
import { renderOnboarding } from './views/onboarding.js';
import { renderDashboard } from './views/dashboard.js';
import { renderDeclareIncident } from './views/declare-incident.js';
import { renderHistory } from './views/history.js';

let shellRoot = null;

function parseHash() {
  const raw = (location.hash || '#/login').slice(1);
  const [pathPart] = raw.split('?');
  return pathPart || '/login';
}

function layoutShell(path, unreadCount) {
  const root = document.getElementById('app');
  root.innerHTML = `
    <div class="public-app-shell">
      <header class="public-topbar">
        <div class="public-topbar-row">
          <div class="public-topbar-brand">
            <div class="public-topbar-logo"><img src="/e-intervention-logo.svg" alt="e-Intervention"></div>
            <div>
              <div class="public-topbar-title">e-Intervention</div>
              <div class="public-topbar-subtitle">Espace client FTTH public</div>
            </div>
          </div>
          <div class="public-topbar-actions">
            <button class="public-icon-btn" id="btnNotifications" type="button">
              <i class="fas fa-bell"></i>
              <span class="public-badge" ${unreadCount ? '' : 'hidden'}>${unreadCount}</span>
            </button>
            <button class="public-icon-btn" id="btnLogout" type="button"><i class="fas fa-right-from-bracket"></i></button>
          </div>
        </div>
        <div class="public-client-chip" id="clientChip">Espace client actif</div>
        <div class="public-notification-panel" id="notificationPanel" hidden></div>
      </header>
      <main class="public-main"><div id="view"></div></main>
      <nav class="public-bottom-nav">
        <a class="${path === '/dashboard' ? 'active' : ''}" href="#/dashboard"><i class="fas fa-house"></i><span>Accueil</span></a>
        <a class="${path === '/declare' ? 'active' : ''}" href="#/declare"><i class="fas fa-circle-plus"></i><span>Déclarer</span></a>
        <a class="${path === '/history' ? 'active' : ''}" href="#/history"><i class="fas fa-clock-rotate-left"></i><span>Historique</span></a>
      </nav>
    </div>
  `;

  shellRoot = root;
  root.querySelector('#btnLogout').addEventListener('click', () => {
    clearSession();
    location.hash = '#/login';
  });
  root.querySelector('#btnNotifications').addEventListener('click', () => {
    const panel = root.querySelector('#notificationPanel');
    panel.hidden = !panel.hidden;
  });
  return root;
}

function renderNotifications(panel, notifications) {
  panel.innerHTML = `
    <div class="public-section-head">
      <div>
        <h3>Notifications</h3>
        <p>Messages de prise en charge et de suivi.</p>
      </div>
      <button class="btn btn-sm btn-outline-secondary" id="btnReadAll" type="button">Tout marquer lu</button>
    </div>
    <div class="screen-stack">
      ${notifications.length ? notifications.map((item) => `
        <article class="public-notification-item ${item.is_read ? 'is-read' : ''}">
          <strong>${escapeHtml(item.title)}</strong>
          <p>${escapeHtml(item.body || '')}</p>
          <span>${escapeHtml(formatDateTime(item.created_at))}</span>
        </article>
      `).join('') : '<div class="public-empty-state compact">Aucune notification pour le moment.</div>'}
    </div>
  `;

  panel.querySelector('#btnReadAll')?.addEventListener('click', async () => {
    await markNotificationsRead();
    await renderRoute();
  });
}

async function renderRoute() {
  const path = parseHash();
  const token = getToken();

  if (!token && path !== '/login' && path !== '/register') {
    location.hash = '#/login';
    return;
  }

  if (token && (path === '/login' || path === '/register')) {
    location.hash = '#/dashboard';
    return;
  }

  if (path === '/login') {
    const root = document.getElementById('app');
    root.innerHTML = '';
    await renderLogin(root, () => {
      location.hash = '#/dashboard';
    });
    return;
  }

  if (path === '/register') {
    const root = document.getElementById('app');
    root.innerHTML = '';
    await renderOnboarding(root, () => {
      location.hash = '#/dashboard';
    });
    return;
  }

  const [profileResponse, incidentsResponse, notificationsResponse, unreadResponse] = await Promise.all([
    fetchProfile(),
    fetchIncidents(),
    fetchNotifications(),
    fetchUnreadCount(),
  ]);

  const client = profileResponse?.client || getStoredClient();
  const incidents = incidentsResponse?.items || [];
  const notifications = notificationsResponse?.notifications || [];
  const unreadCount = Number(unreadResponse?.unread || 0);

  const root = layoutShell(path, unreadCount);
  root.querySelector('#clientChip').textContent = `${client?.full_name || 'Client'} • ${client?.subscription_number || 'abonnement'}`;
  renderNotifications(root.querySelector('#notificationPanel'), notifications);

  const view = root.querySelector('#view');
  if (path === '/dashboard') {
    await renderDashboard(view, { client, incidents, unreadCount });
    return;
  }
  if (path === '/declare') {
    await renderDeclareIncident(view, {
      client,
      onSuccess: async () => {
        location.hash = '#/history';
      },
    });
    return;
  }
  if (path === '/history') {
    await renderHistory(view, { incidents });
    return;
  }
  location.hash = '#/dashboard';
}

export function startApp() {
  window.addEventListener('hashchange', renderRoute);
  showBootSplash().then(renderRoute);
}

async function showBootSplash() {
  const root = document.getElementById('app');
  root.innerHTML = `
    <div class="public-splash-screen">
      <div class="public-splash-orb public-splash-orb-a"></div>
      <div class="public-splash-orb public-splash-orb-b"></div>
      <div class="public-splash-card">
        <div class="public-splash-logo-shell">
          <img src="/e-intervention-logo.svg" alt="e-Intervention" class="public-splash-logo">
        </div>
        <div class="public-splash-title">e-Intervention</div>
        <div class="public-splash-subtitle">Déclaration client et suivi intelligent des interventions</div>
        <div class="public-splash-loader"><span></span><span></span><span></span></div>
      </div>
    </div>
  `;
  await new Promise((resolve) => window.setTimeout(resolve, 1400));
}

function formatDateTime(value) {
  if (!value) {
    return '—';
  }
  const date = new Date(String(value).replace(' ', 'T'));
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
}

function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#039;');
}
