// offer-browser.jsx — "Browse full screen": the Offers panel's search with room
// to see. Tick holidays, then "Add N to email" adds them all and closes.
//
// Rendered by sidebar.jsx's Sidebar (not by App) so every pick goes through
// the Sidebar's own resolveAndAdd — the SAME Hub ref check a single Add uses —
// and never a second copy of the compliance mapping (operator, ATOL, link).
// Products: Holidays (the agent's live offers, with the same lists to choose
// from as the panel) plus the catalogues the Hub says the agent can sell.
function OfferBrowser({ sources, added, resolveAndAdd, onClose }) {
  const HB = window.HolidayBrowse;
  const { Close, Search, Check, Plane, PalmTree } = window.Icons;
  const FilterField = window.FilterField;   // sidebar.jsx's labelled filter, shared
  const EMPTY = { dest: '', type: '', airport: '', month: '', operator: '', q: '' };
  const products = [{ key: 'holidays', label: 'Holidays' }]
    .concat((HB.CATALOGUE_TABS || []).filter((t) => (sources || []).some((s) => s.key === t.source))
      .map((t) => ({ key: t.source, label: t.label, placeholder: t.placeholder })));
  const [product, setProduct] = React.useState('holidays');
  const [filters, setFilters] = React.useState(EMPTY);
  const [qText, setQText] = React.useState('');
  const [data, setData] = React.useState(null);
  const [page, setPage] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  // Picked holidays, in the order they were ticked: id → the add shape.
  const [picked, setPicked] = React.useState([]);
  const [adding, setAdding] = React.useState(false);
  const [problem, setProblem] = React.useState('');
  const isHolidays = product === 'holidays';

  React.useEffect(() => {
    const t = setTimeout(() => setFilters((f) => (f.q === qText ? f : { ...f, q: qText })), 300);
    return () => clearTimeout(t);
  }, [qText]);

  React.useEffect(() => {
    let gone = false;
    setLoading(true);
    const ask = isHolidays ? HB.browseHolidays(filters, page) : HB.searchCatalogue(product, filters.q);
    ask.then((d) => {
      if (gone) return;
      setLoading(false);
      if (isHolidays) setData((prev) => (page > 1 && prev && !d.error ? { ...d, offers: prev.offers.concat(d.offers || []) } : d));
      else setData(d);
    });
    return () => { gone = true; };
  }, [product, filters, page]); // eslint-disable-line

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && !adding) onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [adding]); // eslint-disable-line

  const basis = (b) => (window.getBasisDetail && window.parsePriceCat ? window.getBasisDetail(window.parsePriceCat(b)) : '');
  // Every card, whatever the product, as { key, mapped, img, title, price, deal, meta, from }.
  const cards = !data || data.error || data.unavailable ? [] : isHolidays
    ? (data.offers || []).map((r) => {
        const mapped = HB.browseRowToOffer(r, basis);
        const month = (r.months && r.months[0]) || '';
        return { key: String(r.id), mapped, img: r.image, title: mapped.dest, price: r.price_text, deal: r.title,
                 meta: [r.nights && `${r.nights} nights`, r.board, r.operator].filter(Boolean).join(' · '),
                 from: [mapped.airport && `From ${mapped.airport}`, month && HB.monthLabel(month)].filter(Boolean).join(' · ') };
      })
    : (data.products || []).map((p) => {
        const mapped = HB.catalogueToOffer(p);
        return { key: String(mapped.id), mapped, img: p.image, title: p.title, price: p.price_text, deal: p.subtitle,
                 meta: [p.operator, p.badge].filter(Boolean).join(' · '), from: '' };
      });
  const facets = (data && data.facets) || {};
  const names = (list) => (list || []).map((x) => x.name);
  const set = (k) => (v) => { setPage(1); setFilters((f) => ({ ...f, [k]: v })); };
  const pickedKeys = new Set(picked.map((p) => p.key));
  const toggle = (c) => {
    if (added.has(c.key) || adding) return;
    setPicked((list) => (list.some((p) => p.key === c.key) ? list.filter((p) => p.key !== c.key) : list.concat([c])));
  };
  const addAll = async () => {
    if (!picked.length || adding) return;
    setAdding(true); setProblem('');
    let failed = 0;
    for (const c of picked) {
      const ok = await resolveAndAdd(c.mapped);
      if (ok === false) failed += 1;
    }
    setAdding(false);
    if (failed) {
      setProblem(`${failed} of ${picked.length} couldn't be added — they may have just sold out, or aren't on your offers any more.`);
      setPicked([]);
      return;
    }
    onClose();
  };
  const changeProduct = (k) => { setProduct(k); setFilters(EMPTY); setQText(''); setPage(1); setData(null); };
  const total = isHolidays ? (data && !data.error ? data.total : null) : (data && !data.error && !data.unavailable ? cards.length : null);
  const placeholder = isHolidays ? 'Search hotel or place' : ((products.find((p) => p.key === product) || {}).placeholder || 'Search');
  const ProdIc = isHolidays || product === 'tourhub' ? Plane : PalmTree;

  return (
    <div className="eb-browser" role="dialog" aria-modal="true" aria-labelledby="eb-browser-title">
      <div className="eb-browser-head">
        <div className="eb-browser-titlebar">
          <h2 id="eb-browser-title">Find holidays for this email</h2>
          <button type="button" className="eb-btn eb-btn--secondary" onClick={onClose} disabled={adding}><Close />Close</button>
        </div>
        <div className="eb-browser-controls">
          {products.length > 1 && (
            <label className="eb-product eb-browser-product">
              <span className="eb-filter-label">Product</span>
              <span className="eb-product-field">
                <ProdIc />
                <select className="eb-select eb-select--product" value={product} onChange={(e) => changeProduct(e.target.value)} aria-label="Product">
                  {products.map((p) => <option key={p.key} value={p.key}>{p.label}</option>)}
                </select>
              </span>
            </label>
          )}
          <label className="eb-search eb-browser-search">
            <span className="eb-filter-label">Search</span>
            <span className="eb-search-field">
              <Search />
              <input className="eb-search-input" type="search" value={qText} placeholder={placeholder} aria-label={placeholder}
                     onChange={(e) => setQText(e.target.value)} autoFocus />
            </span>
          </label>
          {isHolidays && (<>
            <FilterField label="Destination" any="Any destination" value={filters.dest} options={names(facets.destinations)} onChange={set('dest')} />
            <FilterField label="Holiday type" any="Any holiday type" value={filters.type} options={names(facets.types)} onChange={set('type')} />
            <FilterField label="Flying from" any="Any airport" value={filters.airport} options={names(facets.airports)} onChange={set('airport')} />
            <FilterField label="Month" any="Any month" value={filters.month} options={names(facets.months)} onChange={set('month')} format={HB.monthLabel} />
            <FilterField label="Operator" any="Any operator" value={filters.operator} options={names(facets.operators)} onChange={set('operator')} />
          </>)}
        </div>
      </div>

      <div className="eb-browser-body">
        <div className="eb-results-head eb-browser-count">
          <span>{total == null ? (loading ? 'Loading…' : '') : <><b>{total}</b> holiday{total === 1 ? '' : 's'}</>}</span>
          {(qText || ['dest', 'type', 'airport', 'month', 'operator'].some((k) => filters[k]))
            ? <button type="button" className="eb-linkbtn" onClick={() => { setQText(''); setPage(1); setFilters(EMPTY); }}>Clear filters</button>
            : <span className="eb-results-sort">Sorted by best deal</span>}
        </div>
        {problem && <p className="eb-error">{problem}</p>}
        {data && (data.error || data.unavailable) && <p className="eb-error">{data.unavailable || data.error}</p>}
        {data && !data.error && !data.unavailable && !cards.length && (
          <div className="eb-empty"><b>Nothing matches those filters</b><p>Try a different destination or month, or clear your filters.</p></div>
        )}
        <div className="eb-browser-grid">
          {cards.map((c) => {
            const inEmail = added.has(c.key);
            const on = pickedKeys.has(c.key);
            return (
              <button key={c.key} type="button" className={"eb-card" + (on ? " is-picked" : "") + (inEmail ? " is-in" : "")}
                      aria-pressed={on} disabled={inEmail} onClick={() => toggle(c)}>
                <span className="eb-card-img">
                  {c.img && <img src={String(c.img).replace(/^http:\/\//, 'https://')} alt="" loading="lazy" onError={(e) => { e.currentTarget.style.display = 'none'; }} />}
                  {inEmail && <span className="eb-card-tag">In email</span>}
                  <span className="eb-card-check" aria-hidden="true">{(on || inEmail) && <Check />}</span>
                </span>
                <span className="eb-card-body">
                  <span className="eb-card-top"><b>{c.title}</b><span className="eb-card-price">{c.price}</span></span>
                  {c.deal && <span className="eb-card-deal">{c.deal}</span>}
                  {c.meta && <span className="eb-card-meta">{c.meta}</span>}
                  {c.from && <span className="eb-card-meta">{c.from}</span>}
                </span>
              </button>
            );
          })}
        </div>
        {isHolidays && data && !data.error && data.offers && data.offers.length < data.total && (
          <button type="button" className="eb-btn eb-btn--secondary eb-browser-more" disabled={loading} onClick={() => setPage((n) => n + 1)}>
            {loading ? 'Loading…' : 'Show more'}
          </button>
        )}
      </div>

      <div className="eb-browser-bar" role="status">
        <span>{picked.length ? <><b>{picked.length}</b> selected</> : 'Tick holidays to add them'}</span>
        {picked.length > 0 && <button type="button" className="eb-linkbtn eb-linkbtn--light" onClick={() => setPicked([])} disabled={adding}>Clear</button>}
        <button type="button" className="eb-btn eb-btn--primary" disabled={!picked.length || adding} onClick={addAll}>
          {adding ? 'Adding…' : picked.length ? `Add ${picked.length} to email` : 'Add to email'}
        </button>
      </div>
    </div>
  );
}

window.OfferBrowser = OfferBrowser;
