// QuotePanel.jsx — slide-in quote form (opened by every "Get a Quote" CTA)
// Accepts an optional `prefill` ({ eventType, guests, note }) so the cost
// calculator can carry the planner's inputs straight in (Design Brief §5).
const QP_EVENT_TYPES = ['Corporate', 'Wedding', 'Campus or school', 'Private party', 'Large event', 'Other'];

// Live inquiry worker — same endpoint the WordPress inquiry form posts to.
// POST writes a Lead to Airtable (Events table) and fires the welcome email.
const QP_WORKER_URL = 'https://delicate-unit-46e9.odd-morning-25e5.workers.dev/';

// Map the granular site event types onto the worker's Airtable single-select.
// The precise selection is also appended to Additional Info so nothing is lost.
const QP_EVENT_TYPE_MAP = {
  'Corporate': 'Corporate',
  'Wedding': 'Wedding',
  'Campus or school': 'Other',
  'Private party': 'Private Party',
  'Large event': 'Festival',
  'Other': 'Other',
};

const QuotePanel = ({ open, onClose, prefill }) => {
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const formRef = React.useRef(null);
  React.useEffect(() => { if (!open) { setSubmitted(false); setSubmitting(false); setError(''); } }, [open]);
  const hasPrefill = !!(prefill && (prefill.eventType || prefill.guests || prefill.note));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setError('');
    const fd = new FormData(formRef.current);
    const name = (fd.get('name') || '').trim();
    const email = (fd.get('email') || '').trim();
    const town = (fd.get('town') || '').trim();
    const selectedType = (fd.get('eventType') || 'Corporate').trim();
    const guests = (fd.get('guests') || '').trim();
    const note = (fd.get('note') || '').trim();
    const eventDate = (fd.get('eventDate') || '').trim();

    if (!name || !email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError('Please enter your name and a valid email.');
      return;
    }

    // Carry calculator/page context so the coordinator sees how the
    // visitor sized the event before the quote was requested.
    const context = [];
    if (prefill && prefill.source) context.push('Source page: ' + prefill.source);
    context.push('Event type (site): ' + selectedType);
    if (prefill && prefill.truckMix) context.push('Truck mix: ' + prefill.truckMix);

    const payload = {
      'Contact Name': name,
      'Customer Email': email,
      'Event Type': QP_EVENT_TYPE_MAP[selectedType] || 'Other',
      'Source': 'Website',
      'State': 'NJ',
    };
    if (town) payload['City'] = town;
    if (eventDate) payload['Event Date'] = eventDate;
    if (guests) payload['Guest Count'] = guests;
    if (note) payload['Event Description'] = note;
    payload['Additional Info'] = context.join('\n');

    setSubmitting(true);
    try {
      const resp = await fetch(QP_WORKER_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      let result = null;
      try { result = await resp.json(); } catch (_) {}
      if (!resp.ok || !result || result.ok !== true) {
        const msg = (result && result.error) ? result.error : ('http_' + resp.status);
        setError('Something went wrong (' + msg + '). Please call us at (201) 208-2682.');
        setSubmitting(false);
        return;
      }
      setSubmitted(true);
      setSubmitting(false);
    } catch (err) {
      setError('Network error. Please try again or call (201) 208-2682.');
      setSubmitting(false);
    }
  };

  return (
    <>
      <div onClick={onClose} style={{
        position:'fixed', inset:0, background:'rgba(17,24,39,.4)', zIndex:90,
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .18s ease-out',
      }}/>
      <aside style={{
        position:'fixed', top:0, right:0, height:'100%', width:'min(460px, 100%)',
        background: T.white, zIndex:100,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        transition:'transform .24s cubic-bezier(0.22, 1, 0.36, 1)',
        boxShadow: T.shadowModal,
        display:'flex', flexDirection:'column',
      }}>
        <header style={{ padding:'20px 24px', borderBottom:`1px solid ${T.border}`,
                         display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom:4 }}>Quote request</div>
            <div style={{ fontSize:20, fontWeight:600, color: T.ink }}>Tell us about your event</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            border:`1px solid ${T.border}`, background: T.white, borderRadius:999,
            width:36, height:36, display:'inline-flex', alignItems:'center', justifyContent:'center',
            cursor:'pointer', color: T.ink,
          }}><IconClose size={18} /></button>
        </header>

        {!submitted ? (
          <form key={open ? 'open' : 'closed'} ref={formRef} onSubmit={handleSubmit}
                style={{ padding:'24px', overflowY:'auto', display:'flex', flexDirection:'column', gap:16, flex:1 }}>
            {hasPrefill && (
              <div style={{ background: T.skyTint, border:`1px solid ${T.border}`, borderRadius:8,
                            padding:'12px 14px', fontSize:13, color: T.ink, lineHeight:1.5,
                            display:'flex', gap:10, alignItems:'flex-start' }}>
                <span style={{ color: T.teal, flex:'0 0 auto', marginTop:1 }}><IconCheck size={16} /></span>
                <span>Pulled in from the calculator — adjust anything below.</span>
              </div>
            )}
            <Field label="Name"        name="name"   type="text"   placeholder="Carmela Rosario" required />
            <Field label="Email"       name="email"  type="email"  placeholder="you@company.com" required />
            <SelectField label="Event type" name="eventType" defaultValue={(prefill && prefill.eventType) || 'Corporate'}
                         options={QP_EVENT_TYPES} />
            <Field label="Event date"  name="eventDate" type="date"   icon={<IconCal size={16} />} />
            <Field label="Town"        name="town"   type="text"   placeholder="Jersey City"     icon={<IconPin size={16} />} />
            <Field label="Guest count" name="guests" type="number" placeholder="120"             icon={<IconUsers size={16} />}
                   defaultValue={(prefill && prefill.guests) || ''} />
            <TextareaField label="Anything else?" name="note" rows={hasPrefill ? 3 : 2}
                           defaultValue={(prefill && prefill.note) || ''}
                           placeholder="Menu ideas, venue, dietary needs…" />
            {error && (
              <div role="alert" style={{ background: T.redTint, border:`1px solid ${T.red}`, borderRadius:8,
                            padding:'10px 12px', fontSize:13, color: T.red, lineHeight:1.5 }}>
                {error}
              </div>
            )}
            <p style={{ fontSize:13, color: T.inkSoft, lineHeight:1.5, margin:'8px 0 0' }}>
              We'll send a real quote within 4 business hours.
            </p>
            <button type="submit" disabled={submitting} className="btn btn-primary"
                    style={{ justifyContent:'center', marginTop:'auto', opacity: submitting ? .6 : 1 }}>
              {submitting ? 'Sending…' : 'Send request'}
            </button>
          </form>
        ) : (
          <div style={{ padding:'32px 24px', display:'flex', flexDirection:'column', gap:16, alignItems:'flex-start' }}>
            <div style={{ width:48, height:48, borderRadius:999, background: T.redTint, display:'flex',
                          alignItems:'center', justifyContent:'center', color: T.red, fontSize:24 }}>✓</div>
            <h3 style={{ margin:0, color: T.ink }}>Got it — we'll send a real quote within 4 business hours.</h3>
            <p style={{ margin:0, color: T.inkSoft, fontSize:15, lineHeight:1.55 }}>
              Carmela or one of the coordinators will email you back. If your event is in the next 7 days, give us a call at <a href="tel:+12012082682" style={{ color: T.teal, fontWeight:600 }}>(201) 208-2682</a>.
            </p>
            <button onClick={onClose} className="btn btn-secondary" style={{ marginTop:8 }}>Close</button>
          </div>
        )}
      </aside>
    </>
  );
};

const Field = ({ label, icon, ...input }) => (
  <label style={{ display:'block' }}>
    <div style={{ fontSize:13, fontWeight:600, color: T.ink, marginBottom:6 }}>{label}</div>
    <div style={{ position:'relative' }}>
      {icon && <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color: T.inkSoft }}>{icon}</span>}
      <input className="input" {...input} style={{ paddingLeft: icon ? 36 : 14 }} />
    </div>
  </label>
);

const SelectField = ({ label, options, ...rest }) => (
  <label style={{ display:'block' }}>
    <div style={{ fontSize:13, fontWeight:600, color: T.ink, marginBottom:6 }}>{label}</div>
    <div style={{ position:'relative' }}>
      <select className="input" {...rest} style={{ appearance:'none', WebkitAppearance:'none', paddingRight:36, cursor:'pointer' }}>
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
      <span style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color: T.inkSoft, pointerEvents:'none' }}><IconChevDown size={16} /></span>
    </div>
  </label>
);

const TextareaField = ({ label, ...rest }) => (
  <label style={{ display:'block' }}>
    <div style={{ fontSize:13, fontWeight:600, color: T.ink, marginBottom:6 }}>{label}</div>
    <textarea className="input" {...rest} style={{ resize:'vertical', minHeight:64, lineHeight:1.5 }} />
  </label>
);

Object.assign(window, { QuotePanel });
