// Contact modal + multi-step quote builder + reusable form pieces

function ContactModal({ open, onClose, defaultService = '' }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  React.useEffect(() => {
    if (open) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  return (
    <div className={`modal-veil ${open ? 'is-open' : ''}`} onClick={onClose} aria-hidden={!open}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Contact Aurora" onClick={e => e.stopPropagation()}>
        <button className="modal-close" aria-label="Close" onClick={onClose}>
          <Icon name="x" size={18} />
        </button>
        <QuoteForm compact defaultService={defaultService} onSubmit={() => { /* on success state is owned inside */ }} />
      </div>
    </div>
  );
}
window.ContactModal = ContactModal;

const QUOTE_SERVICES = [
  { id: 'websites',   label: 'Website',         desc: 'Design + build',   icon: 'browser' },
  { id: 'email',      label: 'Business Email & IT', desc: 'Setup + support', icon: 'mail' },
  { id: 'networking', label: 'Network Consulting', desc: 'Tune-ups + advice', icon: 'wifi' },
  { id: 'cameras',    label: 'Camera Support',  desc: 'Existing systems',  icon: 'camera' },
];
const PROPERTY_TYPES = ['Single-family home', 'Apartment / condo', 'Small business / office', 'Restaurant / retail', 'Multi-tenant building', 'Other'];
// Budget bands per service family; the generic list covers mixed picks.
const BUDGETS_GENERIC = ['Under $2k', '$2k–$5k', '$5k–$10k', '$10k+', 'Not sure yet'];
const BUDGETS_BY_KIND = {
  websites: ['Under $2.5k', '$2.5k–$5k', '$5k–$10k', '$10k+', 'Not sure yet'],
  email:    ['Under $500', '$500–$1k', '$1k–$2.5k', '$2.5k+', 'Not sure yet'],
  support:  ['Under $500', '$500–$1.5k', '$1.5k–$3k', '$3k+', 'Not sure yet'],
};
const TIMELINES = ['ASAP / urgent', 'Within 30 days', '1–3 months', 'Just exploring'];

function QuoteForm({ defaultService = '', compact = false, onSubmit }) {
  const initialServices = defaultService ? [defaultService] : [];
  const [step, setStep] = React.useState(0);
  const [services, setServices] = React.useState(initialServices);
  const [propertyType, setPropertyType] = React.useState('');
  const [size, setSize] = React.useState('');
  const [currentSite, setCurrentSite] = React.useState('');
  const [emailSetup, setEmailSetup] = React.useState('');
  const [budget, setBudget] = React.useState('');
  const [timeline, setTimeline] = React.useState('');
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [address, setAddress] = React.useState('');
  const [notes, setNotes] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);

  const steps = ['Service', 'Project', 'Details'];

  // Step-2 questions depend on what was picked in step 1: on-site services
  // get property questions, websites/email get their own, timeline is
  // universal.
  const needsProperty = services.includes('networking') || services.includes('cameras');
  const needsWebsite  = services.includes('websites');
  const needsEmail    = services.includes('email');

  // Budget bands match the service family; mixed picks fall back to generic.
  const kinds = new Set(services.map(s => s === 'websites' ? 'websites' : s === 'email' ? 'email' : 'support'));
  const budgetOptions = kinds.size === 1 ? BUDGETS_BY_KIND[[...kinds][0]] : BUDGETS_GENERIC;

  const canNextStep = () => {
    if (step === 0) return services.length > 0;
    if (step === 1) return !!timeline && (!needsProperty || !!propertyType);
    return true;
  };

  const toggleService = (id) => {
    setServices(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
    setBudget(''); // ranges change with the service mix; don't carry a stale pick
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
    onSubmit && onSubmit({ services, propertyType, size, currentSite, emailSetup, budget, timeline, name, email, phone, address, notes });
  };

  if (submitted) {
    return (
      <div style={{textAlign:'center', padding: '12px 4px'}}>
        <div className="icon-tile icon-tile--lg icon-tile--aurora" style={{margin:'0 auto'}}>
          <Icon name="check" size={28} />
        </div>
        <h3 className="h2" style={{margin:'24px 0 12px', fontSize:'clamp(24px, 3vw, 32px)'}}>Thanks, {name || 'there'} — we'll be in touch.</h3>
        <p className="lede" style={{fontSize:16, margin:'0 auto'}}>
          We respond personally within one business day. No call center, no auto-replies.
        </p>
        <div className="mono dim" style={{marginTop:24, fontSize:12}}>
          Request received · {new Date().toLocaleString()}
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="quote-form">
      <div className="spaced-cap" style={{marginBottom:12}}>Free Consultation</div>
      <h3 className="h2" style={{fontSize:'clamp(24px, 3.2vw, 36px)', margin:'0 0 8px'}}>
        Let's talk about your project.
      </h3>
      <p className="body" style={{margin:'0 0 28px', fontSize:15}}>
        We respond within one business day — Mon–Fri. No salespeople.
      </p>

      <div className="steps-bar">
        {steps.map((s, i) => (
          <div
            key={s}
            className={`step-pill ${step === i ? 'is-active' : ''} ${i < step ? 'is-done' : ''}`}
          >
            <span>0{i+1} · {s}</span>
            {i < step && <Icon name="check" size={12} />}
          </div>
        ))}
      </div>

      {step === 0 && (
        <div>
          <div className="label">What can we help with? (Choose any.)</div>
          <div className="service-pick">
            {QUOTE_SERVICES.map(s => {
              const checked = services.includes(s.id);
              return (
                <label key={s.id} className={checked ? 'is-checked' : ''}>
                  <input
                    type="checkbox" checked={checked}
                    onChange={() => toggleService(s.id)}
                  />
                  <Icon name={s.icon} size={20} />
                  <div className="ttl">{s.label}</div>
                  <div className="desc">{s.desc}</div>
                </label>
              );
            })}
          </div>
        </div>
      )}

      {step === 1 && (
        <div>
          {needsProperty && (
            <>
              <div className="field">
                <label className="label">Property type</label>
                <select className="select" value={propertyType} onChange={e => setPropertyType(e.target.value)}>
                  <option value="">Select…</option>
                  {PROPERTY_TYPES.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="label">Approximate square footage <span className="dim">(optional)</span></label>
                <input className="input" placeholder="e.g. 2,400 sq ft" value={size} onChange={e => setSize(e.target.value)} />
              </div>
            </>
          )}
          {needsWebsite && (
            <div className="field">
              <label className="label">Current website <span className="dim">(optional — leave blank if starting fresh)</span></label>
              <input className="input" placeholder="yourbusiness.com" value={currentSite} onChange={e => setCurrentSite(e.target.value)} />
            </div>
          )}
          {needsEmail && (
            <div className="field">
              <label className="label">Current email setup <span className="dim">(optional)</span></label>
              <input className="input" placeholder="e.g. free Gmail, GoDaddy email, Microsoft 365 — and roughly how many people" value={emailSetup} onChange={e => setEmailSetup(e.target.value)} />
            </div>
          )}
          <div className="field">
            <label className="label">Timeline</label>
            <select className="select" value={timeline} onChange={e => setTimeline(e.target.value)}>
              <option value="">Select…</option>
              {TIMELINES.map(p => <option key={p} value={p}>{p}</option>)}
            </select>
          </div>
          <div className="field">
            <label className="label">Budget range <span className="dim">(optional)</span></label>
            <select className="select" value={budget} onChange={e => setBudget(e.target.value)}>
              <option value="">Select…</option>
              {budgetOptions.map(p => <option key={p} value={p}>{p}</option>)}
            </select>
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <div className="field-row">
            <div className="field">
              <label className="label">Name</label>
              <input className="input" required value={name} onChange={e => setName(e.target.value)} />
            </div>
            <div className="field">
              <label className="label">Phone</label>
              <input className="input" required type="tel" value={phone} onChange={e => setPhone(e.target.value)} />
            </div>
          </div>
          <div className="field">
            <label className="label">Email</label>
            <input className="input" required type="email" value={email} onChange={e => setEmail(e.target.value)} />
          </div>
          <div className="field">
            <label className="label">Address <span className="dim">(or rough neighborhood)</span></label>
            <input className="input" placeholder="Raleigh, Cary, Wake Forest…" value={address} onChange={e => setAddress(e.target.value)} />
          </div>
          <div className="field">
            <label className="label">Notes <span className="dim">(optional)</span></label>
            <textarea className="textarea" rows="4" placeholder="Anything we should know? What's broken, what you're picturing, links to your current site…" value={notes} onChange={e => setNotes(e.target.value)} />
          </div>
        </div>
      )}

      <div className="row row--between gap-3 mt-8" style={{alignItems:'center', flexWrap:'wrap'}}>
        <div className="spaced-cap dim">
          {step + 1} of {steps.length}
        </div>
        <div className="row gap-3">
          {step > 0 && (
            <button type="button" className="btn btn--secondary" onClick={() => setStep(s => s - 1)}>
              <Icon name="arrow-left" size={16} /> Back
            </button>
          )}
          {step < steps.length - 1 ? (
            <button type="button" className="btn btn--primary" disabled={!canNextStep()} onClick={() => setStep(s => s + 1)}>
              Continue <Icon name="arrow-right" size={16} />
            </button>
          ) : (
            <button type="submit" className="btn btn--primary">
              Send Request <Icon name="arrow-up-right" size={16} />
            </button>
          )}
        </div>
      </div>
    </form>
  );
}
window.QuoteForm = QuoteForm;
