const { Button: QB, Icon: QI, Field: QField } = window.EPCMDesignSystem_e7f830;

/* Quote requests go through our own endpoint (same relay the internal forms use),
   so no webhook URL is exposed in the frontend. */
function QuoteModal({ 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]);
  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;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const f = new FormData(e.target);
    f.append('form', 'quote');
    f.append('language', fr ? 'FR' : 'EN');
    f.append('page_url', window.location.href);
    setSending(true);
    try {
      await fetch('/api/submit.php', { method: 'POST', body: f });
    } catch (err) {
      console.warn('Quote relay failed', err);
    }
    setSending(false);
    setDone(true);
  };

  const projects = fr
    ? ['Installation de thermopompe', 'Installation de climatisation', 'Installation de fournaise ou chaudière', 'Conversion au mazout / biénergie', 'Nettoyage de conduits', 'Remplacement complet du système', 'Autre projet']
    : ['Heat pump installation', 'Air conditioning installation', 'Furnace or boiler installation', 'Oil conversion / bi-energy', 'Air duct cleaning', 'Full system replacement', 'Other project'];
  const timing = fr
    ? ['Dès que possible', 'Dans le prochain mois', 'Dans les 3 prochains mois', 'Je magasine seulement']
    : ['As soon as possible', 'Within a month', 'Within 3 months', 'Just comparing prices'];

  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: 620, 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 ? 'Soumission EPCM' : 'EPCM Quote'}</span>
              <h3 style={{ marginTop: 10, fontSize: '1.6rem', fontWeight: 500, letterSpacing: '-0.02em' }}>{done ? (fr ? 'Demande envoyée' : 'Request sent') : (fr ? 'Obtenez votre soumission gratuite' : 'Get your free quote')}</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' }}><QI 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 }}><QI 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 conseiller EPCM prépare votre soumission et vous revient sous 24 heures ouvrables. Pour aller plus vite, appelez le ' : 'Thanks! An EPCM advisor is preparing your quote and will get back to you within one business day. To move faster, call '}<a href="tel:+14503281110" style={{ color: 'var(--accent)' }}>(450) 328-1110</a>.</p>
              <div style={{ marginTop: 26 }}><QB variant="primary" full onClick={onClose}>{fr ? 'Terminé' : 'Done'}</QB></div>
            </div>
          ) : (
            <React.Fragment>
              <p style={{ marginTop: 14, color: 'var(--text-secondary)', fontSize: '0.98rem', lineHeight: 1.6 }}>{fr ? 'Prix clair et sans engagement, préparé par un technicien certifié RBQ. Subventions vérifiées pour vous.' : 'A clear, no-obligation price prepared by an RBQ-licensed technician. We check your grant eligibility too.'}</p>
              <form onSubmit={handleSubmit} style={{ marginTop: 22, display: 'grid', gap: 16 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="epcm-2col">
                  <QField name="full_name" label={fr ? 'Nom complet' : 'Full name'} placeholder="Jane Tremblay" required />
                  <QField name="phone" label={fr ? 'Téléphone' : 'Phone'} type="tel" placeholder="(450) 000-0000" required />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="epcm-2col">
                  <QField name="email" label={fr ? 'Courriel' : 'Email'} type="email" placeholder="jane@courriel.com" required />
                  <QField name="postal_code" label={fr ? 'Code postal' : 'Postal code'} placeholder="H7R 1W6" required />
                </div>
                <QField name="project_address" label={fr ? 'Adresse des travaux' : 'Project address'} placeholder={fr ? 'No civique et rue, ville' : 'Street number and name, city'} />
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="epcm-2col">
                  <QField name="project_type" label={fr ? 'Type de projet' : 'Project type'} type="select" options={projects} />
                  <QField name="timeline" label={fr ? 'Échéancier' : 'Timeline'} type="select" options={timing} />
                </div>
                <QField name="project_details" label={fr ? 'Détails du projet' : 'Project details'} type="textarea" rows={3} placeholder={fr ? 'Type de maison, système actuel, superficie, contraintes…' : 'Home type, current system, square footage, constraints…'} />
                <QB variant="primary" size="lg" uppercase full iconRight="arrow-right" as="button" type="submit" disabled={sending}>{sending ? (fr ? 'Envoi en cours…' : 'Sending…') : (fr ? 'Obtenir ma soumission' : 'Get my quote')}</QB>
                <p style={{ textAlign: 'center', fontSize: '0.82rem', color: 'var(--text-muted)' }}>{fr ? 'Gratuit · Sans engagement · Réponse en 24 h ouvrables' : 'Free · No obligation · Answer within one business day'}</p>
              </form>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

window.QuoteModal = QuoteModal;
