const { useState } = React;

function QuoteForm() {
  const [form, setForm] = useState({ email: '', phone: '', company: '', message: '' });
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');
  const [honeypot, setHoneypot] = useState('');

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError('');

    if (!form.email.trim() || !form.message.trim()) {
      setError('Please fill email and message.');
      return;
    }

    setSending(true);
    try {
      const response = await fetch('/api/quote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, website: honeypot }),
      });

      const data = await response.json();
      if (!response.ok || !data.ok) {
        throw new Error(data.error || 'Request failed');
      }

      setSubmitted(true);
      setForm({ email: '', phone: '', company: '', message: '' });
      setHoneypot('');
      setTimeout(() => setSubmitted(false), 4000);
    } catch (err) {
      setError('Send failed. Please email info@terramine.ng');
    } finally {
      setSending(false);
    }
  };

  const cardStyle = {
    background: 'var(--bg-elevated)', border: '1px solid rgba(255,255,255,0.06)',
    borderRadius: 8, padding: 32,
  };

  return (
    <section id="quote" className="section-pad" style={{ background: 'var(--bg)' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 24, alignItems: 'stretch' }} className="quote-grid">

          {/* Left: form card */}
          <div className="quote-card" style={cardStyle}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>// REQUEST QUOTE</div>



            <form onSubmit={handleSubmit}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {/* Honeypot field to block basic bot spam */}
                <input
                  type="text"
                  autoComplete="off"
                  tabIndex="-1"
                  value={honeypot}
                  onChange={(e) => setHoneypot(e.target.value)}
                  style={{ position: 'absolute', left: '-9999px', opacity: 0, pointerEvents: 'none' }}
                  aria-hidden="true"
                />

                <div>
                  <label style={labelStyle}>Email</label>
                  <input className="input" type="email" placeholder="your@company.com"
                    value={form.email} onChange={set('email')} required />
                </div>

                <div>
                  <label style={labelStyle}>Phone</label>
                  <input className="input input-mono" type="tel" placeholder="+1 234 567 8900"
                    value={form.phone} onChange={set('phone')} />
                </div>

                <div>
                  <label style={labelStyle}>Company Name</label>
                  <input className="input" placeholder="Your company"
                    value={form.company} onChange={set('company')} />
                </div>

                <div>
                  <label style={labelStyle}>Message</label>
                  <textarea className="input" placeholder="How can we help you?"
                    value={form.message} onChange={set('message')}
                    style={{ height: 96, resize: 'none', lineHeight: 1.5 }} required />
                </div>
              </div>

              <button type="submit" className="btn btn-primary"
                disabled={sending}
                style={{ justifyContent: 'center', fontSize: 13, padding: '8px 20px', borderRadius: 999, marginTop: 20, display: 'flex', margin: '20px auto 0', opacity: sending ? 0.8 : 1 }}>
                {sending ? 'Sending…' : submitted ? '✓ Sent' : 'Get Quote →'}
              </button>
              {error && (
                <div style={{ marginTop: 12, textAlign: 'center', fontSize: 12, color: '#fca5a5' }}>
                  {error}
                </div>
              )}
            </form>
          </div>

          {/* Right: status sidebar */}
          <div className="quote-card" style={{ ...cardStyle, padding: 24, display: 'flex', flexDirection: 'column', gap: 0, height: '100%' }}>
            {/* Why TerraMine */}
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', color: 'var(--text-tertiary)', marginBottom: 14 }}>
              WHY TERRAMINE INDUSTRIAL
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                'OEM & aftermarket spare parts',
                '10,000+ SKUs available',
                'Trusted global partners',
                'Urgent 48h shipping available',
                'Mining equipment expertise',
                'International supplier network',
                'Efficient logistics support',
                'Hard-to-source parts expertise',
                'Custom sourcing solutions',
                'Worldwide delivery',
              ].map((item, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 14, color: 'var(--text-secondary)' }}>
                  <span style={{ color: 'var(--accent)', fontWeight: 600, flexShrink: 0, marginTop: 1 }}>—</span>
                  {item}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .form-grid { }
        @media (max-width: 600px) { .form-grid { grid-template-columns: 1fr !important; } .form-col { } }
        @media (max-width: 900px) { .quote-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

const labelStyle = { display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--text-tertiary)', marginBottom: 6, letterSpacing: '0.03em' };

Object.assign(window, { QuoteForm });
