const { useState, useRef, useEffect } = React;

const SERVICES = [
  { id: 'res',  label: 'Residential wiring', code: 'RES' },
  { id: 'pnl',  label: 'Panel upgrade',      code: 'PNL' },
  { id: 'lgt',  label: 'Lighting / fixtures',code: 'LGT' },
  { id: 'ev',   label: 'EV charger',         code: 'EV'  },
  { id: 'gen',  label: 'Generator',          code: 'GEN' },
  { id: 'emg',  label: 'Emergency',          code: 'EMG' },
  { id: 'oth',  label: 'Something else',     code: 'OTH' },
];

const URGENCY = [
  { id: 'emergency', label: 'Emergency',  sub: 'Call us now'  },
  { id: 'week',      label: 'This week',  sub: 'Within 5 days' },
  { id: 'month',     label: 'This month', sub: 'Planning ahead' },
  { id: 'flex',      label: 'Flexible',   sub: 'Whenever works' },
];

function StepDots({ step, total }) {
  return (
    <div className="flex items-center gap-1.5">
      {Array.from({ length: total }).map((_, i) => (
        <div
          key={i}
          className={`h-1 rounded-full transition-all ${i < step ? 'w-8 bg-brand' : i === step ? 'w-8 bg-ink' : 'w-4 bg-ink/15'}`}
        />
      ))}
    </div>
  );
}

function QuoteForm() {
  const [step, setStep] = useState(0);
  const [services, setServices] = useState([]);
  const [urgency, setUrgency] = useState('');
  const [form, setForm] = useState({ name: '', phone: '', email: '', zip: '', notes: '' });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const jobId = useRef('RDS-' + Math.floor(10000 + Math.random() * 90000));

  const total = 3;

  function toggleService(id) {
    setServices(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  }

  function validateContact() {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    const phoneDigits = form.phone.replace(/\D/g, '');
    if (phoneDigits.length < 10) e.phone = 'Valid phone required';
    if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Invalid email';
    if (form.zip && !/^\d{5}$/.test(form.zip.trim())) e.zip = '5-digit ZIP';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function formatPhone(v) {
    const d = v.replace(/\D/g, '').slice(0, 10);
    if (d.length < 4) return d;
    if (d.length < 7) return `(${d.slice(0,3)}) ${d.slice(3)}`;
    return `(${d.slice(0,3)}) ${d.slice(3,6)}-${d.slice(6)}`;
  }

  function next() {
    if (step === 0 && services.length === 0) {
      setErrors({ services: 'Pick at least one' });
      return;
    }
    if (step === 1 && !urgency) {
      setErrors({ urgency: 'Pick one' });
      return;
    }
    setErrors({});
    setStep(s => Math.min(s + 1, total));
  }
  function back() { setErrors({}); setStep(s => Math.max(s - 1, 0)); }

  async function submit(e) {
    e.preventDefault();
    if (!validateContact()) return;
    setSubmitting(true);
    await new Promise(r => setTimeout(r, 900));
    setSubmitting(false);
    setSubmitted(true);
  }

  if (submitted) {
    return (
      <div className="h-full flex flex-col">
        <div className="flex items-center justify-between mb-6">
          <div className="font-mono text-[10px] tracking-widest text-ink/40">JOB TICKET</div>
          <div className="font-mono text-[10px] text-green-600 flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 bg-green-600 rounded-full" />
            SUBMITTED
          </div>
        </div>
        <div className="border border-ink/10 rounded-xl p-8 bg-paper-2/50">
          <div className="flex items-start justify-between">
            <div>
              <div className="font-mono text-[10px] text-ink/40 tracking-widest">TICKET #</div>
              <div className="font-display font-bold text-3xl mt-1 tracking-tight">{jobId.current}</div>
            </div>
            <div className="w-12 h-12 rounded-full bg-green-500/10 border border-green-500/30 flex items-center justify-center">
              <svg className="w-6 h-6 text-green-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </div>
          </div>

          <h3 className="font-display font-semibold text-2xl mt-8 tracking-tight">Thanks, {form.name.split(' ')[0]}.</h3>
          <p className="text-ink/60 text-[15px] mt-2 leading-relaxed">
            We got your request. A licensed tech will call you back at <span className="font-semibold text-ink">{form.phone}</span> within the hour{urgency === 'emergency' ? ' — marked EMERGENCY, expect a call in minutes.' : '.'}
          </p>

          <div className="mt-8 pt-6 border-t border-ink/10 space-y-2.5 font-mono text-[12px]">
            <div className="flex justify-between"><span className="text-ink/50">SERVICES</span><span>{services.map(s => SERVICES.find(x => x.id === s).code).join(' · ')}</span></div>
            <div className="flex justify-between"><span className="text-ink/50">URGENCY</span><span>{URGENCY.find(u => u.id === urgency).label.toUpperCase()}</span></div>
            {form.zip && <div className="flex justify-between"><span className="text-ink/50">ZIP</span><span>{form.zip}</span></div>}
            <div className="flex justify-between"><span className="text-ink/50">ETA</span><span className="text-brand">&lt; 60 MIN</span></div>
          </div>
        </div>

        <button
          type="button"
          onClick={() => {
            setStep(0); setServices([]); setUrgency('');
            setForm({ name: '', phone: '', email: '', zip: '', notes: '' });
            setSubmitted(false);
            jobId.current = 'RDS-' + Math.floor(10000 + Math.random() * 90000);
          }}
          className="mt-6 text-sm font-semibold text-ink/60 hover:text-brand transition self-start"
        >
          ← Submit another request
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="font-mono text-[10px] tracking-widest text-ink/40">
          STEP {String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}
        </div>
        <StepDots step={step} total={total} />
      </div>

      {/* Steps */}
      <div className="flex-1">
        {step === 0 && (
          <div className="step">
            <h3 className="font-display font-semibold text-2xl tracking-tight">What do you need?</h3>
            <p className="text-ink/50 text-sm mt-1">Pick all that apply.</p>

            <div className="mt-6 flex flex-wrap gap-2">
              {SERVICES.map(s => (
                <button
                  key={s.id}
                  type="button"
                  onClick={() => toggleService(s.id)}
                  data-active={services.includes(s.id)}
                  className="chip px-4 py-2.5 rounded-full border border-ink/15 text-[14px] font-medium hover:border-ink/40"
                >
                  <span className="font-mono text-[10px] tracking-widest opacity-60 mr-2">{s.code}</span>
                  {s.label}
                </button>
              ))}
            </div>
            {errors.services && <div className="mt-3 text-brand text-sm font-mono">⚠ {errors.services}</div>}
          </div>
        )}

        {step === 1 && (
          <div className="step">
            <h3 className="font-display font-semibold text-2xl tracking-tight">How soon?</h3>
            <p className="text-ink/50 text-sm mt-1">We'll route accordingly.</p>

            <div className="mt-6 grid grid-cols-2 gap-2">
              {URGENCY.map(u => (
                <button
                  key={u.id}
                  type="button"
                  onClick={() => setUrgency(u.id)}
                  className={`text-left p-4 rounded-xl border transition ${urgency === u.id
                    ? 'border-brand bg-brand/5'
                    : 'border-ink/10 hover:border-ink/30'}`}
                >
                  <div className="flex items-center justify-between">
                    <div className={`font-display font-semibold text-[17px] ${u.id === 'emergency' && urgency === u.id ? 'text-brand' : ''}`}>{u.label}</div>
                    {u.id === 'emergency' && <span className="font-mono text-[9px] text-brand tracking-widest">EMG</span>}
                  </div>
                  <div className="text-ink/55 text-[13px] mt-0.5">{u.sub}</div>
                </button>
              ))}
            </div>
            {errors.urgency && <div className="mt-3 text-brand text-sm font-mono">⚠ {errors.urgency}</div>}

            <div className="mt-5">
              <label className="font-mono text-[10px] tracking-widest text-ink/50">NOTES (OPTIONAL)</label>
              <textarea
                rows="3"
                value={form.notes}
                onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
                placeholder="Breaker keeps tripping in the kitchen every time the microwave runs…"
                className="mt-1.5 w-full border border-ink/15 rounded-lg px-4 py-3 text-[14px] focus:border-brand resize-none bg-white"
              />
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="step">
            <h3 className="font-display font-semibold text-2xl tracking-tight">Your details.</h3>
            <p className="text-ink/50 text-sm mt-1">We'll call you back within the hour.</p>

            <div className="mt-6 grid grid-cols-2 gap-3">
              <div className="col-span-2">
                <label className="font-mono text-[10px] tracking-widest text-ink/50">FULL NAME *</label>
                <input
                  value={form.name}
                  onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                  placeholder="Jane Doe"
                  className={`mt-1.5 w-full border rounded-lg px-4 py-3 text-[14px] focus:border-brand bg-white ${errors.name ? 'border-brand' : 'border-ink/15'}`}
                />
                {errors.name && <div className="text-brand text-xs font-mono mt-1">⚠ {errors.name}</div>}
              </div>
              <div>
                <label className="font-mono text-[10px] tracking-widest text-ink/50">PHONE *</label>
                <input
                  value={form.phone}
                  onChange={e => setForm(f => ({ ...f, phone: formatPhone(e.target.value) }))}
                  placeholder="(555) 555-5555"
                  inputMode="tel"
                  className={`mt-1.5 w-full border rounded-lg px-4 py-3 text-[14px] focus:border-brand bg-white ${errors.phone ? 'border-brand' : 'border-ink/15'}`}
                />
                {errors.phone && <div className="text-brand text-xs font-mono mt-1">⚠ {errors.phone}</div>}
              </div>
              <div>
                <label className="font-mono text-[10px] tracking-widest text-ink/50">ZIP</label>
                <input
                  value={form.zip}
                  onChange={e => setForm(f => ({ ...f, zip: e.target.value.replace(/\D/g, '').slice(0,5) }))}
                  placeholder="90210"
                  inputMode="numeric"
                  className={`mt-1.5 w-full border rounded-lg px-4 py-3 text-[14px] focus:border-brand bg-white ${errors.zip ? 'border-brand' : 'border-ink/15'}`}
                />
                {errors.zip && <div className="text-brand text-xs font-mono mt-1">⚠ {errors.zip}</div>}
              </div>
              <div className="col-span-2">
                <label className="font-mono text-[10px] tracking-widest text-ink/50">EMAIL (OPTIONAL)</label>
                <input
                  type="email"
                  value={form.email}
                  onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
                  placeholder="jane@example.com"
                  className={`mt-1.5 w-full border rounded-lg px-4 py-3 text-[14px] focus:border-brand bg-white ${errors.email ? 'border-brand' : 'border-ink/15'}`}
                />
                {errors.email && <div className="text-brand text-xs font-mono mt-1">⚠ {errors.email}</div>}
              </div>
            </div>

            {/* Mini summary */}
            <div className="mt-6 p-4 rounded-lg bg-paper-2/60 border border-ink/10 font-mono text-[11px] space-y-1">
              <div className="flex justify-between"><span className="text-ink/50">TICKET</span><span>{jobId.current}</span></div>
              <div className="flex justify-between"><span className="text-ink/50">SERVICES</span><span>{services.map(s => SERVICES.find(x => x.id === s).code).join(' · ') || '—'}</span></div>
              <div className="flex justify-between"><span className="text-ink/50">URGENCY</span><span>{urgency ? URGENCY.find(u => u.id === urgency).label.toUpperCase() : '—'}</span></div>
            </div>
          </div>
        )}
      </div>

      {/* Footer nav */}
      <div className="mt-8 pt-6 border-t border-ink/10 flex items-center justify-between">
        <button
          type="button"
          onClick={back}
          disabled={step === 0}
          className="text-sm font-semibold text-ink/60 hover:text-ink disabled:opacity-0 disabled:pointer-events-none transition"
        >
          ← Back
        </button>

        {step < total - 1 ? (
          <button
            type="button"
            onClick={next}
            className="inline-flex items-center gap-2 bg-ink hover:bg-brand text-white font-semibold px-6 py-3 rounded-full transition"
          >
            Continue
            <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
          </button>
        ) : (
          <button
            type="submit"
            disabled={submitting}
            className="inline-flex items-center gap-2 bg-brand hover:bg-brand-dark text-white font-semibold px-6 py-3 rounded-full transition disabled:opacity-70"
          >
            {submitting ? (
              <>
                <span className="w-4 h-4 rounded-full border-2 border-white/40 border-t-white animate-spin" />
                Submitting…
              </>
            ) : (
              <>
                Submit request
                <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
              </>
            )}
          </button>
        )}
      </div>
    </form>
  );
}

ReactDOM.createRoot(document.getElementById('quote-form-root')).render(<QuoteForm />);
