// Listing overview — the prototype's right-hand panel, opened by clicking a
// listing in any view (Agency Portal Prototype.dc.html, lines 379-433).
//
// This was missing from the first cut of BOO-644 entirely: clicking a row did
// nothing. It is the design's only route to a venue's detail, and the only place
// the whole product's time list is shown rather than a truncated chip rail.
//
// Facts panel: the prototype shows Capacity / Minimum spend / Address. Bookable's
// /venues payload carries none of those (see transformVenues) — so rather than
// invent them, this shows what the API does return: operator, minimum party size
// from the product's weekly rules, and the venue's area + postcode.

function ListingDrawer({ venue, query, itineraryMode, onBook, onClose }) {
  const products = venue ? (venue.products || []).filter(Boolean) : [];
  const [sel, setSel] = React.useState(null);
  React.useEffect(() => { setSel(null); }, [venue && venue.id]);

  React.useEffect(() => {
    if (!venue) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [venue, onClose]);

  // Lock the page behind the panel so wheel events on the scrim don't scroll the
  // listing underneath.
  React.useEffect(() => {
    if (!venue) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [venue]);

  // Hooks must run unconditionally, so the availability fan-out is set up with a
  // null venue too and simply returns nothing.
  const initial = (query.productTypes || []).find(p => products.includes(p)) || products[0];
  const productId = sel || initial;
  const minParty = (() => {
    const rp = (venue && venue.rawProducts || []).find(x => x.portalProduct === productId);
    const n = rp && Number(rp.minPartySize);
    return n > 0 ? n : null;
  })();
  const belowMin = minParty && query.guests < minParty;
  const byProduct = useAllProductsAvailability(
    venue, belowMin ? [] : (productId ? [productId] : []), query.date, query.guests, !!venue && query.searched);
  const slots = byProduct[productId];
  const loading = venue && query.searched && !belowMin && (slots === null || slots === undefined);

  if (!venue) return null;

  const op = operatorById(venue.operator);
  const product = productById(productId) || { name: (venue.productNames && venue.productNames[productId]) || productId };
  const dateLabel = new Date(query.date + 'T00:00:00').toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
  const photo = venue.photos && venue.photos[0];
  const facts = [
    op && ['Operator', op.name],
    ['Minimum party', minParty ? minParty + (minParty === 1 ? ' guest' : ' guests') : 'None'],
    ['Where', [ppArea(venue.area), venue.city, venue.postCode].filter(Boolean).join(' · ') || '—'],
  ].filter(Boolean);
  const first = (slots || [])[0];

  return (
    <React.Fragment>
      <div className="pp-drawer-scrim" onClick={onClose}/>
      <aside className="pp-listing-drawer" role="dialog" aria-modal="true" aria-label={venue.name}>
        <div className="pp-listing-drawer-head">
          <span className="pp-drawer-eyebrow">Listing overview</span>
          <button className="pp-icon-btn" onClick={onClose} aria-label="Close"><IconClose size={14}/></button>
        </div>

        <div className="pp-listing-drawer-body">
          <h2 className="pp-listing-drawer-name">{venue.name}</h2>
          <div className="pp-listing-drawer-sub">
            {[venue.city, ppArea(venue.area)].filter(Boolean).join(' · ')}
          </div>

          <div className={"pp-listing-drawer-hero pp-cover--" + (venue.tone || 'sage')}
               style={photo ? { backgroundImage: 'url("' + photo + '")' } : undefined}>
            {!photo && <span className="pp-listing-drawer-mono">{monogramOf(venue.name)}</span>}
          </div>

          {venue.description && <p className="pp-listing-drawer-desc">{stripHtml(venue.description)}</p>}

          <div className="pp-listing-drawer-block">
            <div className="pp-listing-drawer-label">Product</div>
            <div className="pp-prod-switch">
              {products.map(pid => {
                const PG = glyphFor(pid);
                const p = productById(pid) || { name: (venue.productNames && venue.productNames[pid]) || pid };
                return (
                  <button key={pid} type="button"
                          className={"pp-prod-tab" + (pid === productId ? " is-active" : "")}
                          onClick={() => setSel(pid)}>
                    <PG size={12}/><span>{p.name}</span>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="pp-listing-drawer-block">
            <div className="pp-listing-drawer-label">
              {query.searched ? 'Available times on ' + dateLabel + ' · ' + query.guests + (query.guests === 1 ? ' guest' : ' guests') : 'Available times'}
            </div>
            {!query.searched ? (
              <div className="pp-listing-drawer-idle">Set a date and guests, then search to load live times.</div>
            ) : belowMin ? (
              <div className="pp-listing-drawer-idle">Minimum {minParty} guests for {product.name}.</div>
            ) : loading ? (
              <div className="pp-time-chips">
                {Array.from({ length: 6 }).map((_, i) => <span key={i} className="pp-time-chip-skel pp-shimmer" aria-hidden="true"/>)}
              </div>
            ) : (slots || []).length === 0 ? (
              <div className="pp-listing-drawer-idle">No times for {product.name} on {dateLabel} — try another date.</div>
            ) : (
              // Every time, not the truncated rail the row shows.
              <div className="pp-time-chips">
                {slots.map(s => (
                  <button key={s.time + '-' + (s.type || 'book')} type="button"
                          className={"pp-time-chip" + (s.type === 'request' ? " pp-time-chip--request" : "")}
                          title={(s.type === 'request' ? 'Enquiry — operator must approve.' : 'Instant confirmation.') + (s.price ? ' £' + s.price + ' per person' : '')}
                          onClick={() => onBook({ venueId: venue.id, productId, date: query.date, time: s.time, guests: query.guests, price: s.price, type: s.type, compositeId: s.compositeId, preOrderItems: s.preOrderItems })}>
                    {s.time}
                  </button>
                ))}
              </div>
            )}
          </div>

          <div className="pp-listing-facts">
            {facts.map(([k, val]) => (
              <div className="pp-listing-fact" key={k}>
                <span>{k}</span><strong>{val}</strong>
              </div>
            ))}
          </div>
        </div>

        {query.searched && first && (
          <footer className="pp-listing-drawer-foot">
            <button className="pp-btn pp-btn--primary"
                    onClick={() => onBook({ venueId: venue.id, productId, date: query.date, time: first.time, guests: query.guests, price: first.price, type: first.type, compositeId: first.compositeId, preOrderItems: first.preOrderItems })}>
              {itineraryMode ? 'Add ' + first.time + ' to itinerary' : 'Book ' + first.time}
            </button>
          </footer>
        )}
      </aside>
    </React.Fragment>
  );
}

Object.assign(window, { ListingDrawer });
