/* OpSpot — primary intake form. Simulates success, stores lead locally,
   then shows Courier routing the lead through the crew. */
const { useState, useEffect } = React;

const INDUSTRIES = ['Home services (HVAC, plumbing, roofing…)', 'Auto / repair', 'Med / dental / clinic', 'Legal / accounting', 'Real estate', 'Restaurant / hospitality', 'Salon / spa / fitness', 'Other'];
const TEAM_SIZES = ['Just me', '2–10', '11–50', '50+'];
const AUTOMATE = ['Answering inbound calls', 'Web form & lead response', 'Quote / estimate follow-up', 'Booking & reminders', 'Invoicing & collections', 'Reviews & customer updates', 'Not sure — audit me'];

const ROUTE_STEPS = [
  { id: 'courier', text: 'Courier caught your request', tick: 'captured' },
  { id: 'recon', text: 'Recon is auditing your business', tick: 'queued' },
  { id: 'comms', text: 'Comms will draft your summary', tick: 'next' },
  { id: 'redpen', text: 'Redpen will check it before you see it', tick: 'gate' },
  { id: 'marshal', text: 'Marshal will offer audit times', tick: 'soon' },
];

function ContactForm() {
  const [form, setForm] = useState({
    name: '', business: '', website: '', email: '', phone: '', industry: '',
    team: '', volume: '', jobValue: '', bottleneck: '', tools: '', automate: '',
  });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [routeOn, setRouteOn] = useState(0);
  const [receiptId] = useState(() => 'op-lead-' + Math.random().toString(36).slice(2, 6).toUpperCase());

  const set = (k) => (e) => { setForm(f => ({ ...f, [k]: e.target.value })); if (errors[k]) setErrors(er => ({ ...er, [k]: false })); };

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = true;
    if (!form.business.trim()) er.business = true;
    if (!/^\S+@\S+\.\S+$/.test(form.email)) er.email = true;
    if (!form.phone.trim()) er.phone = true;
    setErrors(er);
    if (Object.keys(er).length) return;
    // store lead locally (later: POST to Courier inbound webhook)
    try {
      const leads = JSON.parse(localStorage.getItem('opspot_leads') || '[]');
      leads.push({ ...form, receiptId, at: new Date().toISOString() });
      localStorage.setItem('opspot_leads', JSON.stringify(leads));
    } catch (e) {}
    setSent(true);
  };

  useEffect(() => {
    if (!sent) return;
    const timers = ROUTE_STEPS.map((_, i) => setTimeout(() => setRouteOn(i + 1), 350 + i * 520));
    return () => timers.forEach(clearTimeout);
  }, [sent]);

  const crewMeta = (id) => CREW.find(c => c.id === id) || CREW[0];

  return (
    <section className="section-pad" id="contact" style={{ paddingTop: 110 }}>
      <div className="container">
        <div className="contact-wrap">
          <Reveal className="contact-aside">
            <span className="kicker"><b>08</b> · Start here</span>
            <h2 className="display" style={{ marginTop: 14 }}>Get your free audit.</h2>
            <p className="ca-sub">Tell us about the business. Recon runs a free audit, finds your leak, and Deal Desk comes back with a right-sized package and a net-ROI target. No charge, no obligation.</p>
            <div className="ca-points">
              <div className="cap" style={{ '--c': 'var(--recon)' }}><span className="ci"><Ico d={ICONS.search} size={16} /></span><div><b>A real leak ledger</b><span>Where your money is leaking, in dollars.</span></div></div>
              <div className="cap" style={{ '--c': 'var(--dealdesk)' }}><span className="ci"><Ico d={ICONS.dollar} size={16} /></span><div><b>A net-ROI target</b><span>What the crew should return per month.</span></div></div>
              <div className="cap" style={{ '--c': 'var(--marshal)' }}><span className="ci"><Ico d={ICONS.calendar} size={16} /></span><div><b>A 24-hour install plan</b><span>If it makes sense, we start same day.</span></div></div>
            </div>
            <p className="ca-alt">Prefer to talk? <a href={CAL} target="_blank" rel="noopener">Book a 30-min call →</a></p>
          </Reveal>

          <Reveal delay={1} className="form-card">
            {!sent ? (
              <form className="form-grid" onSubmit={submit} noValidate>
                <div className="field">
                  <label>Your name <span className="req">*</span></label>
                  <input className={errors.name ? 'invalid' : ''} value={form.name} onChange={set('name')} placeholder="Jordan Avery" />
                  {errors.name && <span className="err">needed so we know who to call</span>}
                </div>
                <div className="field">
                  <label>Business name <span className="req">*</span></label>
                  <input className={errors.business ? 'invalid' : ''} value={form.business} onChange={set('business')} placeholder="Ridge Plumbing" />
                  {errors.business && <span className="err">needed for the audit</span>}
                </div>
                <div className="field">
                  <label>Email <span className="req">*</span></label>
                  <input className={errors.email ? 'invalid' : ''} type="email" value={form.email} onChange={set('email')} placeholder="jordan@ridge.com" />
                  {errors.email && <span className="err">enter a valid email</span>}
                </div>
                <div className="field">
                  <label>Phone <span className="req">*</span></label>
                  <input className={errors.phone ? 'invalid' : ''} value={form.phone} onChange={set('phone')} placeholder="(910) 555-0114" />
                  {errors.phone && <span className="err">so Courier can reach you</span>}
                </div>
                <div className="field">
                  <label>Website</label>
                  <input value={form.website} onChange={set('website')} placeholder="ridgeplumbing.com" />
                </div>
                <div className="field">
                  <label>Industry</label>
                  <select value={form.industry} onChange={set('industry')}>
                    <option value="">Select…</option>
                    {INDUSTRIES.map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>Team size</label>
                  <select value={form.team} onChange={set('team')}>
                    <option value="">Select…</option>
                    {TEAM_SIZES.map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>Monthly leads / jobs</label>
                  <input value={form.volume} onChange={set('volume')} placeholder="~120" />
                </div>
                <div className="field">
                  <label>Average job value</label>
                  <input value={form.jobValue} onChange={set('jobValue')} placeholder="$1,800" />
                </div>
                <div className="field">
                  <label>What to automate first</label>
                  <select value={form.automate} onChange={set('automate')}>
                    <option value="">Select…</option>
                    {AUTOMATE.map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                </div>
                <div className="field full">
                  <label>Biggest bottleneck right now</label>
                  <textarea value={form.bottleneck} onChange={set('bottleneck')} placeholder="Missed calls during jobs, quotes that never get a second follow-up…" />
                </div>
                <div className="field full">
                  <label>Tools you use now</label>
                  <input value={form.tools} onChange={set('tools')} placeholder="Jobber, QuickBooks, a Google Voice number, sticky notes…" />
                </div>
                <div className="form-foot">
                  <button type="submit" className="btn btn-primary btn-xl">Send it to Courier →</button>
                  <span className="privacy">Goes straight to the crew. We never share your info. Cancel anytime.</span>
                </div>
              </form>
            ) : (
              <div className="form-success">
                <div className="fs-check"><Ico d={ICONS.check} size={30} /></div>
                <h3>Got it — Courier’s on it.</h3>
                <p>Thanks, {form.name.split(' ')[0] || 'there'}. Your request is in the queue and routing through the crew right now. You’ll hear back within one business day.</p>
                <div className="fs-route">
                  {ROUTE_STEPS.map((r, i) => {
                    const m = crewMeta(r.id);
                    return (
                      <div className={`fr ${routeOn > i ? 'on' : ''}`} key={r.id} style={{ '--c1': m.c1, '--c2': m.c2 }}>
                        <span className="ag">{m.name === 'Deal Desk' ? 'DD' : m.name[0]}</span>
                        <span><b>{m.name}.</b> {r.text}</span>
                        {routeOn > i && <span className="tick">{r.tick}</span>}
                      </div>
                    );
                  })}
                </div>
                <div className="fs-receipt">receipt · {receiptId} · saved · {new Date().toLocaleDateString()}</div>
              </div>
            )}
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ContactForm });
