// BookingsHub — playbook tab with per-category search forms that fan out to
// affiliate-tagged provider URLs. Saves searches as snips for later reference.
const { useState: useStateBH, useEffect: useEffectBH, useMemo: useMemoBH } = React;

function BookingsHub({ playbook }) {
  const store = useStore();
  const cats = window.BOOKING_CATEGORIES;
  const [activeCat, setActiveCat] = useStateBH(cats[0].id);
  const cat = cats.find(c => c.id === activeCat);

  return (
    <div className="bookings-hub">
      <div className="bookings-cats">
        {cats.map(c => (
          <button key={c.id}
            className={`bk-cat ${activeCat === c.id ? 'on' : ''}`}
            onClick={() => setActiveCat(c.id)}>
            <span className="bk-cat-icon">{c.icon}</span>
            <span className="bk-cat-label">{c.label}</span>
          </button>
        ))}
      </div>

      <BookingSearch key={activeCat} cat={cat} playbook={playbook}/>
    </div>
  );
}

function BookingSearch({ cat, playbook }) {
  const store = useStore();
  const dests = playbook.destinations;
  const [destId, setDestId] = useStateBH(dests[0]?.id || '');
  const [origin, setOrigin] = useStateBH('');
  const [destOverride, setDestOverride] = useStateBH('');
  const [checkIn, setCheckIn] = useStateBH('');
  const [checkOut, setCheckOut] = useStateBH('');
  const [adults, setAdults] = useStateBH(2);
  const [rooms, setRooms] = useStateBH(1);
  const [pickup, setPickup] = useStateBH('');
  const [pickupDate, setPickupDate] = useStateBH('');
  const [dropoffDate, setDropoffDate] = useStateBH('');

  // Auto-fill from selected destination
  const dest = dests.find(d => d.id === destId);
  useEffectBH(() => {
    if (dest) {
      if (dest.arrival && !checkIn) setCheckIn(dest.arrival);
      if (dest.departure && !checkOut) setCheckOut(dest.departure);
      if (cat.id === 'car' && dest.label && !pickup) setPickup(dest.label);
      if (cat.id === 'car' && dest.arrival && !pickupDate) setPickupDate(dest.arrival);
      if (cat.id === 'car' && dest.departure && !dropoffDate) setDropoffDate(dest.departure);
    }
  }, [destId, cat.id]);

  const ctx = useMemoBH(() => {
    const destLabel = destOverride || dest?.label || '';
    const country = (destLabel.split(',').pop() || '').trim();
    return {
      origin: origin || '',
      dest: destLabel,
      country,
      lat: dest?.lat,
      lng: dest?.lng,
      checkIn, checkOut, adults, rooms,
      pickup: pickup || destLabel,
      pickupDate, dropoffDate,
    };
  }, [origin, destOverride, dest, checkIn, checkOut, adults, rooms, pickup, pickupDate, dropoffDate]);

  const links = useMemoBH(() => window.buildBookingLinks(cat.id, ctx), [cat.id, ctx]);

  // Save search as snip
  const saveAsSnip = () => {
    const summary = buildSearchSummary(cat, ctx);
    store.addSnip(playbook.id, {
      type: snipTypeFor(cat.id),
      title: summary.title,
      body: summary.body,
      url: '',
      destinationId: dest?.id || null,
      destinationLabel: ctx.dest,
      tags: [cat.id, 'booking-search'],
      source: 'bookings-hub',
    });
  };

  const needs = cat.needs;

  return (
    <div className="bk-search">
      <div className="bk-search-head">
        <div>
          <div className="loc-kicker">SEARCH · {cat.label.toUpperCase()}</div>
          <h3 className="bk-search-title">Compare {cat.label.toLowerCase()} across providers</h3>
        </div>
        {dests.length === 0 && (
          <div className="bk-empty-hint">
            Add a destination to your playbook for one-click pre-fill.
          </div>
        )}
      </div>

      <div className="bk-form">
        {dests.length > 0 && (
          <label className="bk-field bk-field-wide">
            <span>Destination from playbook</span>
            <select value={destId} onChange={e => { setDestId(e.target.value); setDestOverride(''); }}>
              <option value="">— None / use override —</option>
              {dests.map(d => <option key={d.id} value={d.id}>{d.label}</option>)}
            </select>
          </label>
        )}

        {needs.includes('origin') && (
          <label className="bk-field">
            <span>From</span>
            <input placeholder={cat.id === 'flight' ? 'JFK, NYC, or city' : 'origin city'}
              value={origin} onChange={e => setOrigin(e.target.value)}/>
          </label>
        )}

        {(needs.includes('dest') || needs.includes('country')) && (
          <label className="bk-field">
            <span>{needs.includes('country') ? 'Country' : 'To'}</span>
            <input placeholder={dest?.label || 'destination'}
              value={destOverride} onChange={e => setDestOverride(e.target.value)}/>
          </label>
        )}

        {needs.includes('pickup') && (
          <label className="bk-field">
            <span>Pickup location</span>
            <input placeholder="airport or city"
              value={pickup} onChange={e => setPickup(e.target.value)}/>
          </label>
        )}

        {(needs.includes('dates') || needs.includes('date')) && (
          <>
            <label className="bk-field">
              <span>{cat.id === 'flight' ? 'Depart' : cat.id === 'train' ? 'Date' : 'Check-in'}</span>
              <input type="date" value={checkIn} onChange={e => setCheckIn(e.target.value)}/>
            </label>
            {needs.includes('dates') && (
              <label className="bk-field">
                <span>{cat.id === 'flight' ? 'Return' : 'Check-out'}</span>
                <input type="date" value={checkOut} onChange={e => setCheckOut(e.target.value)}/>
              </label>
            )}
          </>
        )}

        {needs.includes('rentalDates') && (
          <>
            <label className="bk-field">
              <span>Pickup date</span>
              <input type="date" value={pickupDate} onChange={e => setPickupDate(e.target.value)}/>
            </label>
            <label className="bk-field">
              <span>Drop-off date</span>
              <input type="date" value={dropoffDate} onChange={e => setDropoffDate(e.target.value)}/>
            </label>
          </>
        )}

        {needs.includes('guests') && (
          <>
            <label className="bk-field bk-field-sm">
              <span>Adults</span>
              <input type="number" min="1" max="9" value={adults}
                onChange={e => setAdults(Math.max(1, +e.target.value || 1))}/>
            </label>
            {cat.id === 'hotel' && (
              <label className="bk-field bk-field-sm">
                <span>Rooms</span>
                <input type="number" min="1" max="5" value={rooms}
                  onChange={e => setRooms(Math.max(1, +e.target.value || 1))}/>
              </label>
            )}
          </>
        )}
      </div>

      <div className="bk-providers">
        {links.map(p => (
          <a key={p.id} href={p.url} target="_blank" rel="noopener noreferrer sponsored"
            className="bk-provider" style={{ '--bk-color': p.color }}>
            <div className="bk-provider-head">
              <span className="bk-provider-dot" style={{ background: p.color }}/>
              <span className="bk-provider-name">{p.name}</span>
              {!p.configured && <span className="bk-uncfg" title="Affiliate ID not set in admin · still works, just no commission">no aff</span>}
              <span className="bk-arrow">↗</span>
            </div>
            <div className="bk-provider-note">{p.note}</div>
            <div className="bk-provider-net">{p.network === 'none' ? 'no affiliate' : p.network} {p.tagParam ? `· ${p.tagParam}` : ''}</div>
          </a>
        ))}
      </div>

      <div className="bk-actions">
        <button className="bk-save" onClick={saveAsSnip}>
          ✎ Save this search to dashboard
        </button>
        <div className="bk-disclosure">
          Some links earn us a commission at no cost to you. We pick providers we'd use ourselves.
        </div>
      </div>
    </div>
  );
}

function buildSearchSummary(cat, ctx) {
  const parts = [];
  if (ctx.origin) parts.push(ctx.origin);
  if (ctx.dest) parts.push('→ ' + ctx.dest);
  const dateBit = ctx.checkIn ? ` · ${ctx.checkIn}${ctx.checkOut ? ' to ' + ctx.checkOut : ''}` : '';
  const title = `${cat.label}: ${parts.join(' ') || ctx.country || 'search'}${dateBit}`;
  const body = JSON.stringify(stripEmpty(ctx), null, 2);
  return { title: title.slice(0, 200), body };
}

function stripEmpty(obj) {
  const o = {};
  for (const [k, v] of Object.entries(obj)) {
    if (v != null && v !== '' && !(typeof v === 'number' && isNaN(v))) o[k] = v;
  }
  return o;
}

function snipTypeFor(catId) {
  const map = { flight: 'flight', hotel: 'lodging', longstay: 'longstay',
    car: 'car', train: 'train', activity: 'activity', esim: 'esim',
    insurance: 'insurance', coworking: 'coworking', visa: 'visa',
    fitness: 'fitness', money: 'money' };
  return map[catId] || 'note';
}

window.BookingsHub = BookingsHub;
