/* ─── Quote Modal: configurable wizard ──────────────────────────
   Configuration comes from window.HOOPOE_QUOTE (defined in index.html).
   - services: list of options shown in step 1
   - showServiceStep: hide step 1 entirely (becomes a 2-step wizard)
   - timelines / budgets: chips in the scope step
   ───────────────────────────────────────────────────────────────── */

function _getQuoteConfig() {
  const c = window.HOOPOE_QUOTE || {};
  return {
    services: c.services || [],
    showServiceStep: c.showServiceStep !== false,
    timelines: c.timelines || ['< 1 week', '1–2 weeks', '2–4 weeks', '1–3 months', 'Flexible'],
    budgets:   c.budgets   || ['Under AED 5K', 'AED 5–25K', 'AED 25–100K', 'AED 100K+', 'Not sure'],
  };
}

function QuoteModal({ open, onClose, initialService }) {
  const cfg = _getQuoteConfig();
  const QUOTE_SERVICES = cfg.services;
  const TIMELINE_OPTIONS = cfg.timelines;
  const BUDGET_OPTIONS = cfg.budgets;

  // Build the active step list based on config
  const stepDefs = [
    cfg.showServiceStep ? 'services' : null,
    'scope',
    'contact',
  ].filter(Boolean);
  const totalSteps = stepDefs.length;

  const [stepIdx, setStepIdx] = React.useState(0);
  const stepKey = stepDefs[stepIdx];

  const [data, setData] = React.useState({
    services: [],
    timeline: '',
    budget: '',
    name: '',
    email: '',
    phone: '',
    company: '',
    notes: '',
  });

  React.useEffect(() => {
    if (open) {
      setStepIdx(0);
      setData(d => ({ ...d, services: initialService ? [initialService] : [] }));
    }
  }, [open, initialService]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  const toggleService = (id) => {
    setData(d => ({
      ...d,
      services: d.services.includes(id)
        ? d.services.filter(s => s !== id)
        : [...d.services, id]
    }));
  };

  const submitted = stepIdx >= totalSteps;
  const progress = submitted ? 100 : ((stepIdx + 1) / totalSteps) * 100;

  const canAdvance =
    (stepKey === 'services' && data.services.length > 0) ||
    (stepKey === 'scope'    && data.timeline && data.budget) ||
    (stepKey === 'contact'  && data.name && data.email);

  const next = () => stepIdx < totalSteps - 1 ? setStepIdx(stepIdx + 1) : submit();
  const prev = () => stepIdx > 0 ? setStepIdx(stepIdx - 1) : onClose();
  const submit = () => setStepIdx(totalSteps);

  const serviceLabel = (id) => (QUOTE_SERVICES.find(x => x.id === id) || {}).label || id;

  return (
    <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal" role="dialog" aria-label="Request a quote">
        <div className="modal-head">
          <div className="step-meta">
            {!submitted ? <><strong>Step {stepIdx + 1}</strong> / {totalSteps} · Request a Quote</> : <>Submitted</>}
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>

        <div className="modal-progress">
          <div className="bar" style={{ width: `${progress}%` }}/>
        </div>

        <div className="modal-body">
          {stepKey === 'services' && (
            <>
              <h3>What can we build for you?</h3>
              <p className="lead">Select one or more services. You can refine the details next.</p>
              <div className="service-picker">
                {QUOTE_SERVICES.map(s => (
                  <button
                    key={s.id}
                    className={`pick ${data.services.includes(s.id) ? 'selected' : ''}`}
                    onClick={() => toggleService(s.id)}
                  >
                    <span className="num">{s.num}</span>
                    <span>{s.label}</span>
                  </button>
                ))}
              </div>
            </>
          )}

          {stepKey === 'scope' && (
            <>
              <h3>Project scope</h3>
              <p className="lead">Helps us route your enquiry to the right team and reply with accurate lead times.</p>

              <div style={{ marginBottom: 28 }}>
                <label style={{
                  fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--text-3)', display: 'block', marginBottom: 12,
                }}>Target timeline</label>
                <div className="chip-row">
                  {TIMELINE_OPTIONS.map(t => (
                    <button key={t} className={`chip ${data.timeline === t ? 'on' : ''}`}
                            onClick={() => setData(d => ({ ...d, timeline: t }))}>{t}</button>
                  ))}
                </div>
              </div>

              <div>
                <label style={{
                  fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--text-3)', display: 'block', marginBottom: 12,
                }}>Budget range</label>
                <div className="chip-row">
                  {BUDGET_OPTIONS.map(t => (
                    <button key={t} className={`chip ${data.budget === t ? 'on' : ''}`}
                            onClick={() => setData(d => ({ ...d, budget: t }))}>{t}</button>
                  ))}
                </div>
              </div>

              <div style={{ marginTop: 28 }}>
                <div className="field">
                  <label>Notes <span style={{color:'var(--text-4)'}}>(optional)</span></label>
                  <textarea className="textarea" placeholder="Materials, tolerances, quantities, references…"
                            value={data.notes}
                            onChange={(e) => setData(d => ({ ...d, notes: e.target.value }))}/>
                </div>
              </div>
            </>
          )}

          {stepKey === 'contact' && (
            <>
              <h3>How do we reach you?</h3>
              <p className="lead">We'll respond within one business day with a proposal and timeline.</p>

              <div className="row-2">
                <div className="field">
                  <label>Full Name<span className="req">*</span></label>
                  <input className="input" value={data.name}
                         onChange={(e) => setData(d => ({ ...d, name: e.target.value }))}
                         placeholder="Your name"/>
                </div>
                <div className="field">
                  <label>Company</label>
                  <input className="input" value={data.company}
                         onChange={(e) => setData(d => ({ ...d, company: e.target.value }))}
                         placeholder="Company name"/>
                </div>
              </div>
              <div className="row-2">
                <div className="field">
                  <label>Email<span className="req">*</span></label>
                  <input className="input" type="email" value={data.email}
                         onChange={(e) => setData(d => ({ ...d, email: e.target.value }))}
                         placeholder="you@company.com"/>
                </div>
                <div className="field">
                  <label>Phone</label>
                  <input className="input" type="tel" value={data.phone}
                         onChange={(e) => setData(d => ({ ...d, phone: e.target.value }))}
                         placeholder="+971 …"/>
                </div>
              </div>

              <div style={{
                marginTop: 12, padding: '14px 16px',
                background: 'var(--bg-2)', border: '1px solid var(--line)',
                fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em',
                color: 'var(--text-3)',
              }}>
                <div style={{color:'var(--accent)', marginBottom: 4, letterSpacing: '0.12em'}}>SUMMARY</div>
                {cfg.showServiceStep && (
                  <div>Services: {data.services.map(serviceLabel).join(' · ') || '—'}</div>
                )}
                <div>Timeline: {data.timeline || '—'} · Budget: {data.budget || '—'}</div>
              </div>
            </>
          )}

          {submitted && (
            <div style={{ textAlign: 'center', padding: '28px 0' }}>
              <div style={{
                width: 64, height: 64, margin: '0 auto 24px',
                background: 'var(--accent)', display: 'grid', placeItems: 'center',
              }}>
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#111" strokeWidth="3">
                  <path d="M4 12 L10 18 L20 6"/>
                </svg>
              </div>
              <h3>Request received.</h3>
              <p className="lead" style={{ maxWidth: '38ch', margin: '0 auto' }}>
                Thank you, {data.name || 'team'}. Our production lead will email you at <strong style={{color:'var(--text)'}}>{data.email}</strong> within one business day. Reference: <strong style={{color:'var(--accent)', fontFamily:'var(--mono)'}}>HPT-{Math.floor(Math.random()*9000+1000)}</strong>
              </p>
            </div>
          )}
        </div>

        {!submitted && (
          <div className="modal-foot">
            <button className="btn btn-ghost" onClick={prev}>
              {stepIdx === 0 ? 'Cancel' : '← Back'}
            </button>
            <button className="btn btn-primary" onClick={next} disabled={!canAdvance}
                    style={{ opacity: canAdvance ? 1 : 0.4, cursor: canAdvance ? 'pointer' : 'not-allowed' }}>
              {stepIdx === totalSteps - 1 ? 'Submit Request' : 'Continue'}
              <span className="arr">→</span>
            </button>
          </div>
        )}
        {submitted && (
          <div className="modal-foot" style={{ justifyContent: 'center' }}>
            <button className="btn btn-primary" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { QuoteModal });
