---
import BaseLayout from '@/layouts/BaseLayout.astro';
import SectionEyebrow from '@/components/SectionEyebrow.astro';
import { getLangFromUrl, useTranslations } from '@/i18n/utils';

const lang = getLangFromUrl(Astro.url);
const t = useTranslations(lang);
const whatsappUrl = 'https://wa.me/59899812487';
const reCAPTCHA_site_key = '6LeOxaEaAAAAAPD8rQQLqw4woxn1dMjvF_Ooy0BG';
---
<BaseLayout
  title={lang === 'en' ? 'Contact' : 'Contacto'}
  description={lang === 'en'
    ? 'Talk to a real person at Hosting del Sur. WhatsApp, email or form.'
    : 'Hablá con una persona real en Hosting del Sur. WhatsApp, mail o formulario.'}
  lang={lang}
>
  <section class="pt-20 pb-12 md:pt-28 md:pb-16" style="background: var(--hds-bg-soft);">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <SectionEyebrow text={lang === 'en' ? 'Contact' : 'Contacto'} />
      <h1 class="font-display leading-tight mt-5" style="font-size: clamp(2.5rem, 6vw, 4.5rem); color: var(--hds-fg);">
        {lang === 'en'
          ? <>Talk to a <span style="color: var(--color-hds-naranja); font-style: italic;">real person</span>.</>
          : <>Hablá con una <span style="color: var(--color-hds-naranja); font-style: italic;">persona real</span>.</>}
      </h1>
      <p class="text-lg mt-5 max-w-2xl" style="color: var(--hds-fg-soft);">
        {lang === 'en'
          ? 'No bots, no tickets. Write to us on WhatsApp, email us, or fill out the form below.'
          : 'Sin bots, sin tickets. Escribinos por WhatsApp, mandanos un mail o completá el formulario.'}
      </p>
    </div>
  </section>

  <section class="py-20 md:py-24" style="background: var(--hds-bg);">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <aside class="lg:col-span-1 space-y-4">
          <div class="rounded-2xl p-6" style="background: var(--hds-card); border: 1px solid var(--hds-line);">
            <h2 class="text-xs font-semibold tracking-[0.25em] uppercase mb-3" style="color: var(--color-hds-naranja);">WhatsApp</h2>
            <a href={whatsappUrl} target="_blank" rel="noopener noreferrer" class="text-lg font-semibold hover:underline break-all" style="color: var(--color-hds-naranja);">+598 99 812 487</a>
            <p class="text-sm mt-2" style="color: var(--hds-fg-soft);">
              {lang === 'en' ? 'Monday to Friday, 10 to 18 hs UYT' : 'Lunes a viernes, 10 a 18 hs UYT'}
            </p>
          </div>

          <div class="rounded-2xl p-6" style="background: var(--hds-card); border: 1px solid var(--hds-line);">
            <h2 class="text-xs font-semibold tracking-[0.25em] uppercase mb-3" style="color: var(--color-hds-naranja);">Email</h2>
            <a href="mailto:contacto@hostingdelsur.net" class="text-lg font-semibold hover:underline break-all" style="color: var(--color-hds-naranja);">contacto@hostingdelsur.net</a>
          </div>

          <div class="rounded-2xl p-6" style="background: var(--hds-card); border: 1px solid var(--hds-line);">
            <h2 class="text-xs font-semibold tracking-[0.25em] uppercase mb-3" style="color: var(--color-hds-naranja);">{lang === 'en' ? 'Location' : 'Ubicación'}</h2>
            <p style="color: var(--hds-fg-soft);">Maldonado, Uruguay</p>
          </div>
        </aside>

        <div class="lg:col-span-2">
          <form
            action="/api/contact.php"
            method="POST"
            class="rounded-2xl p-8 md:p-10 space-y-5"
            style="background: var(--hds-card); border: 1px solid var(--hds-line);"
            id="contact-form"
            novalidate
          >
            <input type="hidden" name="lang" value={lang} />
            <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response" />
            <div class="absolute -left-[9999px]" aria-hidden="true">
              <label for="website">Website</label>
              <input type="text" id="website" name="website" tabindex="-1" autocomplete="off" />
            </div>

            <div>
              <label for="name" class="block text-sm font-medium mb-1.5" style="color: var(--hds-fg);">
                {lang === 'en' ? 'Name' : 'Nombre'} <span style="color: var(--color-hds-error);">*</span>
              </label>
              <input
                type="text"
                id="name"
                name="name"
                required
                autocomplete="name"
                maxlength="100"
                class="w-full px-3.5 py-2.5 rounded-md outline-none transition-colors"
                style="background: var(--hds-bg); color: var(--hds-fg); border: 1px solid var(--hds-line);"
              />
            </div>

            <div>
              <label for="email" class="block text-sm font-medium mb-1.5" style="color: var(--hds-fg);">
                Email <span style="color: var(--color-hds-error);">*</span>
              </label>
              <input
                type="email"
                id="email"
                name="email"
                required
                autocomplete="email"
                maxlength="200"
                class="w-full px-3.5 py-2.5 rounded-md outline-none transition-colors"
                style="background: var(--hds-bg); color: var(--hds-fg); border: 1px solid var(--hds-line);"
              />
            </div>

            <div>
              <label for="message" class="block text-sm font-medium mb-1.5" style="color: var(--hds-fg);">
                {lang === 'en' ? 'Message' : 'Mensaje'} <span style="color: var(--color-hds-error);">*</span>
              </label>
              <textarea
                id="message"
                name="message"
                required
                rows="5"
                maxlength="5000"
                class="w-full px-3.5 py-2.5 rounded-md outline-none transition-colors resize-y"
                style="background: var(--hds-bg); color: var(--hds-fg); border: 1px solid var(--hds-line);"
              ></textarea>
            </div>

            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pt-2">
              <p class="text-xs" style="color: var(--hds-fg-muted);">
                {lang === 'en' ? 'We typically reply within 24 business hours.' : 'Respondemos típicamente dentro de las 24 hs hábiles.'}
              </p>
              <button type="submit" class="btn-primary text-sm">
                <span id="contact-submit-label">{lang === 'en' ? 'Send message' : 'Enviar mensaje'}</span>
              </button>
            </div>

            <div id="contact-status" role="status" aria-live="polite" class="hidden text-sm"></div>
          </form>
        </div>
      </div>
    </div>
  </section>

  <script src={`https://www.google.com/recaptcha/api.js?render=${reCAPTCHA_site_key}`} async defer></script>
  <noscript>
    <p class="text-xs mt-2" style="color: var(--color-hds-error);">JavaScript is required for the form to work.</p>
  </noscript>
  <script is:inline define:vars={{ siteKey: reCAPTCHA_site_key }}>
    (function() {
      const form = document.getElementById('contact-form');
      if (!form) return;
      const status = document.getElementById('contact-status');
      const submit = form.querySelector('button[type="submit"]');
      const label = document.getElementById('contact-submit-label');
      const langInput = form.querySelector('input[name="lang"]');
      const isEn = langInput && langInput.value === 'en';
      const sendingLabel = isEn ? 'Sending…' : 'Enviando…';
      const successMsg = isEn ? 'Message sent. We will reply soon.' : 'Mensaje enviado. Te respondemos pronto.';
      const errorMsg = isEn ? 'Could not send. Please try again or contact us via WhatsApp.' : 'No se pudo enviar. Probá de nuevo o contactanos por WhatsApp.';

      window.addEventListener('load', () => {
        if (window.grecaptcha && window.grecaptcha.ready) {
          window.grecaptcha.ready();
        }
      });

      form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const originalLabel = label.textContent;
        label.textContent = sendingLabel;
        submit.disabled = true;
        status.classList.remove('hidden');
        status.className = 'text-sm';
        status.textContent = '';
        status.style.color = 'var(--hds-fg-soft)';

        try {
          let token = '';
          if (window.grecaptcha && window.grecaptcha.execute) {
            try {
              token = await Promise.race([
                window.grecaptcha.execute(siteKey, { action: 'contact' }),
                new Promise((_, reject) => setTimeout(() => reject(new Error('recaptcha timeout')), 5000)),
              ]);
            } catch (e) { /* fall through without token */ }
          }
          document.getElementById('g-recaptcha-response').value = token || '';

          const formData = new FormData(form);
          const res = await fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'fetch' },
          });
          const data = await res.json().catch(() => ({}));
          if (res.ok && data.ok) {
            status.style.color = 'var(--color-hds-exito)';
            status.textContent = successMsg;
            form.reset();
          } else {
            throw new Error(data.error || 'error');
          }
        } catch (err) {
          status.style.color = 'var(--color-hds-error)';
          status.textContent = errorMsg;
        } finally {
          label.textContent = originalLabel;
          submit.disabled = false;
        }
      });
    })();
  </script>
</BaseLayout>
