// Estimate request form — multi-step with validation
const { useState } = React;

const PROJECT_TYPES = ['New Deck', 'Replace Existing', 'Pavilion / Roof', 'Stairs / Railings', 'Restoration'];
const SIZE_RANGES = ['< 200 sq ft', '200–400 sq ft', '400–600 sq ft', '600+ sq ft', 'Not sure yet'];
const TIMELINES = ['ASAP', 'Spring 2026', 'Summer 2026', 'Fall 2026', 'Just exploring'];
const MATERIALS = ['Cedar', 'Composite', 'Ipe / Hardwood', 'Pressure-treated', 'Open to advice'];

function EstimateForm() {
  const [step, setStep] = useState(1);
  const [done, setDone] = useState(false);
  const [data, setData] = useState({
    projectType: '',
    size: '',
    timeline: '',
    materials: [],
    name: '',
    email: '',
    phone: '',
    zip: '',
    notes: ''
  });
  const [errors, setErrors] = useState({});

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleMaterial = (m) => setData(d => ({
    ...d,
    materials: d.materials.includes(m) ? d.materials.filter(x => x !== m) : [...d.materials, m]
  }));

  const validateStep = () => {
    const e = {};
    if (step === 1) {
      if (!data.projectType) e.projectType = 'Select a project type';
      if (!data.size) e.size = 'Pick a size range';
      if (!data.timeline) e.timeline = 'Pick a timeline';
    }
    if (step === 2) {
      if (data.materials.length === 0) e.materials = 'Pick at least one (or "Open to advice")';
    }
    if (step === 3) {
      if (!data.name.trim()) e.name = 'Required';
      if (!data.email.trim()) e.email = 'Required';
      else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = 'Enter a valid email';
      if (!data.phone.trim()) e.phone = 'Required';
      if (!data.zip.trim()) e.zip = 'Required';
      else if (!/^\d{5}$/.test(data.zip.trim())) e.zip = '5-digit ZIP';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validateStep()) setStep(s => s + 1); };
  const back = () => { setErrors({}); setStep(s => Math.max(1, s - 1)); };

  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [refNum, setRefNum] = useState('');

  const submit = async () => {
    if (!validateStep()) return;
    setSubmitting(true);
    setSubmitError('');
    const ref = 'BB-' + Math.floor(Math.random() * 90000 + 10000);
    try {
      const res = await fetch('/api/estimate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...data, reference: ref, submittedAt: new Date().toISOString() })
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || 'Could not send your request. Please call 763-568-8358 or email build@bigbeamdecks.com directly.');
      }
      setRefNum(ref);
      setDone(true);
    } catch (e) {
      setSubmitError(e.message || 'Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  if (done) {
    return (
      <div className="form-success">
        <div className="check">✓</div>
        <h3>Request received.</h3>
        <p>Thanks, {data.name.split(' ')[0]}. We'll be in touch within one business day to schedule your site visit.</p>
        <div style={{
          marginTop: 24, paddingTop: 24, borderTop: '1px solid var(--ink-4)',
          fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em',
          textTransform: 'uppercase', color: 'var(--fog-2)'
        }}>
          Reference: {refNum} · {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="form-progress">
        <div className={`form-progress-step ${step > 1 ? 'done' : step === 1 ? 'active' : ''}`}></div>
        <div className={`form-progress-step ${step > 2 ? 'done' : step === 2 ? 'active' : ''}`}></div>
        <div className={`form-progress-step ${step === 3 ? 'active' : ''}`}></div>
      </div>

      <div className="form-step-label">Step 0{step} / 03</div>
      <h3 className="form-step-title">
        {step === 1 && <>The <em style={{fontStyle:'italic', color:'var(--amber-2)'}}>project</em>.</>}
        {step === 2 && <>Your <em style={{fontStyle:'italic', color:'var(--amber-2)'}}>materials</em>.</>}
        {step === 3 && <>How to <em style={{fontStyle:'italic', color:'var(--amber-2)'}}>reach you</em>.</>}
      </h3>

      {step === 1 && (
        <>
          <div className={`form-row ${errors.projectType ? 'error' : ''}`}>
            <label>Project type</label>
            <div className="pill-group">
              {PROJECT_TYPES.map(t => (
                <button key={t} type="button" className={`pill ${data.projectType === t ? 'selected' : ''}`} onClick={() => set('projectType', t)}>{t}</button>
              ))}
            </div>
            <div className="err">{errors.projectType}</div>
          </div>
          <div className="form-cols">
            <div className={`form-row ${errors.size ? 'error' : ''}`}>
              <label>Approx. size</label>
              <select value={data.size} onChange={e => set('size', e.target.value)}>
                <option value="">Select size —</option>
                {SIZE_RANGES.map(s => <option key={s}>{s}</option>)}
              </select>
              <div className="err">{errors.size}</div>
            </div>
            <div className={`form-row ${errors.timeline ? 'error' : ''}`}>
              <label>Timeline</label>
              <select value={data.timeline} onChange={e => set('timeline', e.target.value)}>
                <option value="">Select window —</option>
                {TIMELINES.map(s => <option key={s}>{s}</option>)}
              </select>
              <div className="err">{errors.timeline}</div>
            </div>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div className={`form-row ${errors.materials ? 'error' : ''}`}>
            <label>Materials of interest <span style={{color:'var(--fog-1)', textTransform:'none', letterSpacing:0}}>· select any</span></label>
            <div className="pill-group">
              {MATERIALS.map(m => (
                <button key={m} type="button" className={`pill ${data.materials.includes(m) ? 'selected' : ''}`} onClick={() => toggleMaterial(m)}>{m}</button>
              ))}
            </div>
            <div className="err">{errors.materials}</div>
          </div>
          <div className="form-row">
            <label>Notes <span style={{color:'var(--fog-1)', textTransform:'none', letterSpacing:0}}>· optional</span></label>
            <textarea
              value={data.notes}
              onChange={e => set('notes', e.target.value)}
              placeholder="Existing deck condition, slope, design ideas, photos to share, anything we should know…"
            />
          </div>
        </>
      )}

      {step === 3 && (
        <>
          <div className="form-cols">
            <div className={`form-row ${errors.name ? 'error' : ''}`}>
              <label>Full name</label>
              <input type="text" value={data.name} onChange={e => set('name', e.target.value)} placeholder="Jane Doe" />
              <div className="err">{errors.name}</div>
            </div>
            <div className={`form-row ${errors.phone ? 'error' : ''}`}>
              <label>Phone</label>
              <input type="tel" value={data.phone} onChange={e => set('phone', e.target.value)} placeholder="(612) 555-0100" />
              <div className="err">{errors.phone}</div>
            </div>
          </div>
          <div className="form-cols">
            <div className={`form-row ${errors.email ? 'error' : ''}`}>
              <label>Email</label>
              <input type="email" value={data.email} onChange={e => set('email', e.target.value)} placeholder="jane@example.com" />
              <div className="err">{errors.email}</div>
            </div>
            <div className={`form-row ${errors.zip ? 'error' : ''}`}>
              <label>Project ZIP</label>
              <input type="text" maxLength="5" value={data.zip} onChange={e => set('zip', e.target.value.replace(/\D/g, ''))} placeholder="55401" />
              <div className="err">{errors.zip}</div>
            </div>
          </div>
        </>
      )}

      <div className="form-actions">
        {step > 1 ? (
          <button type="button" className="btn btn-ghost" onClick={back} disabled={submitting}>← Back</button>
        ) : (
          <span className="form-step-info">Takes about 2 minutes</span>
        )}
        {step < 3 ? (
          <button type="button" className="btn btn-primary" onClick={next}>Continue <span className="arrow">→</span></button>
        ) : (
          <button type="button" className="btn btn-primary" onClick={submit} disabled={submitting}>
            {submitting ? 'Sending…' : <>Submit Request <span className="arrow">→</span></>}
          </button>
        )}
      </div>
      {submitError && (
        <div style={{
          marginTop: 16, padding: '12px 14px', border: '1px solid #c25c5c',
          color: '#d97777', fontSize: 13, fontFamily: 'var(--sans)', lineHeight: 1.5
        }}>{submitError}</div>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('formCard'));
root.render(<EstimateForm />);
