function EstimateModal({ onClose }) {
  const [status, setStatus] = React.useState('idle');
  const [files, setFiles] = React.useState([]);
  const [waUrl, setWaUrl] = React.useState('');

  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [onClose]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const sb = window.getSB();
      const form = e.target;
      const name = form.name.value.trim();
      const phone = form.phone.value.trim();
      const email = form.email.value.trim();
      const message = form.description.value.trim();
      const photoUrls = [];

      // Upload all files to Supabase storage
      for (const file of files) {
        const ext = file.name.split('.').pop();
        const path = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
        const { error: uploadError } = await sb.storage
          .from('estimate-photos')
          .upload(path, file, { contentType: file.type, upsert: false });
        if (!uploadError) {
          const { data: urlData } = sb.storage
            .from('estimate-photos')
            .getPublicUrl(path);
          photoUrls.push(urlData.publicUrl);
        }
      }

      // Insert lead
      const { error } = await sb.from('leads').insert([{
        name,
        phone,
        email: email || null,
        message,
        photo_url: photoUrls[0] || null,
        source: 'website-estimate-form'
      }]);

      if (error) throw error;
      const photoLine = photoUrls.length > 0 ? `\nFiles:\n${photoUrls.join('\n')}` : '';
      const msg = encodeURIComponent(`Hi Jaspal! New service request:\nName: ${name}\nPhone: ${phone}${email ? '\nEmail: ' + email : ''}\nIssue: ${message}${photoLine}`);
      setWaUrl(`https://wa.me/17786284900?text=${msg}`);
      setStatus('success');
    } catch (err) {
      console.error('Estimate submission error:', err);
      setStatus('error');
    }
  };

  return (
    <div onClick={(e) => { if (e.target === e.currentTarget) onClose(); }} style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '16px', overflowY: 'auto'
    }}>
      <div style={{
        background: '#111315', border: '1px solid rgba(196,154,108,0.25)',
        borderRadius: '12px', width: '100%', maxWidth: '520px',
        padding: '40px 36px', position: 'relative',
        boxShadow: '0 24px 80px rgba(0,0,0,0.6)',
        margin: 'auto'
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: '3px',
          borderRadius: '12px 12px 0 0',
          background: 'linear-gradient(90deg, #8B6535, #C49A6C, #8B6535)'
        }} />

        <button onClick={onClose} style={{
          position: 'absolute', top: '16px', right: '16px',
          background: 'none', border: 'none', cursor: 'pointer',
          color: '#9CA3AF', fontSize: '20px', lineHeight: 1, padding: '4px'
        }}>✕</button>

        {status === 'success' ? (
          <div style={{ textAlign: 'center', padding: '24px 0' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px', color: '#C49A6C' }}>✓</div>
            <h2 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: '28px', color: '#fff', marginBottom: '12px' }}>
              We've got your project!
            </h2>
            <p style={{ color: '#9CA3AF', lineHeight: 1.7 }}>
              Thanks! We'll review your project and get back to you within 4 hours.
            </p>
            <a href={waUrl} className="btn btn-primary" style={{ marginTop: '28px', justifyContent: 'center', textDecoration: 'none' }}>
              Open WhatsApp to Send →
            </a>
          </div>
        ) : (
          <>
            <h2 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: '32px', fontWeight: 700, color: '#fff', marginBottom: '6px' }}>
              Get Your Estimate
            </h2>
            <p style={{ color: '#9CA3AF', fontSize: '14px', lineHeight: 1.65, marginBottom: '28px' }}>
              Upload a photo of your project and describe what you need. We respond within 4 hours.
            </p>

            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9CA3AF', marginBottom: '8px' }}>
                  Photos / Videos (optional, up to 4)
                </label>
                <label style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  gap: '10px', padding: '20px', borderRadius: '8px', cursor: 'pointer',
                  border: '1px dashed rgba(196,154,108,0.4)',
                  background: 'rgba(196,154,108,0.04)', color: '#C49A6C',
                  fontSize: '14px'
                }}>
                  <span style={{ fontSize: '20px' }}>📷</span>
                  <span>{files.length > 0 ? `${files.length} file(s) selected` : 'Tap to add photos or videos (up to 4)'}</span>
                  <input
                    type="file" accept="image/*,video/*" multiple
                    style={{ display: 'none' }}
                    onChange={(e) => {
                      const selected = Array.from(e.target.files).slice(0, 4);
                      setFiles(selected);
                    }}
                  />
                </label>
              </div>

              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9CA3AF', marginBottom: '8px' }}>
                  Project Description *
                </label>
                <textarea name="description" required rows={4}
                  placeholder="Describe your project — what needs to be done, where, and any details that help us give you an accurate estimate."
                  style={{
                    width: '100%', background: 'rgba(255,255,255,0.04)',
                    border: '1px solid rgba(255,255,255,0.1)',
                    borderRadius: '8px', padding: '12px 14px', color: '#fff',
                    fontSize: '14px', lineHeight: 1.6, resize: 'vertical',
                    fontFamily: 'Outfit, sans-serif', outline: 'none', boxSizing: 'border-box'
                  }} />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9CA3AF', marginBottom: '8px' }}>
                    Your Name *
                  </label>
                  <input type="text" name="name" required placeholder="John Smith" style={{
                    width: '100%', background: 'rgba(255,255,255,0.04)',
                    border: '1px solid rgba(255,255,255,0.1)',
                    borderRadius: '8px', padding: '12px 14px', color: '#fff',
                    fontSize: '14px', fontFamily: 'Outfit, sans-serif',
                    outline: 'none', boxSizing: 'border-box'
                  }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9CA3AF', marginBottom: '8px' }}>
                    Phone Number *
                  </label>
                  <input type="tel" name="phone" required
                    placeholder="6045550199"
                    pattern="[0-9]{10}" maxLength={10}
                    title="Please enter a 10-digit phone number"
                    onChange={(e) => { e.target.value = e.target.value.replace(/\D/g, ''); }}
                    style={{
                      width: '100%', background: 'rgba(255,255,255,0.04)',
                      border: '1px solid rgba(255,255,255,0.1)',
                      borderRadius: '8px', padding: '12px 14px', color: '#fff',
                      fontSize: '14px', fontFamily: 'Outfit, sans-serif',
                      outline: 'none', boxSizing: 'border-box'
                    }} />
                </div>
              </div>

              <div style={{ marginBottom: '24px' }}>
                <label style={{ display: 'block', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#9CA3AF', marginBottom: '8px' }}>
                  Email Address (optional)
                </label>
                <input type="email" name="email" placeholder="you@example.com" style={{
                  width: '100%', background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.1)',
                  borderRadius: '8px', padding: '12px 14px', color: '#fff',
                  fontSize: '14px', fontFamily: 'Outfit, sans-serif',
                  outline: 'none', boxSizing: 'border-box'
                }} />
              </div>

              {status === 'error' && (
                <p style={{ color: '#f87171', fontSize: '13px', marginBottom: '16px' }}>
                  Something went wrong. Please call us at {window.CONTACT.phone}
                </p>
              )}

              <button type="submit" className="btn btn-primary"
                disabled={status === 'sending'}
                style={{ width: '100%', justifyContent: 'center' }}>
                {status === 'sending' ? 'Sending...' : 'Send My Project →'}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}
window.EstimateModal = EstimateModal;
