function Contact() {
  const [submitted, setSubmitted] = React.useState(false);
  const [form, setForm] = React.useState({
    name: '', company: '', email: '', phone: '',
    category: PRODUCT_CATEGORIES[0].label,
    quantity: '',
    message: '',
  });

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

  const submit = async (e) => {
    e.preventDefault();
    
    // Validate required fields
    if (!form.name || !form.email) {
      alert('Please fill out your name and email.');
      return;
    }

    try {
      const res = await fetch('contact.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      });
      
      const data = await res.json();
      
      if (res.ok && data.success) {
        setSubmitted(true);
      } else {
        alert(data.message || 'Failed to send enquiry. Please try again.');
      }
    } catch (err) {
      console.error('Error submitting form:', err);
      alert('Error connecting to server. Please try again later.');
    }
  };

  return (
    <Section id="contact" background="var(--navy-deep)" color="var(--paper)" style={{ padding: '140px 0' }}>
      <GridOverlay color="rgba(255,255,255,0.03)" size={80} />

      <div style={{ position: 'relative', zIndex: 1 }}>
        {/* Header */}
        <div style={{ marginBottom: 72, maxWidth: 900 }}>
          <Kicker color="var(--amber)">§ 07 · Get in touch</Kicker>
          <Display size={88} color="var(--paper)" style={{ marginTop: 24 }}>
            Let's talk components.
          </Display>
          <p style={{ fontSize: 19, lineHeight: 1.5, color: 'var(--steel)', marginTop: 24, maxWidth: 640, textWrap: 'pretty' }}>
            Request a quote, ask for a spec sheet, or send us a drawing. We supply domestically and internationally — our team typically responds within one business day.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 60 }} className="sse-contact-grid">
          {/* Left: Form */}
          <div>
            {submitted ? (
              <SuccessCard onReset={() => { setSubmitted(false); setForm({ name: '', company: '', email: '', phone: '', category: PRODUCT_CATEGORIES[0].label, quantity: '', message: '' }); }} />
            ) : (
              <form onSubmit={submit} style={{
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: 12,
                padding: 36,
              }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.2em', color: 'var(--amber)', textTransform: 'uppercase', marginBottom: 20 }}>
                  Request for Quotation
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="sse-form-grid">
                  <Field label="Full name" value={form.name} onChange={upd('name')} placeholder="Your name" required />
                  <Field label="Company" value={form.company} onChange={upd('company')} placeholder="Company name" />
                  <Field label="Email" type="email" value={form.email} onChange={upd('email')} placeholder="you@company.com" required />
                  <Field label="Phone / WhatsApp" value={form.phone} onChange={upd('phone')} placeholder="+Country Code …" />
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }} className="sse-form-grid">
                  <div>
                    <Label>Product category</Label>
                    <select value={form.category} onChange={upd('category')} style={selectStyle}>
                      {PRODUCT_CATEGORIES.map(c => <option key={c.id} value={c.label} style={{ background: '#0a192f', color: 'var(--paper)' }}>{c.label}</option>)}
                    </select>
                  </div>
                  <Field label="Approx. quantity" value={form.quantity} onChange={upd('quantity')} placeholder="e.g. 500 units" />
                </div>

                <div style={{ marginTop: 16 }}>
                  <Label>Requirement details</Label>
                  <textarea
                    value={form.message}
                    onChange={upd('message')}
                    placeholder="Tell us about SKUs, ratings, sizes, timelines, drawings…"
                    rows={5}
                    style={{ ...inputStyle, resize: 'vertical', fontFamily: 'inherit' }}
                  />
                </div>

                <div style={{ marginTop: 16, padding: '12px 14px', background: 'rgba(212,160,23,0.06)', border: '1px solid rgba(212,160,23,0.2)', borderRadius: 6 }}>
                  <div style={{ fontSize: 12, color: 'var(--steel)', fontFamily: 'var(--font-mono)', letterSpacing: '0.05em', lineHeight: 1.6 }}>
                    For export enquiries, please mention your country and any required certifications (IEC, ATEX, etc.) in the details field.
                  </div>
                </div>
                <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
                  <div style={{ fontSize: 12, color: 'var(--steel)', fontFamily: 'var(--font-mono)', letterSpacing: '0.05em' }}>
                    → Response within 1 business day · We ship globally
                  </div>
                  <Button variant="amber" onClick={submit} style={{ padding: '15px 28px' }}>
                    Send enquiry <Arrow />
                  </Button>
                </div>
              </form>
            )}
          </div>

          {/* Right: Details */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
            <ContactBlock
              label="Registered address"
              value={SSE_INFO.address}
              icon={<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 1 L15 5 V13 L9 17 L3 13 V5 Z" stroke="currentColor" strokeWidth="1.3"/><circle cx="9" cy="8" r="2" stroke="currentColor" strokeWidth="1.3"/></svg>}
            />
            <ContactBlock
              label="Speak with the team"
              value={
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <a href={`tel:${SSE_INFO.phoneRaw}`} style={{ color: 'inherit', textDecoration: 'none' }} onMouseEnter={e => e.currentTarget.style.color = 'var(--amber)'} onMouseLeave={e => e.currentTarget.style.color = 'inherit'}>{SSE_INFO.phone}</a>
                  <a href={`tel:${SSE_INFO.phoneRaw2}`} style={{ color: 'inherit', textDecoration: 'none' }} onMouseEnter={e => e.currentTarget.style.color = 'var(--amber)'} onMouseLeave={e => e.currentTarget.style.color = 'inherit'}>{SSE_INFO.phone2}</a>
                </div>
              }
              icon={<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M4 2 L7 2 L8 6 L6 7 C7 9 9 11 11 12 L12 10 L16 11 L16 14 C16 15 15 16 14 16 C8 16 2 10 2 4 C2 3 3 2 4 2 Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>}
            />
            <ContactBlock
              label="Send us an email"
              value={SSE_INFO.email}
              href={`mailto:${SSE_INFO.email}`}
              icon={<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="4" width="14" height="10" stroke="currentColor" strokeWidth="1.3"/><path d="M2 4 L9 10 L16 4" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>}
            />
            <ContactBlock
              label="Working hours"
              value="Mon – Sat · 9:30 AM – 6:30 PM IST"
              icon={<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" strokeWidth="1.3"/><path d="M9 5 V9 L12 11" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>}
            />

            {/* Embedded Google Map */}
            <div style={{
              marginTop: 12,
              aspectRatio: '4/3',
              border: '1px solid rgba(255,255,255,0.1)',
              borderRadius: 8,
              position: 'relative',
              overflow: 'hidden',
              background: 'var(--navy-deep)', // seamless load
            }}>
              <iframe 
                src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3742.232589959262!2d72.99854947447594!3d20.29063761272223!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3be0cc9d10225a53%3A0x18d8611b770d3547!2sSakshi%20Saurabh%20Enterprises!5e0!3m2!1sen!2sin!4v1783163119136!5m2!1sen!2sin" 
                width="100%" 
                height="100%" 
                style={{ 
                  border: 0, 
                  display: 'block',
                  /* Inverts colors to dark mode and rotates hue to make roads amber and water dark blue to match SSE branding */
                  filter: 'invert(90%) hue-rotate(180deg) contrast(85%) brightness(95%)'
                }} 
                allowFullScreen 
                loading="lazy" 
                referrerPolicy="strict-origin-when-cross-origin"
              />
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 1000px) {
          .sse-contact-grid { grid-template-columns: 1fr !important; }
        }
        @media (max-width: 600px) {
          .sse-form-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </Section>
  );
}

const inputStyle = {
  width: '100%',
  background: 'rgba(255,255,255,0.05)',
  border: '1px solid rgba(255,255,255,0.12)',
  borderRadius: 6,
  padding: '12px 14px',
  color: 'var(--paper)',
  fontSize: 15,
  fontFamily: 'inherit',
  outline: 'none',
  transition: 'border 0.2s',
};
const selectStyle = { ...inputStyle, appearance: 'none', backgroundImage: 'linear-gradient(45deg, transparent 50%, var(--steel) 50%), linear-gradient(-45deg, transparent 50%, var(--steel) 50%)', backgroundPosition: 'calc(100% - 18px) 50%, calc(100% - 12px) 50%', backgroundSize: '6px 6px', backgroundRepeat: 'no-repeat', paddingRight: 32 };

function Label({ children }) {
  return <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', color: 'var(--steel)', textTransform: 'uppercase', marginBottom: 8 }}>{children}</div>;
}

function Field({ label, value, onChange, type = 'text', placeholder, required }) {
  return (
    <div>
      <Label>{label}{required && <span style={{ color: 'var(--amber)' }}> *</span>}</Label>
      <input type={type} value={value} onChange={onChange} placeholder={placeholder} required={required}
        style={inputStyle}
        onFocus={e => e.target.style.borderColor = 'var(--amber)'}
        onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.12)'}
      />
    </div>
  );
}

function ContactBlock({ label, value, href, icon }) {
  const Comp = href ? 'a' : 'div';
  return (
    <Comp href={href} style={{
      display: 'flex', gap: 16, alignItems: 'flex-start',
      padding: '20px 0',
      borderBottom: '1px solid rgba(255,255,255,0.08)',
      color: 'inherit',
      transition: 'transform 0.2s',
    }}
      onMouseEnter={href ? (e) => e.currentTarget.style.transform = 'translateX(4px)' : undefined}
      onMouseLeave={href ? (e) => e.currentTarget.style.transform = 'translateX(0)' : undefined}>
      <div style={{ color: 'var(--amber)', marginTop: 2, flexShrink: 0 }}>{icon}</div>
      <div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', color: 'var(--steel)', textTransform: 'uppercase', marginBottom: 6 }}>{label}</div>
        <div style={{ fontSize: 16, color: 'var(--paper)', lineHeight: 1.4 }}>{value}</div>
      </div>
    </Comp>
  );
}

function SuccessCard({ onReset }) {
  return (
    <div style={{
      background: 'rgba(212,160,23,0.08)',
      border: '1px solid rgba(212,160,23,0.4)',
      borderRadius: 12,
      padding: 48,
      textAlign: 'center',
    }}>
      <Hex size={64} stroke="var(--amber)" strokeWidth={1.5} style={{ margin: '0 auto 24px' }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M5 12 L10 17 L19 7" stroke="var(--amber)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </Hex>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--paper)', marginBottom: 12 }}>
        Enquiry received.
      </div>
      <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--steel)', maxWidth: 420, margin: '0 auto 28px' }}>
        Thank you — our team will get back to you within one business day. For urgent requests, WhatsApp us at {SSE_INFO.phone}.
      </p>
      <Button variant="outlineLight" onClick={onReset}>Send another enquiry</Button>
    </div>
  );
}

Object.assign(window, { Contact });
