/* BookingFlow.jsx — Unified booking + search/filter flow */

function BookingFlow() {
  const today = new Date().toISOString().slice(0, 10);
  const inThreeDays = new Date(Date.now() + 3 * 86400000).toISOString().slice(0, 10);
  const inWeek = new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 10);

  // Parse URL params for pre-filled values (e.g. from homepage search)
  const params = new URLSearchParams(window.location.search);

  const [filters, setFilters] = React.useState({
    checkIn:  params.get('checkIn')  || inThreeDays,
    checkOut: params.get('checkOut') || inWeek,
    guests:   parseInt(params.get('guests') || '2'),
    bedrooms: params.get('bedrooms') || 'any',
    type:     params.get('type')     || 'all',
    neighborhood: params.get('neighborhood') || 'all',
    minPrice: parseInt(params.get('minPrice') || '0'),
    maxPrice: parseInt(params.get('maxPrice') || '5000'),
    amenities: [],
    sort:     'recommended',
  });

  const [selected, setSelected] = React.useState(null);
  const [showMobileFilters, setShowMobileFilters] = React.useState(false);

  // Calculate nights
  const nights = Math.max(1, Math.ceil((new Date(filters.checkOut) - new Date(filters.checkIn)) / 86400000));

  // Source properties — the LIVE catalog (real Hospitable villas) via NovusCatalog,
  // with a graceful fallback. Re-renders when the live catalog arrives.
  const [allProperties, setAllProperties] = React.useState(() => {
    if (typeof window === 'undefined') return [];
    if (window.NovusCatalog) return window.NovusCatalog.getProperties();
    return window.NOVUS_PROPERTIES || [];
  });

  React.useEffect(() => {
    if (window.NovusCatalog && window.NovusCatalog.load) {
      window.NovusCatalog.load().then((list) => { if (list && list.length) setAllProperties(list); });
    }
    const onCatalog = (e) => { const l = e.detail && e.detail.properties; if (l && l.length) setAllProperties(l); };
    window.addEventListener('novus-catalog', onCatalog);
    return () => window.removeEventListener('novus-catalog', onCatalog);
  }, []);

  // Lock body scroll while the mobile filter drawer is open (Airbnb behavior).
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    if (showMobileFilters) document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [showMobileFilters]);

  // Keep in sync with locally-edited catalog ONLY in demo mode; in live mode the
  // catalog comes from NovusCatalog (above) and must not be overwritten by the
  // empty live-mode HostData store.
  React.useEffect(() => {
    const isLive = window.NovusCatalog && window.NovusCatalog.isLive && window.NovusCatalog.isLive();
    if (isLive) return;
    const refresh = () => {
      if (window.HostData && window.HostData.getProperties) setAllProperties(window.HostData.getProperties());
    };
    const onStorage = (e) => { if (e.key === 'novus_properties') refresh(); };
    const onLocal = (e) => { if (e.detail?.key === 'novus_properties') refresh(); };
    window.addEventListener('storage', onStorage);
    window.addEventListener('host-data-change', onLocal);
    return () => {
      window.removeEventListener('storage', onStorage);
      window.removeEventListener('host-data-change', onLocal);
    };
  }, []);

  // Apply filters
  const filtered = React.useMemo(() => {
    return allProperties.filter(p => {
      // Type
      if (filters.type !== 'all' && p.kind !== filters.type) return false;
      // Neighborhood
      if (filters.neighborhood !== 'all' && p.neighborhood !== filters.neighborhood) return false;
      // Bedrooms
      if (filters.bedrooms !== 'any') {
        const bedNum = parseInt(filters.bedrooms);
        const propBeds = parseInt((p.facts || []).find(f => /bedroom/i.test(f))?.match(/\d+/)?.[0] || 0);
        if (propBeds < bedNum) return false;
      }
      // Price range
      if (p.rate < filters.minPrice || p.rate > filters.maxPrice) return false;
      // Guests capacity
      const sleepsMatch = (p.facts || []).find(f => /sleep/i.test(f));
      const capacity = parseInt(sleepsMatch?.match(/\d+/)?.[0] || '10');
      if (filters.guests > capacity) return false;
      return true;
    });
  }, [allProperties, filters]);

  const sorted = React.useMemo(() => {
    const arr = [...filtered];
    switch (filters.sort) {
      case 'price-asc':  return arr.sort((a, b) => a.rate - b.rate);
      case 'price-desc': return arr.sort((a, b) => b.rate - a.rate);
      case 'rating':     return arr.sort((a, b) => (b.rating || 0) - (a.rating || 0));
      default:           return arr;
    }
  }, [filtered, filters.sort]);

  // Get unique neighborhoods
  const neighborhoods = ['all', ...new Set(allProperties.map(p => p.neighborhood).filter(Boolean))];

  function updateFilter(key, value) {
    setFilters(f => ({ ...f, [key]: value }));
  }

  function resetFilters() {
    setFilters({
      checkIn: inThreeDays, checkOut: inWeek, guests: 2,
      bedrooms: 'any', type: 'all', neighborhood: 'all',
      minPrice: 0, maxPrice: 5000, amenities: [], sort: 'recommended',
    });
  }

  return (
    <>
      <style>{`
        .booking-layout {
          display: grid;
          grid-template-columns: 1fr;
          gap: 24px;
          padding: 24px 0 80px;
        }
        @media (min-width: 1024px) {
          .booking-layout {
            grid-template-columns: 300px 1fr;
            gap: 32px;
            padding: 32px 0 100px;
          }
        }
        .filter-sidebar {
          background: #fff;
          border: 1px solid var(--line);
          border-radius: 18px;
          padding: 24px;
          height: fit-content;
          position: sticky;
          top: 88px;
        }
        @media (max-width: 1023px) {
          .filter-sidebar {
            position: fixed;
            inset: 0;
            z-index: 100;
            border-radius: 0;
            border: none;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            /* room so the sticky "Show results" button clears the browser chrome */
            padding-bottom: calc(40px + env(safe-area-inset-bottom));
            transform: translateX(100%);
            transition: transform 320ms var(--ease-novus);
          }
          .filter-sidebar.is-open {
            transform: translateX(0);
          }
        }
        .results-grid {
          display: grid;
          grid-template-columns: 1fr;
          gap: 20px;
        }
        @media (min-width: 640px) {
          .results-grid { grid-template-columns: repeat(2, 1fr); gap: 16px; }
        }
        @media (min-width: 1024px) {
          .results-grid { grid-template-columns: repeat(2, 1fr); gap: 24px; }
        }
        @media (min-width: 1280px) {
          .results-grid { grid-template-columns: repeat(3, 1fr); }
        }
        .filter-row {
          display: flex;
          flex-direction: column;
          gap: 6px;
          margin-bottom: 18px;
        }
        .filter-row label {
          font-size: 10px; font-weight: 600;
          letter-spacing: 0.14em; text-transform: uppercase;
          color: var(--ink-500);
        }
        .filter-row input, .filter-row select {
          padding: 11px 14px;
          border: 1px solid var(--line);
          border-radius: 10px;
          font-size: 14px;
          background: #fff;
          font-family: inherit;
          color: var(--navy-900);
        }
        .filter-row input:focus, .filter-row select:focus {
          outline: none;
          border-color: var(--navy-500);
        }
        .filter-divider {
          height: 1px; background: var(--line); margin: 24px -24px;
        }
        .price-range {
          display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
        }
      `}</style>

      {/* Booking Hero */}
      <section style={{
        background: 'linear-gradient(135deg, var(--navy-900) 0%, var(--navy-800) 60%, var(--navy-700) 100%)',
        color: '#fff',
        padding: '56px 0 40px',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -100, right: -100, width: 360, height: 360,
          background: 'var(--sunset-gradient-warm)',
          opacity: 0.18, filter: 'blur(80px)', borderRadius: '50%',
          pointerEvents: 'none',
        }} />
        <div className="container" style={{ position: 'relative' }}>
          <div className="fade-up">
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <span className="sun-bullet" style={{ width: 12, height: 12 }} />
              <span style={{
                fontSize: 11, fontWeight: 600, letterSpacing: '0.2em',
                textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)',
              }}>Find your stay</span>
            </div>
            <h1 style={{
              fontFamily: 'var(--font-display)', fontWeight: 400,
              fontSize: 'clamp(32px, 4.5vw, 56px)', color: '#fff',
              margin: '0 0 12px', letterSpacing: '-0.015em', lineHeight: 1.1,
              maxWidth: 720,
            }}>
              Browse <em style={{ fontStyle: 'italic', color: 'var(--sun-amber)' }}>eight</em> luxury residences
            </h1>
            <p style={{
              color: 'rgba(255,255,255,0.7)', fontSize: 'clamp(14px, 1.4vw, 16px)',
              maxWidth: 560, lineHeight: 1.6, margin: 0,
            }}>
              {sorted.length} {sorted.length === 1 ? 'property' : 'properties'} available · {nights} night{nights !== 1 ? 's' : ''} · {filters.guests} guest{filters.guests !== 1 ? 's' : ''}
            </p>
          </div>
        </div>
      </section>

      {/* Booking Layout */}
      <div className="container">
        {/* Mobile filter toggle */}
        <div className="hide-desktop" style={{ paddingTop: 16 }}>
          <button onClick={() => setShowMobileFilters(true)} className="btn btn-secondary" style={{
            width: '100%', justifyContent: 'space-between',
          }}>
            <span>Filters</span>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <line x1="4" y1="21" x2="4" y2="14"></line>
              <line x1="4" y1="10" x2="4" y2="3"></line>
              <line x1="12" y1="21" x2="12" y2="12"></line>
              <line x1="12" y1="8" x2="12" y2="3"></line>
              <line x1="20" y1="21" x2="20" y2="16"></line>
              <line x1="20" y1="12" x2="20" y2="3"></line>
              <line x1="1" y1="14" x2="7" y2="14"></line>
              <line x1="9" y1="8" x2="15" y2="8"></line>
              <line x1="17" y1="16" x2="23" y2="16"></line>
            </svg>
          </button>
        </div>

        <div className="booking-layout">
          {/* Filter Sidebar */}
          <aside className={`filter-sidebar ${showMobileFilters ? 'is-open' : ''}`}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
              <h3 style={{
                fontFamily: 'var(--font-display)', fontWeight: 500,
                fontSize: 22, color: 'var(--navy-900)', margin: 0,
                letterSpacing: '-0.01em',
              }}>Filters</h3>
              <button onClick={() => setShowMobileFilters(false)}
                className="hide-desktop"
                style={{ background: 'transparent', border: 0, padding: 8, cursor: 'pointer' }}
              >
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>

            {/* Dates */}
            <div className="filter-row">
              <label>Check-in</label>
              <input type="date" value={filters.checkIn} min={today}
                onChange={e => updateFilter('checkIn', e.target.value)} />
            </div>
            <div className="filter-row">
              <label>Check-out</label>
              <input type="date" value={filters.checkOut} min={filters.checkIn}
                onChange={e => updateFilter('checkOut', e.target.value)} />
            </div>

            <div className="filter-row">
              <label>Guests · {filters.guests}</label>
              <input type="range" min="1" max="14" value={filters.guests}
                onChange={e => updateFilter('guests', parseInt(e.target.value))}
                style={{ accentColor: 'var(--sun-coral)', cursor: 'pointer' }}
              />
            </div>

            <div className="filter-divider"></div>

            {/* Type */}
            <div className="filter-row">
              <label>Property type</label>
              <select value={filters.type} onChange={e => updateFilter('type', e.target.value)}>
                <option value="all">All types</option>
                <option value="villa">Villas</option>
                <option value="luxury-rental">Luxury apartments</option>
              </select>
            </div>

            {/* Neighborhood */}
            <div className="filter-row">
              <label>Neighborhood</label>
              <select value={filters.neighborhood} onChange={e => updateFilter('neighborhood', e.target.value)}>
                {neighborhoods.map(n => (
                  <option key={n} value={n}>{n === 'all' ? 'All Miami' : n}</option>
                ))}
              </select>
            </div>

            {/* Bedrooms */}
            <div className="filter-row">
              <label>Bedrooms</label>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {['any', '1', '2', '3', '4', '5+'].map(b => (
                  <button key={b}
                    onClick={() => updateFilter('bedrooms', b === '5+' ? '5' : b)}
                    style={{
                      padding: '8px 14px',
                      borderRadius: 999,
                      border: '1px solid var(--line)',
                      background: filters.bedrooms === b || (b === '5+' && filters.bedrooms === '5')
                        ? 'var(--navy-900)' : '#fff',
                      color: filters.bedrooms === b || (b === '5+' && filters.bedrooms === '5')
                        ? '#fff' : 'var(--ink-700)',
                      fontSize: 12,
                      fontWeight: 500,
                      cursor: 'pointer',
                      transition: 'all 200ms var(--ease-novus)',
                    }}>{b}</button>
                ))}
              </div>
            </div>

            <div className="filter-divider"></div>

            {/* Price Range */}
            <div className="filter-row">
              <label>Price per night · ${filters.minPrice} – ${filters.maxPrice}</label>
              <div className="price-range">
                <input type="number" value={filters.minPrice}
                  onChange={e => updateFilter('minPrice', parseInt(e.target.value) || 0)}
                  placeholder="Min" min="0" />
                <input type="number" value={filters.maxPrice}
                  onChange={e => updateFilter('maxPrice', parseInt(e.target.value) || 5000)}
                  placeholder="Max" max="5000" />
              </div>
            </div>

            <button onClick={resetFilters}
              style={{
                marginTop: 12, width: '100%', padding: '12px',
                background: 'transparent', border: '1px solid var(--line)',
                borderRadius: 10, fontSize: 13, color: 'var(--ink-700)',
                cursor: 'pointer', fontFamily: 'inherit',
                transition: 'all 200ms var(--ease-novus)',
              }}
              onMouseEnter={e => { e.target.style.borderColor = 'var(--navy-500)'; e.target.style.color = 'var(--navy-700)'; }}
              onMouseLeave={e => { e.target.style.borderColor = 'var(--line)'; e.target.style.color = 'var(--ink-700)'; }}
            >Reset filters</button>

            <button onClick={() => setShowMobileFilters(false)}
              className="hide-desktop btn btn-primary"
              style={{ marginTop: 12, width: '100%', justifyContent: 'center' }}
            >
              Show {sorted.length} results →
            </button>
          </aside>

          {/* Results */}
          <main>
            {/* Sort + count */}
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: 20,
              flexWrap: 'wrap',
              gap: 12,
            }}>
              <div style={{ fontSize: 14, color: 'var(--ink-700)' }}>
                <strong style={{ color: 'var(--navy-900)' }}>{sorted.length}</strong> properties found
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, color: 'var(--ink-500)', fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Sort:</span>
                <select value={filters.sort} onChange={e => updateFilter('sort', e.target.value)}
                  style={{
                    padding: '8px 12px', border: '1px solid var(--line)', borderRadius: 8,
                    fontSize: 13, background: '#fff', fontFamily: 'inherit',
                    color: 'var(--navy-900)', cursor: 'pointer',
                  }}>
                  <option value="recommended">Recommended</option>
                  <option value="price-asc">Price: low to high</option>
                  <option value="price-desc">Price: high to low</option>
                  <option value="rating">Highest rated</option>
                </select>
              </div>
            </div>

            {sorted.length === 0 ? (
              <div style={{
                background: '#fff', border: '1px solid var(--line)', borderRadius: 18,
                padding: '60px 40px', textAlign: 'center',
              }}>
                <h3 style={{
                  fontFamily: 'var(--font-display)', fontWeight: 400,
                  fontSize: 28, color: 'var(--navy-900)', margin: '0 0 12px',
                }}>No properties match your filters.</h3>
                <p style={{ color: 'var(--ink-500)', margin: '0 0 24px', lineHeight: 1.6 }}>
                  Try adjusting your dates, guest count, or price range.
                </p>
                <button onClick={resetFilters} className="btn btn-primary">
                  Reset all filters →
                </button>
              </div>
            ) : (
              <div className="results-grid">
                {sorted.map((p, i) => (
                  <div key={p.id} className={`fade-up delay-${Math.min(i + 1, 6)}`}>
                    <BookingResultCard p={p} nights={nights}
                      onSelect={() => {
                        const url = new URL(`property-${p.id}.html`, window.location.href);
                        url.searchParams.set('checkIn', filters.checkIn);
                        url.searchParams.set('checkOut', filters.checkOut);
                        url.searchParams.set('guests', filters.guests);
                        window.location.href = url.toString();
                      }}
                    />
                  </div>
                ))}
              </div>
            )}
          </main>
        </div>
      </div>
    </>
  );
}

/* Card component for booking results */
function BookingResultCard({ p, nights, onSelect }) {
  const total = (p.rate || 0) * nights;
  return (
    <div className="hover-lift hover-zoom" style={{
      background: '#fff',
      border: '1px solid var(--line)',
      borderRadius: 18,
      overflow: 'hidden',
      cursor: 'pointer',
      transition: 'all 320ms var(--ease-novus)',
    }} onClick={onSelect}>
      <div style={{ position: 'relative', aspectRatio: '4/3', overflow: 'hidden', background: 'var(--sand-100)' }}>
        <img src={p.photo} alt={p.name}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        {p.badge && (
          <div style={{
            position: 'absolute', top: 14, left: 14,
            padding: '5px 11px',
            background: 'rgba(255,255,255,0.94)',
            color: 'var(--navy-900)',
            borderRadius: 999, fontSize: 10, fontWeight: 600,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            backdropFilter: 'blur(8px)',
          }}>{p.badge}</div>
        )}
        {p.rating && (
          <div style={{
            position: 'absolute', top: 14, right: 14,
            padding: '5px 10px',
            background: 'rgba(10,31,51,0.78)',
            color: '#fff',
            borderRadius: 999, fontSize: 12, fontWeight: 600,
            backdropFilter: 'blur(8px)',
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>
            <span style={{ color: 'var(--sun-amber)' }}>★</span> {p.rating}
          </div>
        )}
      </div>
      <div style={{ padding: '18px 20px 20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 6 }}>
          <h3 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400,
            fontSize: 22, color: 'var(--navy-900)',
            margin: 0, letterSpacing: '-0.01em', lineHeight: 1.15,
          }}>{p.name}</h3>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-500)', marginBottom: 12 }}>
          {p.neighborhood}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
          {(p.facts || []).slice(0, 3).map(f => (
            <span key={f} style={{
              padding: '3px 9px', fontSize: 11,
              background: 'var(--sand-100)', color: 'var(--ink-700)',
              borderRadius: 999, fontWeight: 500,
            }}>{f}</span>
          ))}
        </div>
        <div style={{
          paddingTop: 14, borderTop: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 12,
        }}>
          <div>
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 500,
              fontSize: 22, color: 'var(--navy-900)', letterSpacing: '-0.01em',
            }}>${p.rate}<span style={{ fontSize: 12, color: 'var(--ink-500)', fontWeight: 400, fontFamily: 'var(--font-text)' }}> / night</span></div>
            <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 2 }}>
              ${total.toLocaleString()} for {nights} nights
            </div>
          </div>
          <span style={{
            padding: '8px 14px', background: 'var(--navy-900)', color: '#fff',
            borderRadius: 999, fontSize: 12, fontWeight: 500,
          }}>View →</span>
        </div>
      </div>
    </div>
  );
}

window.BookingFlow = BookingFlow;
window.BookingResultCard = BookingResultCard;
