/* ============================================================
   VANTIK — Páginas: Proyectos, Nosotros, Contacto
   ============================================================ */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

/* ---- Envío de formulario → POST /api/contact (Cloudflare Pages Function) ---- */
async function submitContactForm(payload) {
  const res = await fetch('/api/contact', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  const data = await res.json();
  if (!res.ok || !data.ok) {
    throw new Error(data.error || 'Error desconocido al enviar el mensaje.');
  }
  return data;
}

/* ---- Modal de proyecto ---- */
function ProjectModal({ project, onClose }) {
  const closeRef = useRefB(null);

  useEffectB(() => {
    document.body.style.overflow = 'hidden';
    if (closeRef.current) closeRef.current.focus();
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  const onOverlayClick = (e) => { if (e.target === e.currentTarget) onClose(); };

  return (
    <div className="v-overlay" onClick={onOverlayClick} role="dialog" aria-modal="true" aria-label={project.title}>
      <div className="v-modal">
        <button className="v-modal__close" ref={closeRef} onClick={onClose} aria-label="Cerrar">
          <Icon name="x" size={18} strokeWidth={2} />
        </button>
        <div className="v-modal__media">
          <Img imgKey={project.img} label={project.title} />
        </div>
        <div className="v-modal__body">
          {project.tag && <span className="v-modal__tag">{project.tag}</span>}
          <h2 className="v-modal__title">{project.title}</h2>
          <p className="v-modal__desc">{project.desc || project.text}</p>
          {project.capabilities && project.capabilities.length > 0 && (
            <>
              <div className="v-modal__caps-label">CAPACIDADES APLICADAS</div>
              <div className="v-modal__caps">
                {project.capabilities.map((c) => (
                  <span className="v-modal__cap" key={c}>{c}</span>
                ))}
              </div>
            </>
          )}
          <a href="#/contacto" className="v-btn v-btn--solid" onClick={onClose}>
            CONSULTAR POR ESTE PROYECTO
          </a>
        </div>
      </div>
    </div>
  );
}

/* =================== PROYECTOS =================== */
function PageProyectos() {
  const [filter, setFilter] = useStateB('TODOS');
  const [selected, setSelected] = useStateB(null);
  const list = filter === 'TODOS' ? PROJECTS : PROJECTS.filter((p) => p.tag === filter);
  return (
    <main>
      <PageHeader title={PROYECTOS_HEAD.title} subtitle={PROYECTOS_HEAD.subtitle} />
      <section className="v-section">
        <div className="v-wrap">
          <div className="v-filters" role="group" aria-label="Filtrar proyectos">
            {PROJECT_FILTERS.map((f) => (
              <button
                key={f}
                className={'v-filter ' + (filter === f ? 'is-active' : '')}
                aria-pressed={filter === f}
                onClick={() => setFilter(f)}
              >{f}</button>
            ))}
          </div>
          <div className="v-grid v-grid--3">
            {list.map((p) => (
              <PhotoCard
                key={p.title}
                img={p.img} tag={p.tag} title={p.title} text={p.text}
                cta="VER MÁS"
                onClick={() => setSelected(p)}
                onCta={() => setSelected(p)}
              />
            ))}
          </div>
        </div>
      </section>
      {selected && <ProjectModal project={selected} onClose={() => setSelected(null)} />}
    </main>
  );
}

/* =================== NOSOTROS =================== */
function PageNosotros() {
  return (
    <main>
      {/* Bloque superior: azul izquierda + imagen derecha */}
      <section className="v-about">
        <div className="v-wrap v-about__inner">
          <div className="v-about__panel v-reveal-left">
            <Kicker>{ABOUT.kicker}</Kicker>
            <h1 className="v-about__title">{ABOUT.title}</h1>
            <p className="v-about__text">{ABOUT.text}</p>
          </div>
          <div className="v-about__media v-reveal-right"><Img imgKey="heroNosotros" /></div>
        </div>
      </section>

      {/* Banda de conceptos */}
      <ConceptBand items={CONCEPTS} />

      {/* Misión y Visión */}
      <section className="v-section">
        <div className="v-wrap v-mv">
          <div className="v-mv__text v-reveal-left">
            <h2 className="v-h3">{MISION_TITLE}</h2>
            <p>{MISION}</p>
            <h2 className="v-h3">{VISION_TITLE}</h2>
            <p>{VISION}</p>
          </div>
          <div className="v-mv__imgs v-reveal-right">
            <Img imgKey="nosMision" />
            <Img imgKey="nosVision" />
          </div>
        </div>
      </section>

      {/* Valores */}
      <section className="v-section v-section--alt">
        <div className="v-wrap">
          <SectionHead title={VALUES_TITLE} />
          <div className="v-values">
            {VALUES.map((v, i) => {
              const delay = i < 3 ? ' v-reveal-delay-' + (i + 1) : '';
              return (
                <div className={'v-value v-reveal' + delay} key={v.label}>
                  <div className="v-value__icon"><Icon name={v.icon} size={32} strokeWidth={1.5} /></div>
                  <div className="v-value__label">{v.label}</div>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    </main>
  );
}

/* =================== CONTACTO =================== */
function validateContactForm(data) {
  const errs = {};
  if (!data.nombre || !data.nombre.trim()) errs.nombre = 'El nombre es obligatorio.';
  if (!data.correo || !data.correo.trim()) {
    errs.correo = 'El correo electrónico es obligatorio.';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.correo.trim())) {
    errs.correo = 'Ingresa un correo electrónico válido.';
  }
  if (!data.mensaje || !data.mensaje.trim()) errs.mensaje = 'El mensaje es obligatorio.';
  return errs;
}

function PageContacto() {
  const [status, setStatus]             = useStateB('idle'); // idle | sending | sent | error
  const [errors, setErrors]             = useStateB({});
  const [turnstileToken, setTsToken]    = useStateB('');
  const [tsRequired, setTsRequired]     = useStateB(false);
  const formRef        = useRefB(null);
  const tsContainerRef = useRefB(null);
  const tsWidgetId     = useRefB(null);

  // Ciclo de vida del widget Turnstile (renderizado explícito)
  useEffectB(() => {
    let active = true;

    function mountWidget() {
      if (!active || !tsContainerRef.current || tsWidgetId.current !== null) return;
      if (!window.turnstile) return;
      tsWidgetId.current = window.turnstile.render(tsContainerRef.current, {
        sitekey:            SITE_CONFIG.turnstileSiteKey,
        callback:           (t) => { if (active) setTsToken(t); },
        'expired-callback': ()  => { if (active) setTsToken(''); },
        'error-callback':   ()  => { if (active) setTsToken(''); },
        theme:    'light',
        size:     'flexible',
        language: 'es',
      });
    }

    if (window.turnstile) {
      mountWidget();
    } else {
      const poll = setInterval(() => {
        if (window.turnstile) { clearInterval(poll); mountWidget(); }
      }, 150);
      return () => {
        active = false;
        clearInterval(poll);
        if (tsWidgetId.current !== null && window.turnstile) {
          window.turnstile.remove(tsWidgetId.current);
          tsWidgetId.current = null;
        }
      };
    }

    return () => {
      active = false;
      if (tsWidgetId.current !== null && window.turnstile) {
        window.turnstile.remove(tsWidgetId.current);
        tsWidgetId.current = null;
      }
    };
  }, []);

  function resetTurnstile() {
    setTsToken('');
    setTsRequired(false);
    if (tsWidgetId.current !== null && window.turnstile) {
      window.turnstile.reset(tsWidgetId.current);
    }
  }

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending' || status === 'sent') return;

    const raw  = Object.fromEntries(new FormData(e.target));
    const errs = validateContactForm(raw);
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    if (!turnstileToken) { setTsRequired(true); return; }
    setTsRequired(false);

    setStatus('sending');
    try {
      await submitContactForm({
        nombre:         (raw.nombre   || '').trim(),
        email:          (raw.correo   || '').trim(),
        empresa:        (raw.empresa  || '').trim(),
        telefono:       (raw.telefono || '').trim(),
        asunto:         (raw.asunto   || '').trim(),
        mensaje:        (raw.mensaje  || '').trim(),
        _hp:            raw._hp || '',
        turnstileToken,
      });
      setStatus('sent');
    } catch {
      setStatus('error');
      resetTurnstile();
    }
  };

  return (
    <main>
      <PageHeader title={CONTACTO_HEAD.title} subtitle={CONTACTO_HEAD.subtitle} />
      <section className="v-section">
        <div className="v-wrap v-contact">
          <div className="v-contact__info v-reveal-left">
            <ContactRow icon="pin"  label="DIRECCIÓN" value={CONTACT.ciudad} />
            <ContactRow icon="mail" label="CORREO"    value={CONTACT.correo} />
            {CONTACT.telefono && <ContactRow icon="phone" label="TELÉFONO" value={CONTACT.telefono} />}
            {CONTACT.horario  && <ContactRow icon="clock" label="HORARIO"  value={CONTACT.horario} />}
          </div>
          <div className="v-contact__map v-reveal-right">
            <div className="v-map__fallback" aria-hidden="true">
              <Icon name="pin" size={30} />
              <span>MAPA · PUERTO MONTT</span>
            </div>
            <iframe
              title="Mapa — Puerto Montt, Chile"
              className="v-map"
              loading="lazy"
              src="https://www.openstreetmap.org/export/embed.html?bbox=-73.13%2C-41.52%2C-72.78%2C-41.40&layer=mapnik&marker=-41.4717%2C-72.9369"
            ></iframe>
          </div>
        </div>

        <div className="v-wrap">
          <div className="v-formwrap v-reveal">
            <h2 className="v-h3">{CONTACT_FORM_TITLE}</h2>
            {status === 'sent' ? (
              <div className="v-formok" role="status">{CONTACT_OK}</div>
            ) : (
              <form className="v-form" onSubmit={onSubmit} noValidate ref={formRef}>
                {/* Honeypot anti-spam: campo oculto, debe permanecer vacío */}
                <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 0, height: 0, overflow: 'hidden' }}>
                  <input name="_hp" type="text" tabIndex={-1} autoComplete="off" />
                </div>

                {CONTACT_FIELDS.map((f) => (
                  <Field key={f.name} label={f.label} name={f.name}
                    type={f.type} textarea={f.textarea} full={f.full}
                    error={errors[f.name]} />
                ))}

                {/* Cloudflare Turnstile — renderizado explícito */}
                <div style={{ gridColumn: '1 / -1', marginTop: '4px' }}>
                  <div ref={tsContainerRef} style={{ minHeight: '65px' }} />
                  {tsRequired && !turnstileToken && (
                    <span className="v-field__error" role="alert" style={{ display: 'block', marginTop: '4px' }}>
                      Por favor completa la verificación antes de enviar.
                    </span>
                  )}
                </div>

                {status === 'error' && (
                  <div className="v-form__error" role="alert">
                    No se pudo enviar el mensaje. Por favor inténtalo nuevamente o escríbenos a {CONTACT.correo}.
                  </div>
                )}
                <div className="v-form__actions">
                  <button type="submit" className="v-btn v-btn--solid"
                    disabled={status === 'sending'}>
                    {status === 'sending' ? 'ENVIANDO…' : CONTACT_SUBMIT}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

function ContactRow({ icon, label, value }) {
  return (
    <div className="v-crow">
      <div className="v-crow__icon"><Icon name={icon} size={22} /></div>
      <div>
        <div className="v-crow__label">{label}</div>
        <div className="v-crow__value">{value}</div>
      </div>
    </div>
  );
}

function Field({ label, name, type = 'text', textarea, full, error }) {
  const errId = name + '-err';
  return (
    <label className={'v-field ' + (full ? 'v-field--full' : '') + (error ? ' v-field--error' : '')}>
      <span className="v-field__label">{label}</span>
      {textarea
        ? <textarea name={name} rows="5" aria-describedby={error ? errId : undefined} aria-invalid={error ? 'true' : undefined} />
        : <input type={type} name={name} aria-describedby={error ? errId : undefined} aria-invalid={error ? 'true' : undefined} />}
      {error && <span className="v-field__error" id={errId} role="alert">{error}</span>}
    </label>
  );
}

Object.assign(window, { submitContactForm, ProjectModal, PageProyectos, PageNosotros, PageContacto });
