// Trip calculator with mock API, debounce, abort, skeleton

const TripCalculator = ({ onRequestQuote }) => {
  const [form, setForm] = React.useState({
    destination: 'hunza-skardu',
    travellers: 2,
    days: 5,
    tripStyle: 'standard',
    hotelTier: 4,
    transport: 'private-sedan',
  });
  const [result, setResult] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(false);
  const abortRef = React.useRef(0);

  React.useEffect(() => {
    const reqId = ++abortRef.current;
    setLoading(true);
    setError(false);
    const timer = setTimeout(() => {
      mockEstimate(form).then((res) => {
        if (abortRef.current !== reqId) return; // cancelled
        setResult(res);
        setLoading(false);
      }).catch(() => {
        if (abortRef.current !== reqId) return;
        setError(true);
        setLoading(false);
      });
    }, 400);
    return () => clearTimeout(timer);
  }, [form]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const dest = DEST_OPTS.find((d) => d.value === form.destination);

  return (
    <section id="calc" className="section-alt">
      <div className="container">
        <SectionHead eyebrow="Trip Calculator" title="Plan your perfect trip"
          sub="Real-time estimates from our rate cards. No obligation, no hidden fees — what you see is what you pay." />
        <div className="calc-wrap">
          {/* FORM */}
          <Reveal as="div" {...{ className: 'calc-form' }}>
            <div className="calc-header">
              <div>
                <div className="uppercase-label">Booking · Step 01</div>
                <h3>Build your itinerary</h3>
                <div className="sub">Six questions. Thirty seconds.</div>
              </div>
              <div className="calc-seal">Departures<br/>Lahore<br/>PK</div>
            </div>

            <div className="calc-field">
              <label>Destination</label>
              <select className="calc-select" value={form.destination} onChange={(e) => set('destination', e.target.value)}>
                {DEST_OPTS.map((d) => <option key={d.value} value={d.value}>{d.label}</option>)}
              </select>
            </div>

            <div className="calc-row-2">
              <div className="calc-field">
                <label>Travellers</label>
                <div className="calc-counter">
                  <button onClick={() => set('travellers', Math.max(1, form.travellers - 1))} disabled={form.travellers <= 1}><IconMinus size={16} /></button>
                  <span className="val">{form.travellers}</span>
                  <button onClick={() => set('travellers', Math.min(30, form.travellers + 1))}><IconPlus size={16} /></button>
                </div>
              </div>
              <div className="calc-field">
                <label>Duration <span className="val mono">{form.days} DAYS</span></label>
                <input type="range" className="calc-range" min="2" max="15" value={form.days} onChange={(e) => set('days', +e.target.value)} />
              </div>
            </div>

            <div className="calc-field">
              <label>Trip style</label>
              <div className="calc-pills">
                {[{v:'budget',l:'Budget',s:'Essentials'},{v:'standard',l:'Standard',s:'Most popular'},{v:'luxury',l:'Luxury',s:'Premium'}].map((o) => (
                  <button key={o.v} className={`calc-pill ${form.tripStyle === o.v ? 'active' : ''}`} onClick={() => set('tripStyle', o.v)}>
                    {o.l}<span className="small">{o.s}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="calc-field">
              <label>Accommodation</label>
              <div className="calc-pills">
                {[3,4,5].map((t) => (
                  <button key={t} className={`calc-pill ${form.hotelTier === t ? 'active' : ''}`} onClick={() => set('hotelTier', t)}>
                    Hotel {t}★<span className="small">{t===3?'Good value':t===4?'Comfort':'Top tier'}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="calc-field">
              <label>Transport</label>
              <select className="calc-select" value={form.transport} onChange={(e) => set('transport', e.target.value)}>
                <option value="shared">Shared coaster / group van</option>
                <option value="private-sedan">Private sedan</option>
                <option value="private-suv">Private SUV (4x4 recommended)</option>
                <option value="coaster">Private coaster (groups 8+)</option>
              </select>
            </div>
          </Reveal>

          {/* PRICE PASS */}
          <div className="price-pass">
            <Reveal as="div" {...{ className: 'price-card' }} delay={120}>
              <div className="pp-head">
                <div className="pp-head-row">
                  <span>Boarding Pass / Quote</span>
                  <strong>DEP-{String(Date.now()).slice(-5)}</strong>
                </div>
                <h4>{dest?.label}</h4>
              </div>
              <div className="pp-body">
                <div className="pp-route">
                  <div className="pp-node">
                    <div className="code">LHE</div>
                    <div className="lbl">Lahore · Origin</div>
                  </div>
                  <div className="pp-line"><span className="plane"><IconSend size={12} stroke={2} /></span></div>
                  <div className="pp-node r">
                    <div className="code">{dest?.code}</div>
                    <div className="lbl">Destination</div>
                  </div>
                </div>

                <div className="pp-dash" />

                <div className="pp-items">
                  <div className="pp-item"><span className="k"><IconCalendar size={14} stroke={1.6} />Duration</span><span className="v">{form.days} days</span></div>
                  <div className="pp-item"><span className="k"><IconUsers size={14} stroke={1.6} />Travellers</span><span className="v">{form.travellers} pax</span></div>
                  <div className="pp-item"><span className="k"><IconShield size={14} stroke={1.6} />Trip style</span><span className="v" style={{ textTransform: 'capitalize' }}>{form.tripStyle}</span></div>

                  {loading ? (
                    <>
                      <div className="pp-item"><span className="k">Transport</span><span className="v shimmer">Rs. 0000</span></div>
                      <div className="pp-item"><span className="k">Hotel</span><span className="v shimmer">Rs. 0000</span></div>
                      <div className="pp-item"><span className="k">Meals</span><span className="v shimmer">Rs. 0000</span></div>
                      <div className="pp-item"><span className="k">Guide</span><span className="v shimmer">Rs. 0000</span></div>
                    </>
                  ) : error ? null : result && (
                    <>
                      <div className="pp-item"><span className="k">Transport</span><span className="v">{formatPKR(result.breakdown.transport)}</span></div>
                      <div className="pp-item"><span className="k">Hotel {form.hotelTier}★</span><span className="v">{formatPKR(result.breakdown.hotel)}</span></div>
                      <div className="pp-item"><span className="k">Meals</span><span className="v">{formatPKR(result.breakdown.meals)}</span></div>
                      <div className="pp-item"><span className="k">Guide & Ops</span><span className="v">{formatPKR(result.breakdown.guide)}</span></div>
                    </>
                  )}
                </div>

                {error ? (
                  <div style={{ padding: '20px 0', textAlign: 'center' }}>
                    <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 12 }}>Unable to fetch live pricing right now.</p>
                    <button className="btn btn-primary btn-sm" onClick={() => onRequestQuote(form, null)}>Request a quote</button>
                  </div>
                ) : (
                  <div className="pp-total">
                    <span className="pp">Per person</span>
                    <span className="pp-val">{loading ? <span className="shimmer">Rs. 00,000</span> : formatPKR(result.perPerson)}</span>
                    <span className="tt">Total estimate</span>
                    <span className="tt-val">{loading ? <span className="shimmer">Rs. 000,000</span> : formatPKR(result.total)}</span>
                  </div>
                )}
              </div>

              <div className="pp-foot">
                <button className="btn btn-primary" style={{ width: '100%' }} onClick={() => onRequestQuote(form, result)} disabled={loading || error}>
                  Request custom quote <IconArrowRight size={14} />
                </button>
                <p className="pp-note">Prices shown are estimates based on today's rate card. Peak-season surcharge may apply. Valid until {result?.validUntil || '—'}.</p>
                <div className="pp-barcode">
                  <div className="bars">
                    {Array.from({length: 36}).map((_, i) => (
                      <span key={i} style={{ width: (i%4===0?3:i%3===0?1:2) }} />
                    ))}
                  </div>
                  <span className="ref">REF · DEP/{dest?.code}/{form.days}D</span>
                </div>
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { TripCalculator });
