import L from 'leaflet';
import { registerClient, getApiBase, setApiBase } from '../api.js';
import { setSession } from '../auth.js';

let mapInstance = null;
let mapMarker = null;

function destroyMap() {
  if (mapInstance) {
    mapInstance.remove();
  }
  mapInstance = null;
  mapMarker = null;
}

function ensureMap(container, lat, lng, onMove) {
  destroyMap();
  mapInstance = L.map(container, { zoomControl: false }).setView([lat, lng], 15);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap',
  }).addTo(mapInstance);
  mapMarker = L.marker([lat, lng], { draggable: true }).addTo(mapInstance);
  mapMarker.on('dragend', () => {
    const position = mapMarker.getLatLng();
    onMove(position.lat, position.lng);
  });
  mapInstance.on('click', (event) => {
    mapMarker.setLatLng(event.latlng);
    onMove(event.latlng.lat, event.latlng.lng);
  });
}

export async function renderOnboarding(root, onRegistered) {
  root.innerHTML = `
    <section class="public-auth-shell">
      <div class="public-auth-card">
        <div class="public-hero-card">
          <div class="public-brand-mark"><img src="/e-intervention-logo.svg" alt="e-Intervention"></div>
          <span class="public-hero-pill">Création d'espace client</span>
          <h1>Créer mon compte</h1>
          <p>Enregistrez votre abonnement, votre contact et votre localisation pour déclarer vos incidents depuis l'application.</p>
        </div>

        <div class="public-auth-switch">
          <span>Vous avez déjà un compte ?</span>
          <a href="#/login">Se connecter</a>
        </div>

        <div class="alert alert-danger" id="errorBox" hidden></div>

        <form id="onboardingForm" class="public-form-stack">
          <div>
            <label class="form-label">Serveur backend</label>
            <input class="form-control" name="api_base" type="url" value="${escapeHtml(getApiBase())}" required>
          </div>
          <div class="public-grid-two">
            <div>
              <label class="form-label">Nom & Prénoms</label>
              <input class="form-control" name="full_name" required>
            </div>
            <div>
              <label class="form-label">Email</label>
              <input class="form-control" name="email" type="email" autocomplete="email" placeholder="client@mail.com">
            </div>
          </div>
          <div class="public-grid-two">
            <div>
              <label class="form-label">Contact client</label>
              <input class="form-control" name="phone" placeholder="+225 01 XX XX XX XX" autocomplete="tel" required>
            </div>
            <div>
              <label class="form-label">Mot de passe</label>
              <input class="form-control" name="password" type="password" autocomplete="new-password" minlength="6" required>
            </div>
          </div>
          <div class="public-grid-two">
            <div>
              <label class="form-label">Ville</label>
              <input class="form-control" name="city" required>
            </div>
            <div>
              <label class="form-label">Commune / Quartier</label>
              <input class="form-control" name="district" required>
            </div>
          </div>
          <div>
            <label class="form-label">N° Abonnement</label>
            <input class="form-control" name="subscription_number" required>
          </div>
          <div class="public-location-card">
            <div class="public-location-head">
              <div>
                <strong>Position géographique domicile</strong>
                <div class="text-body-secondary small">Touchez la carte ou utilisez votre position actuelle.</div>
              </div>
              <button class="btn btn-outline-secondary btn-sm" type="button" id="btnLocate">Utiliser ma position</button>
            </div>
            <div class="public-grid-two public-location-fields">
              <div>
                <label class="form-label">Latitude</label>
                <input class="form-control" name="home_lat" id="homeLat" required>
              </div>
              <div>
                <label class="form-label">Longitude</label>
                <input class="form-control" name="home_lng" id="homeLng" required>
              </div>
            </div>
            <div class="public-map" id="homeMap"></div>
          </div>
          <button class="btn btn-primary public-cta" type="submit">Créer mon espace client</button>
        </form>
      </div>
    </section>
  `;

  const form = root.querySelector('#onboardingForm');
  const errorBox = root.querySelector('#errorBox');
  const homeLat = root.querySelector('#homeLat');
  const homeLng = root.querySelector('#homeLng');
  const homeMap = root.querySelector('#homeMap');
  const setCoordinates = (lat, lng) => {
    homeLat.value = String(lat.toFixed(7));
    homeLng.value = String(lng.toFixed(7));
  };

  setCoordinates(5.3599517, -4.0082563);
  ensureMap(homeMap, Number(homeLat.value), Number(homeLng.value), setCoordinates);

  root.querySelector('#btnLocate').addEventListener('click', () => {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;
      setCoordinates(lat, lng);
      ensureMap(homeMap, lat, lng, setCoordinates);
    }, () => {
      errorBox.hidden = false;
      errorBox.textContent = 'Impossible de récupérer la position actuelle. Vérifiez les autorisations GPS.';
    }, {
      enableHighAccuracy: true,
      timeout: 12000,
    });
  });

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    errorBox.hidden = true;

    const payload = Object.fromEntries(new FormData(form).entries());
    setApiBase(payload.api_base);

    try {
      const response = await registerClient(payload);
      if (!response?.ok || !response?.token) {
        throw new Error('register_failed');
      }
      setSession(response.token, response.client);
      onRegistered();
    } catch (error) {
      errorBox.hidden = false;
      errorBox.textContent = error?.status
        ? 'Impossible de créer votre espace client. Vérifiez les informations envoyées.'
        : 'Serveur e-Intervention injoignable. Vérifiez l\'URL backend et le réseau.';
    }
  });
}

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