/* global React */
const { useState } = React;

/* ──────────────────────────────────────────────────────────────────────────
   QUOTE DELIVERY
   Quote submissions are emailed to info@vailuxuryglassandmirror.com.

   Setup (one time, free): go to https://web3forms.com, enter
   info@vailuxuryglassandmirror.com, and they'll email you an Access Key.
   Paste that key below between the quotes. That's it — every submission
   then arrives in that inbox.

   Until a key is set, the form opens the visitor's email app with the
   details pre-filled and addressed to you (fallback, no setup needed).
   ────────────────────────────────────────────────────────────────────────── */
const WEB3FORMS_ACCESS_KEY = ''; // ← paste your Web3Forms access key here
const QUOTE_RECIPIENT = 'info@vailuxuryglassandmirror.com';

function QuoteView({ onNavigate }) {
  const { Eyebrow, Field, Select, Checkbox, Button, ValueItem, LitEdge } = window.VailuxuryGlassDesignSystem_8a37c5;
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');

  const scrollTop = () => {
    const s = document.getElementById('vlx-scroll');
    if (s) s.scrollTo({ top: 0, behavior: 'smooth' });
  };

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    const form = e.target;
    const data = new FormData(form);
    data.append('subject', 'New Quote Request — Vailuxury Glass & Mirror');
    data.append('from_name', 'Vailuxury Website');

    // Primary path: deliver server-side via Web3Forms.
    if (WEB3FORMS_ACCESS_KEY) {
      setSending(true);
      data.append('access_key', WEB3FORMS_ACCESS_KEY);
      try {
        const res = await fetch('https://api.web3forms.com/submit', { method: 'POST', body: data });
        const json = await res.json();
        if (json.success) {
          setSubmitted(true);
          scrollTop();
        } else {
          setError('Something went wrong sending your request. Please call us or try again.');
        }
      } catch (err) {
        setError('Network error — please check your connection and try again.');
      } finally {
        setSending(false);
      }
      return;
    }

    // Fallback (no key set yet): open the visitor's email app, pre-addressed.
    const lines = [];
    const labels = {
      full_name: 'Name', phone: 'Phone', email: 'Email', service: 'Service',
      property: 'Property Type', city: 'City', timeline: 'Timeline', message: 'Details',
    };
    for (const [k, v] of data.entries()) {
      if (k === 'subject' || k === 'from_name' || k === 'consent') continue;
      if (v) lines.push(`${labels[k] || k}: ${v}`);
    }
    const body = encodeURIComponent('New quote request:\n\n' + lines.join('\n'));
    const subject = encodeURIComponent('New Quote Request — Vailuxury Glass & Mirror');
    window.location.href = `mailto:${QUOTE_RECIPIENT}?subject=${subject}&body=${body}`;
    setSubmitted(true);
    scrollTop();
  }

  const points = [
    { label: '100% Free', title: 'No fees, no obligations', body: 'Just a clear, honest estimate.' },
    { label: 'Fast Response', title: 'We get back to you quickly', body: 'We review your request and reply promptly.' },
    { label: 'Tailored to You', title: 'Customized to your space', body: 'Every quote fits your style and budget.' },
    { label: 'Quality Guaranteed', title: 'The same precision, every job', body: 'Premium materials, big project or small.' },
  ];

  return (
    <div>
      {/* hero */}
      <section style={{ background: 'var(--ink)', padding: 'calc(var(--section-y) * 0.8) 0 var(--section-y)' }}>
        <div style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--gutter)' }}>
          <Eyebrow tone="dark">Free Quote</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '-0.02em', fontSize: 'var(--fs-display-l)', color: 'var(--text-inv)', margin: '16px 0 0', lineHeight: 1.02, maxWidth: '18ch' }}>
            Get Your Free, No-Obligation Quote
          </h1>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body-l)', lineHeight: 1.6, color: 'var(--text-inv)', opacity: 0.9, margin: '20px 0 0', maxWidth: '56ch' }}>
            Beautiful glasswork starts with a conversation. Tell us about your project and receive a personalized estimate — completely free, with zero pressure.
          </p>
        </div>
      </section>

      {/* why request + form */}
      <section style={{ background: 'var(--glass)', padding: 'var(--section-y) 0' }}>
        <div style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--gutter)', display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: '64px' }} className="vlx-quote-grid">
          {/* left: reassurance */}
          <div>
            <Eyebrow>Transparent Pricing · Zero Commitment</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '-0.02em', fontSize: 'var(--fs-h2)', color: 'var(--ink)', margin: '14px 0 28px', lineHeight: 1.1 }}>
              Honesty from the very first step
            </h2>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px 32px' }}>
              {points.map((p) => (
                <ValueItem key={p.label} label={p.label} title={p.title} tone="light">{p.body}</ValueItem>
              ))}
            </div>
          </div>

          {/* right: the form */}
          <div>
            {submitted ? (
              <div style={{ padding: '40px 0' }}>
                <div className="lit-edge" />
                <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '1.6rem', letterSpacing: '-0.02em', color: 'var(--ink)', margin: '32px 0 12px' }}>
                  Thank you!
                </h3>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body-l)', lineHeight: 1.6, color: 'var(--text-dim)', margin: '0 0 28px', maxWidth: '40ch' }}>
                  We've received your request and will be in touch shortly.
                </p>
                <Button variant="ghost" onClick={() => setSubmitted(false)}>Submit Another Request</Button>
              </div>
            ) : (
              <form onSubmit={handleSubmit}
                style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '26px 28px' }}>
                <Field label="Full Name" name="full_name" placeholder="Your name" required />
                <Field label="Phone Number" name="phone" type="tel" placeholder="Best number to reach you" required />
                <Field label="Email Address" name="email" type="email" placeholder="Where we'll send your quote" required style={{ gridColumn: '1 / -1' }} />
                <Select label="Service Needed" name="service" required options={['Shower Doors','Custom Mirrors','Glass Walls & Partitions','Glass Table Tops','Window Glass Repair','Other']} />
                <Select label="Property Type" name="property" placeholder="Select…" options={['Residential','Commercial']} />
                <Field label="Project Location (City)" name="city" placeholder="City in Colorado" />
                <Select label="Preferred Timeline" name="timeline" placeholder="Select…" options={['ASAP','1–2 Weeks','1 Month','Just Exploring']} />
                <Field label="Message / Project Details" name="message" multiline rows={3} placeholder="Tell us more about what you have in mind" style={{ gridColumn: '1 / -1' }} />
                <div style={{ gridColumn: '1 / -1' }}>
                  <Checkbox label="I agree to be contacted about my request." name="consent" required />
                </div>
                {error && (
                  <p style={{ gridColumn: '1 / -1', margin: 0, fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', color: 'var(--teal)' }}>
                    {error}
                  </p>
                )}
                <div style={{ gridColumn: '1 / -1', marginTop: '6px' }}>
                  <Button variant="primary" size="lg" type="submit" withArrow disabled={sending}>
                    {sending ? 'Sending…' : 'Submit My Free Quote Request'}
                  </Button>
                </div>
              </form>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}
window.QuoteView = QuoteView;
