---
/**
 * Contact section — Minitel-themed, vanilla JS (no React runtime).
 */
import { TRACK_EVENTS, trackAttrs } from '@/lib/tracking';

const DEFAULT_MESSAGE = `Bonjour Clément,

J'ai un projet / besoin autour d'un système électronique spécifique.

Contexte :
Ce que j'attends :
Contraintes (délai, budget) :`;

// All contact goes through CRM form — no mailto
---

<section
  id="contact"
  aria-labelledby="contact-title"
  class="section-anchor mt-5"
  data-reveal
>
  <div class="contact-minitel">
    <div class="contact-minitel-header">
      <span class="contact-minitel-dot" aria-hidden="true"></span>
      <span class="contact-minitel-dot contact-minitel-dot--amber" aria-hidden="true"></span>
      <span class="contact-minitel-dot contact-minitel-dot--green" aria-hidden="true"></span>
      <span class="contact-minitel-title-bar">Contact</span>
    </div>

    <div class="contact-minitel-screen">
      <h2 id="contact-title" class="contact-minitel-h2">
        Parlons de votre projet
      </h2>

      <p class="contact-minitel-line">
        Décrivez votre besoin en quelques lignes.
      </p>
      <p class="contact-minitel-line contact-minitel-line--dim">
        Réponse sous 48h avec un premier retour technique.
      </p>

      <div data-contact-panel="form">
        <div id="contact-form-container">
          <form id="contact-crm-form" class="contact-minitel-form">
            <div class="contact-minitel-field">
              <label for="contact-form-name" class="contact-minitel-label">Nom</label>
              <input
                id="contact-form-name"
                type="text"
                required
                class="contact-minitel-input"
                autocomplete="name"
                placeholder="Votre nom"
              />
            </div>

            <div class="contact-minitel-field">
              <label for="contact-form-email" class="contact-minitel-label">Email</label>
              <input
                id="contact-form-email"
                type="email"
                required
                class="contact-minitel-input"
                autocomplete="email"
                placeholder="votre@email.com"
              />
            </div>

            <div class="contact-minitel-field">
              <label for="contact-form-phone" class="contact-minitel-label">Telephone</label>
              <input
                id="contact-form-phone"
                type="tel"
                class="contact-minitel-input"
                autocomplete="tel"
                placeholder="Optionnel"
              />
            </div>

            <div class="contact-minitel-field">
              <label for="contact-form-organization" class="contact-minitel-label">Structure</label>
              <input
                id="contact-form-organization"
                type="text"
                class="contact-minitel-input"
                autocomplete="organization"
                placeholder="Entreprise, atelier, compagnie, studio..."
              />
            </div>

            <div class="contact-minitel-field">
              <label for="contact-form-need-type" class="contact-minitel-label">Type de besoin</label>
              <select id="contact-form-need-type" class="contact-minitel-select" required>
                <option value="" selected disabled>Choisir le type de besoin</option>
                <option value="technique">Projet technique</option>
                <option value="formation">Formation</option>
                <option value="mixte">Projet mixte</option>
              </select>
            </div>

            <div class="contact-minitel-textarea-wrap">
              <label for="contact-form-message" class="contact-minitel-label">Message</label>
              <textarea
                id="contact-form-message"
                class="contact-minitel-textarea"
                required
                spellcheck="true"
                rows="8"
              >{DEFAULT_MESSAGE}</textarea>
            </div>

            <label class="contact-minitel-consent" for="contact-form-consent">
              <input id="contact-form-consent" type="checkbox" required />
              <span class="contact-minitel-consent-text">
                J'accepte que mes coordonnees soient utilisees pour traiter cette demande.
              </span>
            </label>

            <div class="contact-minitel-actions">
              <button
                type="submit"
                id="contact-form-submit"
                class="contact-minitel-btn contact-minitel-btn--primary"
              >
                Envoyer le message
              </button>
            </div>
            <p
              id="contact-form-error"
              class="contact-minitel-line"
              style="color:var(--accent-warn, #f59e0b);margin-top:0.5rem;display:none"
            >
              Une erreur est survenue. Veuillez reessayer.
            </p>
          </form>
        </div>

        <div id="contact-form-success" style="display:none;">
          <p class="contact-minitel-line" style="text-align:center;padding:2rem 0">
            Message envoye
          </p>
          <p class="contact-minitel-line contact-minitel-line--dim" style="text-align:center">
            Merci ! Je reviens vers vous sous 48h.
          </p>
          <div class="contact-minitel-actions" style="justify-content:center;margin-top:1rem">
            <button
              type="button"
              id="contact-form-reset"
              class="contact-minitel-btn"
            >
              Envoyer un autre message
            </button>
          </div>
        </div>
      </div>

      <div class="contact-minitel-footer">
        <p class="contact-minitel-line contact-minitel-line--dim">
          Electronique · automatisme · energie · diagnostic · formation
        </p>
        <p class="contact-minitel-line contact-minitel-line--dim">
          Vos donnees sont traitees de maniere securisee.
        </p>
      </div>
    </div>
  </div>
</section>

<script>
  const CRM_INTAKE_ENDPOINT = 'https://api.lelectronrare.fr/api/submit-lead';
  const DEFAULT_MESSAGE = `Bonjour Clément,

J'ai un projet / besoin autour d'un système électronique spécifique.

Contexte :
Ce que j'attends :
Contraintes (délai, budget) :`;

  const trackingWindow = window as Window & { dataLayer?: Array<Record<string, unknown>> };

  const pushTrackingEvent = (eventName: string, payload: Record<string, unknown> = {}) => {
    trackingWindow.dataLayer = trackingWindow.dataLayer || [];
    trackingWindow.dataLayer.push({
      event: eventName,
      event_category: 'engagement',
      event_label: eventName,
      page_path: window.location.pathname || '/',
      page_title: document.title || '',
      da_variant: document.documentElement.getAttribute('data-da-variant') || 'v12',
      ...payload,
    });
  };

  // All contact goes through CRM form — no tabs

  const form = document.getElementById('contact-crm-form') as HTMLFormElement;
  const formContainer = document.getElementById('contact-form-container') as HTMLElement;
  const formSuccess = document.getElementById('contact-form-success') as HTMLElement;
  const formError = document.getElementById('contact-form-error') as HTMLElement;
  const submitBtn = document.getElementById('contact-form-submit') as HTMLButtonElement;
  const nameInput = document.getElementById('contact-form-name') as HTMLInputElement;
  const emailInput = document.getElementById('contact-form-email') as HTMLInputElement;
  const phoneInput = document.getElementById('contact-form-phone') as HTMLInputElement;
  const organizationInput = document.getElementById('contact-form-organization') as HTMLInputElement;
  const needTypeInput = document.getElementById('contact-form-need-type') as HTMLSelectElement;
  const messageArea = document.getElementById('contact-form-message') as HTMLTextAreaElement;
  const consentInput = document.getElementById('contact-form-consent') as HTMLInputElement;

  const resetContactForm = () => {
    nameInput.value = '';
    emailInput.value = '';
    phoneInput.value = '';
    organizationInput.value = '';
    needTypeInput.value = '';
    messageArea.value = DEFAULT_MESSAGE;
    consentInput.checked = false;
  };

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    formError.style.display = 'none';
    formError.textContent = "Une erreur est survenue. Veuillez reessayer.";
    submitBtn.disabled = true;
    submitBtn.textContent = 'Envoi en cours...';

    const payload = {
      name: nameInput.value.trim(),
      email: emailInput.value.trim(),
      phone: phoneInput.value.trim() || undefined,
      organization: organizationInput.value.trim() || undefined,
      message: messageArea.value.trim(),
      sourceChannel: 'site',
      sourceDetail: 'contact_form',
      needType: needTypeInput.value,
      pagePath: `${window.location.pathname || '/'}${window.location.hash || ''}`,
      consent: consentInput.checked,
    };

    try {
      const response = await fetch(CRM_INTAKE_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const result = await response.json().catch(() => null);

      if (response.ok) {
        formContainer.style.display = 'none';
        formSuccess.style.display = '';
        pushTrackingEvent('contact_form_submit', {
          destination: CRM_INTAKE_ENDPOINT,
          source_detail: payload.sourceDetail,
          need_type: payload.needType,
        });
        resetContactForm();
      } else {
        const detail = result?.error?.message || result?.error?.code;
        formError.textContent = detail
          ? detail
          : "Une erreur est survenue. Veuillez reessayer.";
        formError.style.display = '';
        pushTrackingEvent('contact_form_error', {
          destination: CRM_INTAKE_ENDPOINT,
          source_detail: payload.sourceDetail,
          status_code: response.status,
        });
      }
    } catch {
      formError.style.display = '';
      pushTrackingEvent('contact_form_error', {
        destination: CRM_INTAKE_ENDPOINT,
        source_detail: payload.sourceDetail,
        status_code: 'network_error',
      });
    }

    submitBtn.disabled = false;
    submitBtn.textContent = 'Envoyer le message';
  });

  const resetBtn = document.getElementById('contact-form-reset') as HTMLButtonElement;
  resetBtn.addEventListener('click', () => {
    formSuccess.style.display = 'none';
    formContainer.style.display = '';
    formError.style.display = 'none';
  });
</script>
