import { loginClient, getApiBase, setApiBase } from '../api.js';
import { setSession } from '../auth.js';

export async function renderLogin(root, onLoggedIn) {
  root.innerHTML = `
    <section class="public-auth-shell public-auth-shell-login">
      <div class="public-auth-card public-auth-card-login">
        <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">Connexion client</span>
          <h1>Accéder à mon espace</h1>
          <p>Consultez vos déclarations, suivez la prise en charge et échangez avec le service intervention depuis votre espace client.</p>
        </div>

        <div class="public-auth-switch">
          <span>Vous n'avez pas encore de compte ?</span>
          <a href="#/register">Créer un compte</a>
        </div>

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

        <form id="loginForm" 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>
            <label class="form-label">Contact client ou email</label>
            <input class="form-control" name="login" autocomplete="username" placeholder="+225 01 XX XX XX XX ou client@mail.com" required>
          </div>
          <div>
            <label class="form-label">Mot de passe</label>
            <input class="form-control" name="password" type="password" autocomplete="current-password" required>
          </div>
          <button class="btn btn-primary public-cta" type="submit">Se connecter</button>
        </form>
      </div>
    </section>
  `;

  const form = root.querySelector('#loginForm');
  const errorBox = root.querySelector('#errorBox');
  const successBox = root.querySelector('#successBox');

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

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

    try {
      const response = await loginClient(payload);
      if (!response?.ok || !response?.token) {
        throw new Error('login_failed');
      }

      setSession(response.token, response.client);
      successBox.hidden = false;
      successBox.textContent = 'Connexion établie.';
      onLoggedIn();
    } catch (error) {
      errorBox.hidden = false;
      errorBox.textContent = error?.status
        ? 'Compte introuvable ou mot de passe invalide.'
        : '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;');
}
