// ===== RIVAMAR Group — Convenios B2B / Cotización Delegaciones =====
const { useState } = React;

function Convenios({ go, data, onCotizar }) {
  const cdata = data || {};
  const beneficios = cdata.beneficios || [];
  const [form, setForm] = useState({ empresa: '', rut: '', contacto: '', correo: '', telefono: '', local: '', pax: '20-50', colaboradores: '', fecha: '', mensaje: '' });
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const valid = form.empresa && form.contacto && form.correo && form.telefono;

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    const id = 'COT-' + Math.floor(1000 + Math.random() * 9000);
    const cot = { ...form, id, estado: 'nueva', fecha_solicitud: new Date().toISOString() };
    try { onCotizar && onCotizar(cot); } catch (err) {}
    try {
      enviarCorreoReserva({
        id, nombre: form.contacto, empresa: form.empresa, correo: form.correo, telefono: form.telefono,
        local: form.local || 'rivamar', fecha: form.fecha || 'Por definir', hora: '—',
        pax: form.colaboradores || form.pax, exponor: false,
        comentarios: 'COTIZACIÓN B2B — ' + form.pax + ' pax. ' + (form.mensaje || ''),
      });
    } catch (err) {}
    setSent(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const site = (typeof window !== 'undefined' && window.SITE) || {};
  const waNum = site.whatsapp || '56964979087';
  const correoDest = site.email_destino || site.contacto_correo || 'contacto@rivamar.cl';
  const resumenB2B = [
    '*Cotización B2B*',
    `Empresa: ${form.empresa}`,
    form.rut ? `RUT: ${form.rut}` : '',
    `Contacto: ${form.contacto}`,
    `Correo: ${form.correo}`,
    `Teléfono: ${form.telefono}`,
    `Delegación: ${form.pax} pax`,
    form.fecha ? `Fecha estimada: ${form.fecha}` : '',
    form.mensaje ? `Detalle: ${form.mensaje}` : '',
  ].filter(Boolean).join('\n');
  const waB2B = `https://wa.me/${waNum}?text=${encodeURIComponent(resumenB2B)}`;
  const mailB2B = `mailto:${correoDest}?subject=${encodeURIComponent('Cotización B2B — ' + form.empresa)}&body=${encodeURIComponent(resumenB2B.replace(/\*/g, ''))}`;

  if (sent) {
    return (
      <main className="max-w-lg mx-auto px-5 py-20 text-center">
        <div className="grid place-items-center w-20 h-20 rounded-full bg-gold/15 border border-gold/30 mx-auto mb-6">
          <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="#D4A52C" strokeWidth="2"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg>
        </div>
        <h2 className="font-display text-3xl font-extrabold text-gray-50">Cotización enviada</h2>
        <p className="mt-3 text-gray-400">
          Recibimos la solicitud de <span className="text-gray-200">{form.empresa}</span>. Una alerta prioritaria fue enviada a nuestro equipo de convenios; te contactaremos dentro de las próximas horas hábiles.
        </p>
        <div className="mt-6 inline-flex items-center gap-2 text-sm px-3 py-1.5 rounded-full bg-orange-500/15 text-orange-400">
          <span className="w-1.5 h-1.5 rounded-full bg-orange-400"></span> Prioridad alta · delegación {form.pax} pax
        </div>

        {/* Activación de la cotización */}
        <div className="mt-7 bg-steel/40 border border-gold/20 rounded-xl p-5 text-left">
          <p className="text-sm font-semibold text-gray-100 flex items-center gap-2">
            <span className="grid place-items-center w-6 h-6 rounded-full bg-gold/20 text-gold text-xs font-bold">!</span>
            Acelera tu cotización
          </p>
          <p className="text-xs text-gray-400 mt-1.5 leading-relaxed">Envíala directo a nuestro equipo de convenios por WhatsApp o correo y te respondemos antes.</p>
          <div className="mt-4 flex flex-col sm:flex-row gap-2.5">
            <a href={waB2B} target="_blank" rel="noopener" className="flex-1 inline-flex items-center justify-center gap-2 min-h-[44px] px-4 rounded-lg bg-[#25D366] text-white font-semibold text-sm hover:brightness-110 transition-all">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.2-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.8-2-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2s.9 2.5 1.1 2.7c.1.2 1.8 2.7 4.3 3.8.6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4M12 2a10 10 0 0 0-8.6 15l-1.4 5.1 5.2-1.4A10 10 0 1 0 12 2"/></svg>
              Enviar por WhatsApp
            </a>
            <a href={mailB2B} className="flex-1 inline-flex items-center justify-center gap-2 min-h-[44px] px-4 rounded-lg bg-white/5 border border-white/10 text-gray-100 font-semibold text-sm hover:bg-white/10 transition-all">
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
              Enviar por correo
            </a>
          </div>
        </div>

        <div className="mt-7">
          <Btn variant="primary" onClick={() => go('home')}>Volver al inicio</Btn>
        </div>
      </main>
    );
  }

  return (
    <main>
      <section className="border-b border-white/10 bg-iron/40">
        <div className="max-w-7xl mx-auto px-5 lg:px-8 py-16">
          <p className="text-xs font-semibold uppercase tracking-[0.28em] text-copper mb-3">Convenios empresariales · B2B</p>
          <h1 className="font-display text-3xl md:text-5xl font-extrabold text-gray-50 tracking-tight max-w-3xl leading-[1.08]">
            Cotización rápida para delegaciones mineras
          </h1>
          <p className="mt-4 text-base md:text-lg text-gray-400 max-w-2xl leading-relaxed">
            {cdata.intro}
          </p>
        </div>
      </section>

      <section className="max-w-7xl mx-auto px-5 lg:px-8 py-14 grid lg:grid-cols-[1fr_400px] gap-12 items-start">
        <div className="space-y-8">
          <div className="grid sm:grid-cols-3 gap-4">
            {beneficios.map(([t, d]) => (
              <div key={t} className="bg-iron border border-white/10 rounded-xl p-5">
                <div className="w-8 h-8 rounded-lg bg-copper/15 grid place-items-center mb-3">
                  <span className="w-2 h-2 rounded-full bg-copper"></span>
                </div>
                <h3 className="font-display font-bold text-gray-50 text-sm">{t}</h3>
                <p className="mt-1.5 text-xs text-gray-400 leading-relaxed">{d}</p>
              </div>
            ))}
          </div>

          <ImgSlot label="Estación de buffet corporativo — montaje para delegación minera" src={cdata.img2} tone="#B45309" ratio="2/1" className="w-full rounded-xl" />

          <div className="bg-iron border border-white/10 rounded-xl p-6">
            <h3 className="font-display font-bold text-gray-50 mb-4">Empresas que confían en RIVAMAR Group</h3>
            <div className="grid grid-cols-3 sm:grid-cols-4 gap-3">
              {['BHP', 'Codelco', 'Antofagasta\nMinerals', 'Komatsu', 'Finning', 'Sierra Gorda', 'Albemarle', 'SQM'].map((c) => (
                <div key={c} className="h-14 rounded-md bg-carbon border border-white/5 grid place-items-center text-center">
                  <span className="text-xs font-semibold text-gray-500 whitespace-pre-line leading-tight">{c}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Formulario de cotización */}
        <form onSubmit={submit} className="lg:sticky lg:top-24 bg-iron border border-white/10 rounded-xl p-6 space-y-4">
          <div className="flex items-center gap-2 pb-2">
            <span className="w-2 h-2 rounded-full bg-gold"></span>
            <h3 className="font-display font-bold text-gray-50">Solicitar cotización</h3>
          </div>
          <Field label="Empresa / Minera" required>
            <input className={inputCls} value={form.empresa} onChange={set('empresa')} placeholder="Ej. Antofagasta Minerals" />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="RUT empresa">
              <input className={inputCls} value={form.rut} onChange={set('rut')} placeholder="76.123.456-7" />
            </Field>
            <Field label="N° colaboradores" hint="Estimado">
              <input className={inputCls} value={form.colaboradores} onChange={set('colaboradores')} placeholder="Ej. 35" />
            </Field>
          </div>
          <Field label="Persona de contacto" required>
            <input className={inputCls} value={form.contacto} onChange={set('contacto')} placeholder="Nombre y cargo" />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Correo" required>
              <input type="email" className={inputCls} value={form.correo} onChange={set('correo')} placeholder="@empresa.cl" />
            </Field>
            <Field label="Teléfono" required>
              <input className={inputCls} value={form.telefono} onChange={set('telefono')} placeholder="+56 9 …" />
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Local preferido">
              <select className={inputCls} value={form.local} onChange={set('local')}>
                <option value="">Indistinto</option>
                {LOCALES.map((l) => <option key={l.id} value={l.id}>{l.nombre}</option>)}
              </select>
            </Field>
            <Field label="N° de personas">
              <select className={inputCls} value={form.pax} onChange={set('pax')}>
                <option value="20-50">20 a 50 pax</option>
                <option value="50-100">50 a 100 pax</option>
                <option value="100+">100+ pax</option>
              </select>
            </Field>
          </div>
          <Field label="Fecha estimada del evento">
            <input type="date" className={inputCls} value={form.fecha} onChange={set('fecha')} min="2026-05-29" />
          </Field>
          <Field label="Detalles del servicio">
            <textarea className={inputCls + ' !h-24 py-2.5 resize-none'} value={form.mensaje} onChange={set('mensaje')} placeholder="Tipo de evento, requerimientos especiales, convenio mensual…" />
          </Field>
          <Btn type="submit" variant="primary" disabled={!valid} className="w-full">Enviar Cotización Rápida</Btn>
          <p className="text-[11px] text-gray-500 text-center">Genera una alerta prioritaria al administrador de convenios.</p>
        </form>
      </section>
    </main>
  );
}

Object.assign(window, { Convenios });
