'use strict';

const API_BASE =
  typeof window !== 'undefined' && window.location.hostname === 'pointage.crewplan.fr'
    ? 'https://app.crewplan.fr/api'
    : '/api';
const API = API_BASE;
let contractData = null;

// ── Helpers ──────────────────────────────────────────────────────────────────
function show(viewId) {
  document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
  const el = document.getElementById(viewId);
  if (el) el.classList.add('active');
}

function getToken() {
  return new URLSearchParams(window.location.search).get('token');
}

function formatDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric' });
}

function formatDateTime(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('fr-FR') + ' à ' + d.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
}

// ── Render contract summary ──────────────────────────────────────────────────
function renderSummary(contract) {
  const user = contract.user || {};
  const company = contract.company || {};
  const restaurant = contract.restaurant || {};

  const typeLabels = { CDI: 'CDI — Contrat à Durée Indéterminée', CDD: 'CDD — Contrat à Durée Déterminée', extra: 'Contrat Extra' };
  const typeColors = { CDI: '#1e40af', CDD: '#92400e', extra: '#6b21a8' };

  const subtitle = document.getElementById('contract-subtitle');
  if (subtitle) subtitle.textContent = `${company.name || '—'} · ${typeLabels[contract.contractType] || contract.contractType}`;

  const rows = [
    ['Employeur', company.name || '—'],
    ['Restaurant', restaurant.name || '—'],
    ['Salarié(e)', user.name || '—'],
    ['Email', user.email || '—'],
    ['Type de contrat', `<span style="background:${typeColors[contract.contractType]}22;color:${typeColors[contract.contractType]};padding:2px 8px;border-radius:4px;font-weight:700">${contract.contractType}</span>`],
    ['Poste', contract.position || '—'],
    ['Durée hebdomadaire', `${contract.contractHours}h / semaine`],
    ['Salaire brut mensuel', `${Number(contract.salary).toFixed(2)} €`],
    ['Date de début', formatDate(contract.startDate)],
    ...(contract.endDate ? [['Date de fin', formatDate(contract.endDate)]] : []),
    ...(contract.trialPeriodDays ? [['Période d\'essai', `${contract.trialPeriodDays} jours`]] : []),
    ['Convention collective', 'CCN Hôtels, Cafés, Restaurants (IDCC 1979)'],
  ];

  const summaryEl = document.getElementById('contract-summary');
  if (summaryEl) {
    summaryEl.innerHTML = rows.map(([label, value]) => `
      <div class="summary-row">
        <span class="summary-label">${label}</span>
        <span class="summary-value">${value}</span>
      </div>
    `).join('');
  }

  const token = getToken();
  if (token) {
    const pdfUrl = `${API}/contracts/sign/${token}/pdf`;
    const frame = document.getElementById('contract-pdf-frame');
    const openLink = document.getElementById('contract-pdf-open');
    if (frame) frame.src = pdfUrl;
    if (openLink) openLink.href = pdfUrl;
  }

  // Pre-fill name if known
  const nameInput = document.getElementById('sign-name');
  if (nameInput && user.name) nameInput.value = user.name;
  if (user.phone) {
    const phoneInput = document.getElementById('sign-phone');
    if (phoneInput) phoneInput.value = user.phone;
  }
}

// ── Sign ─────────────────────────────────────────────────────────────────────
async function handleSign() {
  const name = document.getElementById('sign-name').value.trim();
  const phone = document.getElementById('sign-phone').value.trim();
  const accepted = document.getElementById('sign-accept').checked;
  const errorEl = document.getElementById('sign-error');

  errorEl.style.display = 'none';

  if (!name || !phone) {
    errorEl.textContent = 'Veuillez renseigner votre nom et numéro de téléphone.';
    errorEl.style.display = 'block';
    return;
  }
  if (!accepted) {
    errorEl.textContent = 'Veuillez cocher la case pour accepter les termes du contrat.';
    errorEl.style.display = 'block';
    return;
  }

  const btn = document.getElementById('btn-sign');
  btn.disabled = true;
  btn.textContent = 'Signature en cours…';

  try {
    const token = getToken();
    const res = await fetch(`${API}/contracts/sign/${token}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ phone, name }),
    });
    const data = await res.json();

    if (!res.ok) throw new Error(data.message || 'Erreur lors de la signature');

    const infoEl = document.getElementById('success-info');
    if (infoEl) {
      infoEl.innerHTML = `
        <div class="summary-row"><span class="summary-label">Nom</span><span class="summary-value">${name}</span></div>
        <div class="summary-row"><span class="summary-label">Téléphone</span><span class="summary-value">${phone}</span></div>
        <div class="summary-row"><span class="summary-label">Date de signature</span><span class="summary-value">${formatDateTime(data.signedAt)}</span></div>
      `;
    }
    show('view-success');
  } catch (err) {
    errorEl.textContent = err.message || 'Une erreur est survenue. Réessayez.';
    errorEl.style.display = 'block';
    btn.disabled = false;
    btn.textContent = '✍️ Signer mon contrat';
  }
}

// ── Init ─────────────────────────────────────────────────────────────────────
async function init() {
  const token = getToken();
  if (!token) {
    document.getElementById('error-msg').textContent = 'Lien de signature manquant.';
    show('view-error');
    return;
  }

  try {
    const res = await fetch(`${API}/contracts/sign/${token}`);
    const data = await res.json();

    if (!res.ok) {
      document.getElementById('error-msg').textContent = data.message || 'Lien invalide.';
      show('view-error');
      return;
    }

    contractData = data;

    if (data.alreadySigned || data.status === 'signed') {
      const infoEl = document.getElementById('already-signed-info');
      if (infoEl) {
        infoEl.innerHTML = `
          <div class="summary-row"><span class="summary-label">Signé par</span><span class="summary-value">${data.signedByName || '—'}</span></div>
          <div class="summary-row"><span class="summary-label">Téléphone</span><span class="summary-value">${data.signedByPhone || '—'}</span></div>
          <div class="summary-row"><span class="summary-label">Date</span><span class="summary-value">${formatDateTime(data.signedAt)}</span></div>
        `;
      }
      show('view-already-signed');
      return;
    }

    renderSummary(data);
    show('view-contract');
  } catch (err) {
    document.getElementById('error-msg').textContent = 'Impossible de charger le contrat. Vérifiez votre connexion.';
    show('view-error');
  }
}

document.addEventListener('DOMContentLoaded', init);
