const { Button: MB, Icon: MI, Field: MField } = window.EPCMDesignSystem_e7f830;

const SLACK_WEBHOOK = 'https://hooks.slack.com/triggers/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';

/* Slack workflow triggers do not send CORS headers, so the JSON POST is fired
   with a simple content type (no preflight) and an opaque no-cors fallback. */
async function sendToSlack(payload) {
  return fetch(SLACK_WEBHOOK, { method: 'POST', mode: 'no-cors', body: JSON.stringify(payload), keepalive: true });
}

function BookingModal({ open, onClose, lang }) {
  const fr = lang === 'fr';
  const [done, setDone] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  React.useEffect(() => { if (open) { setDone(false); setSending(false); } }, [open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const f = new FormData(e.target);
    const payload = {
      full_name: (f.get('full_name') || '').toString().trim(),
      phone: (f.get('phone') || '').toString().trim(),
      postal_code: (f.get('postal_code') || '').toString().trim().toUpperCase(),
      service: (f.get('service') || '').toString(),
      preferred_date: (f.get('preferred_date') || '').toString().trim(),
      issue: (f.get('issue') || '').toString().trim(),
      language: fr ? 'FR' : 'EN',
      page_url: window.location.href,
      submitted_at: new Date().toISOString()
    };
    setSending(true);
    try { await sendToSlack(payload); } catch (err) { console.warn('Slack submit failed', err); }
    setSending(false);
    setDone(true);
  };
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(8,8,11,0.72)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '5vh 20px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: 560, background: 'var(--surface-1)', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-xl)', overflow: 'hidden', position: 'relative' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'var(--gradient-hero)', opacity: 0.45, pointerEvents: 'none' }} />
        <div style={{ position: 'relative', padding: 'clamp(1.75rem,4vw,2.5rem)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
            <div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--accent)' }}>{fr ? 'Réservation EPCM' : 'EPCM Booking'}</span>
              <h3 style={{ marginTop: 10, fontSize: '1.6rem', fontWeight: 500, letterSpacing: '-0.02em' }}>{done ? (fr ? 'Demande reçue' : 'Request received') : (fr ? 'Planifiez votre service' : 'Schedule your service')}</h3>
            </div>
            <button onClick={onClose} aria-label="Close" style={{ flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 40, height: 40, borderRadius: 'var(--radius-sm)', background: 'var(--surface-2)', border: '1px solid var(--border-strong)', color: 'var(--text)', cursor: 'pointer' }}><MI name="x" size={20} /></button>
          </div>

          {done ? (
            <div style={{ marginTop: 24 }}>
              <div style={{ display: 'inline-flex', width: 60, height: 60, borderRadius: 999, background: 'rgba(79,178,134,0.16)', border: '1px solid rgba(79,178,134,0.4)', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}><MI name="check" size={30} color="#7BD3AC" strokeWidth={2.4} /></div>
              <p style={{ color: 'var(--text-secondary)', fontSize: '1.05rem', lineHeight: 1.6 }}>{fr ? 'Merci! Un technicien certifié d’EPCM confirmera votre rendez-vous sous peu. Pour une urgence, appelez le ' : 'Thanks! A certified EPCM technician will confirm your appointment shortly. For urgent service, call '}<a href="tel:+14503281110" style={{ color: 'var(--accent)' }}>(450) 328-1110</a>.</p>
              <div style={{ marginTop: 26 }}><MB variant="primary" full onClick={onClose}>{fr ? 'Terminé' : 'Done'}</MB></div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ marginTop: 24, display: 'grid', gap: 16 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <MField name="postal_code" label={fr ? 'Code postal' : 'Postal code'} placeholder="H7R 1W6" required />
                <MField name="service" label="Service" type="select" options={fr ? ['Chauffage', 'Climatisation', 'Thermopompe', 'Entretien', 'Autre'] : ['Heating', 'Air Conditioning', 'Heat Pump', 'Maintenance', 'Other']} />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <MField name="full_name" label={fr ? 'Nom complet' : 'Full name'} placeholder="Jane Tremblay" required />
                <MField name="phone" label={fr ? 'Téléphone' : 'Phone'} type="tel" placeholder="(450) 000-0000" required />
              </div>
              <MField name="preferred_date" label={fr ? 'Date souhaitée' : 'Preferred date'} type="text" placeholder={fr ? 'ex. 12 avril, matin' : 'e.g. April 12, morning'} />
              <MField name="issue" label={fr ? 'Décrivez le besoin' : 'Tell us about the issue'} type="textarea" rows={3} placeholder={fr ? 'Décrivez brièvement votre besoin…' : 'Briefly describe what you need…'} />
              <MB variant="primary" size="lg" uppercase full iconRight="arrow-right" as="button" type="submit" disabled={sending}>{sending ? (fr ? 'Envoi en cours…' : 'Sending…') : (fr ? 'Demander un rendez-vous' : 'Request appointment')}</MB>
              <p style={{ textAlign: 'center', fontSize: '0.82rem', color: 'var(--text-muted)' }}>{fr ? 'Sans engagement · Prix clairs · Techniciens certifiés' : 'No obligation · Upfront pricing · Certified technicians'}</p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
