
// Contact / Quote Page
const ContactField = ({ id, label, required, children, error }) => (
  <div style={{ marginBottom: '20px' }}>
    <label
      htmlFor={id}
      style={{
        display: 'block', fontFamily: 'Inter, sans-serif',
        fontSize: '13px', fontWeight: '600', color: '#1B2A4A',
        marginBottom: '6px', letterSpacing: '0.01em',
      }}
    >
      {label}{required && <span style={{ color: '#E53E3E', marginLeft: '3px' }}>*</span>}
    </label>
    {children}
    {error && <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#E53E3E', margin: '4px 0 0 0' }}>{error}</p>}
  </div>
);

const ContactPage = () => {
  const [formData, setFormData] = React.useState({
    name: '', email: '', phone: '', zip: '',
    interest: '', size: '', condition: '', delivery: '', message: '',
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [submitMessage, setSubmitMessage] = React.useState('');

  const validate = () => {
    const e = {};
    if (!formData.name.trim()) e.name = 'Name is required';
    if (!formData.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) e.email = 'Valid email is required';
    if (!formData.zip.trim()) e.zip = 'Delivery ZIP code is required';
    return e;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }
    setLoading(true);
    setSubmitMessage('');

    try {
      const response = await fetch('/api/quotes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      const payload = await response.json().catch(() => ({}));

      if (!response.ok || !payload.ok) {
        throw new Error(payload.message || 'Unable to submit your quote request right now.');
      }

      if (payload.warning) {
        setSubmitMessage(payload.warning);
      }

      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error) {
      setSubmitMessage(error.message || 'Unable to submit your quote request right now.');
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = (hasError) => ({
    width: '100%', boxSizing: 'border-box',
    fontFamily: 'Inter, sans-serif', fontSize: '15px',
    padding: '12px 14px', borderRadius: '6px',
    border: `1.5px solid ${hasError ? '#E53E3E' : '#CBD5E0'}`,
    color: '#1B2A4A', background: '#fff', outline: 'none',
    transition: 'border-color 0.2s',
  });

  const selectStyle = (hasError) => ({
    ...inputStyle(hasError),
    appearance: 'none', backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\'%3E%3Cpath d=\'M1 1l5 5 5-5\' stroke=\'%236B7E96\' strokeWidth=\'1.5\' fill=\'none\'/%3E%3C/svg%3E")',
    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center',
    paddingRight: '36px', cursor: 'pointer',
  });

  if (submitted) {
    return (
      <div style={{ minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '140px 32px 80px', background: '#F4F6F8' }}>
        <div style={{ textAlign: 'center', maxWidth: '520px' }}>
          <div style={{ width: '72px', height: '72px', borderRadius: '50%', background: '#4A9FD4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 28px', fontSize: '32px' }}>✓</div>
          <h2 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '40px', fontWeight: '800', color: '#1B2A4A', margin: '0 0 16px 0' }}>
            Quote Request Sent!
          </h2>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '16px', color: '#4A5568', lineHeight: '1.65', marginBottom: '28px' }}>
            Thanks {formData.name.split(' ')[0]}! We've received your quote request and will be in touch shortly. You can also reach us directly at the contact info below.
          </p>
          {submitMessage && (
            <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#D69E2E', lineHeight: '1.6', margin: '0 0 20px 0' }}>
              {submitMessage}
            </p>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', alignItems: 'center' }}>
            <a href="tel:2532719238" style={{ fontFamily: 'Inter, sans-serif', fontSize: '16px', fontWeight: '600', color: '#4A9FD4', textDecoration: 'none' }}>📞 (253) 271-9238</a>
            <a href="mailto:Sales@seasteelstorage.com" style={{ fontFamily: 'Inter, sans-serif', fontSize: '16px', fontWeight: '600', color: '#4A9FD4', textDecoration: 'none' }}>✉ Sales@seasteelstorage.com</a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Hero */}
      <section style={{
        background: 'linear-gradient(160deg, #0F1D33 0%, #1B2A4A 100%)',
        padding: '140px 32px 72px',
      }}>
        <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#4A9FD4', display: 'block', marginBottom: '12px' }}>
            Contact & Quote
          </span>
          <h1 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: 'clamp(36px, 5vw, 64px)', fontWeight: '800', color: '#fff', margin: '0 0 20px 0', lineHeight: '1.05' }}>
            Get Your Free<br /><span style={{ color: '#4A9FD4' }}>Container Quote</span>
          </h1>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '17px', color: 'rgba(255,255,255,0.7)', lineHeight: '1.65', maxWidth: '500px', margin: 0 }}>
            Tell us what you need and we'll get back to you fast with pricing, delivery options, and availability.
          </p>
        </div>
      </section>

      {/* Form + Info */}
      <Section bg="#F4F6F8">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '48px', alignItems: 'start' }} className="contact-grid">

          {/* Form */}
          <Card style={{ padding: '40px' }}>
            <h2 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 8px 0' }}>
              Submit a Quote Request
            </h2>
            <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', margin: '0 0 32px 0' }}>
              Fields marked with * are required.
            </p>
            {submitMessage && (
              <div style={{ background: '#FFF8E1', border: '1px solid #F6E05E', borderRadius: '8px', padding: '12px 14px', margin: '0 0 20px 0', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#856404', lineHeight: '1.5' }}>
                {submitMessage}
              </div>
            )}

            <form onSubmit={handleSubmit} noValidate>
              {/* Row: Name + Phone */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }} className="form-row">
                <ContactField id="name" label="Full Name" required error={errors.name}>
                  <input
                    id="name"
                    type="text" placeholder="Jane Smith"
                    value={formData.name}
                    onChange={e => { setFormData(p => ({ ...p, name: e.target.value })); setErrors(p => ({ ...p, name: '' })); }}
                    style={inputStyle(errors.name)}
                    onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                    onBlur={e => e.target.style.borderColor = errors.name ? '#E53E3E' : '#CBD5E0'}
                  />
                </ContactField>
                <ContactField id="phone" label="Phone">
                  <input
                    id="phone"
                    type="tel" placeholder="(253) 555-0100"
                    value={formData.phone}
                    onChange={e => setFormData(p => ({ ...p, phone: e.target.value }))}
                    style={inputStyle(false)}
                    onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                    onBlur={e => e.target.style.borderColor = '#CBD5E0'}
                  />
                </ContactField>
              </div>

              {/* Row: Email + ZIP */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }} className="form-row">
                <ContactField id="email" label="Email Address" required error={errors.email}>
                  <input
                    id="email"
                    type="email" placeholder="jane@example.com"
                    value={formData.email}
                    onChange={e => { setFormData(p => ({ ...p, email: e.target.value })); setErrors(p => ({ ...p, email: '' })); }}
                    style={inputStyle(errors.email)}
                    onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                    onBlur={e => e.target.style.borderColor = errors.email ? '#E53E3E' : '#CBD5E0'}
                  />
                </ContactField>
                <ContactField id="zip" label="Delivery ZIP Code" required error={errors.zip}>
                  <input
                    id="zip"
                    type="text" placeholder="98101"
                    value={formData.zip}
                    onChange={e => { setFormData(p => ({ ...p, zip: e.target.value })); setErrors(p => ({ ...p, zip: '' })); }}
                    style={inputStyle(errors.zip)}
                    onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                    onBlur={e => e.target.style.borderColor = errors.zip ? '#E53E3E' : '#CBD5E0'}
                  />
                </ContactField>
              </div>

              {/* Row: Interest + Size */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }} className="form-row">
                <ContactField id="interest" label="Interested In">
                  <select id="interest" value={formData.interest} onChange={e => setFormData(p => ({ ...p, interest: e.target.value }))} style={selectStyle(false)}>
                    <option value="">Select one…</option>
                    <option value="sale">Sale</option>
                    <option value="rental">Rental</option>
                    <option value="not-sure">Not Sure</option>
                  </select>
                </ContactField>
                <ContactField id="size" label="Container Size">
                  <select id="size" value={formData.size} onChange={e => setFormData(p => ({ ...p, size: e.target.value }))} style={selectStyle(false)}>
                    <option value="">Select size…</option>
                    <option value="20">20'</option>
                    <option value="40">40'</option>
                    <option value="not-sure">Not Sure</option>
                  </select>
                </ContactField>
              </div>

              {/* Row: Condition + Delivery */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }} className="form-row">
                <ContactField id="condition" label="Condition Preference">
                  <select id="condition" value={formData.condition} onChange={e => setFormData(p => ({ ...p, condition: e.target.value }))} style={selectStyle(false)}>
                    <option value="">Select condition…</option>
                    <option value="new">New</option>
                    <option value="premium-used">Premium Used</option>
                    <option value="cargo-worthy">Cargo Worthy</option>
                    <option value="wwt">Wind & Water Tight</option>
                    <option value="specialty">Specialty</option>
                    <option value="not-sure">Not Sure</option>
                  </select>
                </ContactField>
                <ContactField id="delivery" label="Delivery Needed">
                  <select id="delivery" value={formData.delivery} onChange={e => setFormData(p => ({ ...p, delivery: e.target.value }))} style={selectStyle(false)}>
                    <option value="">Select…</option>
                    <option value="yes">Yes</option>
                    <option value="no">No</option>
                    <option value="not-sure">Not Sure</option>
                  </select>
                </ContactField>
              </div>

              {/* Message */}
              <ContactField id="message" label="Message / Additional Details">
                <textarea
                  id="message"
                  placeholder="Tell us more about your project, timeline, or any special requirements…"
                  value={formData.message}
                  onChange={e => setFormData(p => ({ ...p, message: e.target.value }))}
                  rows={4}
                  style={{ ...inputStyle(false), resize: 'vertical', minHeight: '100px' }}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#CBD5E0'}
                />
              </ContactField>

              <button type="submit" disabled={loading} style={{
                width: '100%', background: loading ? '#9AAAB8' : '#4A9FD4', color: '#fff',
                border: 'none', cursor: loading ? 'not-allowed' : 'pointer',
                fontFamily: 'Inter, sans-serif', fontSize: '16px', fontWeight: '600',
                padding: '16px', borderRadius: '6px',
                transition: 'background 0.2s',
                letterSpacing: '0.01em',
              }}
              onMouseEnter={e => { if (!loading) e.target.style.background = '#3a8fc4'; }}
              onMouseLeave={e => { if (!loading) e.target.style.background = '#4A9FD4'; }}
              >
                {loading ? 'Sending…' : 'Submit Quote Request →'}
              </button>
            </form>
          </Card>

          {/* Contact info sidebar */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
            <Card style={{ padding: '28px' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 20px 0' }}>
                Contact Us Directly
              </h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                <a href="tel:2532719238" style={{
                  display: 'flex', alignItems: 'center', gap: '14px',
                  padding: '16px', borderRadius: '8px',
                  background: '#F4F6F8', border: '1px solid #E8EDF2',
                  textDecoration: 'none',
                }}>
                  <div style={{ width: '40px', height: '40px', borderRadius: '8px', background: '#1B2A4A', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', flexShrink: 0 }}>📞</div>
                  <div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Call Us</div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '16px', fontWeight: '700', color: '#1B2A4A' }}>(253) 271-9238</div>
                  </div>
                </a>
                <a href="mailto:Sales@seasteelstorage.com" style={{
                  display: 'flex', alignItems: 'center', gap: '14px',
                  padding: '16px', borderRadius: '8px',
                  background: '#F4F6F8', border: '1px solid #E8EDF2',
                  textDecoration: 'none',
                }}>
                  <div style={{ width: '40px', height: '40px', borderRadius: '8px', background: '#1B2A4A', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', flexShrink: 0 }}>✉</div>
                  <div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Email Us</div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A', wordBreak: 'break-all' }}>Sales@seasteelstorage.com</div>
                  </div>
                </a>
                <a href="https://www.facebook.com/share/18JwPrXa16/?mibextid=wwXIfr" target="_blank" rel="noreferrer" style={{
                  display: 'flex', alignItems: 'center', gap: '14px',
                  padding: '16px', borderRadius: '8px',
                  background: '#F4F6F8', border: '1px solid #E8EDF2',
                  textDecoration: 'none',
                }}>
                  <div style={{ width: '40px', height: '40px', borderRadius: '8px', background: '#1877F2', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', flexShrink: 0, color: '#fff', fontFamily: '"Barlow Condensed", sans-serif', fontWeight: '800' }}>f</div>
                  <div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Follow Us</div>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A' }}>Sea Steel Storage on Facebook</div>
                  </div>
                </a>
              </div>
            </Card>

            <Card style={{ padding: '28px' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 14px 0' }}>
                Service Area
              </h3>
              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '14px' }}>
                {['Washington', 'Oregon', 'Idaho', 'National Wholesale'].map(s => (
                  <span key={s} style={{
                    background: 'rgba(74,159,212,0.1)', border: '1px solid rgba(74,159,212,0.25)',
                    color: '#2E6FA3', padding: '5px 12px', borderRadius: '100px',
                    fontSize: '12px', fontWeight: '600', fontFamily: 'Inter, sans-serif',
                  }}>{s}</span>
                ))}
              </div>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', lineHeight: '1.6', margin: 0 }}>
                We deliver across WA, OR, and ID. National wholesale also available. Ask about your area when requesting a quote.
              </p>
            </Card>

            <Card style={{ padding: '28px', background: '#1B2A4A' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#fff', margin: '0 0 10px 0' }}>
                Response Time
              </h3>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: 'rgba(255,255,255,0.65)', lineHeight: '1.6', margin: '0 0 16px 0' }}>
                We typically respond to quote requests within one business day.
              </p>
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#4ade80' }}></div>
                <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.5)' }}>Washington-owned and operated</span>
              </div>
            </Card>
          </div>
        </div>
        <style>{`@media (max-width: 768px) { .contact-grid { grid-template-columns: 1fr !important; } .form-row { grid-template-columns: 1fr !important; } }`}</style>
      </Section>
    </div>
  );
};

Object.assign(window, { ContactPage });
