const { Button, Tag, Select, Pagination, Skeleton, DestinationCard, PackageCard, TripSearch, Breadcrumbs, Icon, Badge } = window.VE;

const STYLES = ['Beach', 'Mountains', 'Culture', 'Honeymoon', 'Family', 'Luxury'];

function DestinationListingScreen({ onOpen, search, onSearchChange, onSearchSubmit, isMobile }) {
  const [active, setActive] = React.useState([]);
  const [sort, setSort] = React.useState('recommended');
  const [page, setPage] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const D = window.VE_DATA;

  const toggle = (s) => {
    setActive((prev) => (prev.includes(s) ? prev.filter((x) => x !== s) : prev.concat(s)));
    setLoading(true);
    window.setTimeout(() => setLoading(false), 450);
  };

  let list = D.destinations.filter((d) => !active.length || active.some((s) => d.style.includes(s)));
  if (sort === 'price-low') list = list.slice().sort((a, b) => a.priceFrom - b.priceFrom);
  if (sort === 'price-high') list = list.slice().sort((a, b) => b.priceFrom - a.priceFrom);

  return (
    <main>
      <div style={{ borderBottom: '1px solid var(--color-hairline-soft)', background: 'var(--color-canvas)' }}>
        <div className="ve-container" style={{ paddingBlock: 'var(--space-lg)', display: 'flex', flexDirection: 'column', gap: 'var(--space-lg)' }}>
          <Breadcrumbs items={[{ label: 'Home', href: '#' }, { label: 'Destinations' }]} />
          <div style={{ maxWidth: 960 }}>
            {isMobile
              ? <TripSearch compact destination={search.destination} onExpand={onSearchSubmit} />
              : <TripSearch destination={search.destination} dates={search.dates} travellers={search.travellers}
                  activeField={search.activeField} onFieldFocus={(field) => onSearchChange({ ...search, activeField: field })}
                  onSubmit={onSearchSubmit} submitLabel="Search" />}
          </div>
        </div>
      </div>

      <div className="ve-container" style={{ paddingBlock: 'var(--space-xl)', display: 'flex', flexDirection: 'column', gap: 'var(--space-lg)' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-md)' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-sm)' }}>
            {STYLES.map((s) => <Tag key={s} selected={active.includes(s)} onClick={() => toggle(s)}>{s}</Tag>)}
            {active.length ? <Button variant="tertiary" size="sm" onClick={() => setActive([])}>Clear</Button> : null}
          </div>
          <div style={{ minWidth: 220 }}>
            <Select value={sort} onChange={(e) => setSort(e.target.value)}
              options={[{ value: 'recommended', label: 'Sort: Recommended' }, { value: 'price-low', label: 'Sort: Price, low to high' }, { value: 'price-high', label: 'Sort: Price, high to low' }]} />
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 'var(--space-md)' }}>
          <h1 className="ve-display-sm">{active.length ? active.join(' · ') + ' escapes' : 'All destinations'}</h1>
          <span className="ve-caption">{list.length} destinations · prices per person</span>
        </div>

        {loading ? (
          <div className="ve-grid ve-grid--4">{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => <Skeleton key={i} variant="card" />)}</div>
        ) : (
          <div className="ve-grid ve-grid--4">
            {list.map((d) => (
              <DestinationCard key={d.slug} image={vePhoto(d.photo, 800, 600)} alt={d.tagline + ' in ' + d.name}
                name={d.name} region={d.region} tagline={d.tagline} priceFrom={d.priceFrom} badge={d.badge} saveable
                onClick={(e) => { e.preventDefault(); onOpen('destination', d); }} />
            ))}
          </div>
        )}

        <hr className="ve-divider" style={{ marginBlock: 'var(--space-lg)' }} />

        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 'var(--space-md)' }}>
          <h2 className="ve-heading-lg">Packages in these destinations</h2>
          <Badge tone="outline" icon="Sun">Seasonal picks</Badge>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-base)' }}>
          {D.packages.slice(0, 3).map((p) => (
            <div key={p.slug} onClick={() => onOpen('package', p)} style={{ cursor: 'pointer' }}>
              <PackageCard layout="horizontal" image={vePhoto(p.photo, 700, 520)} alt={p.title} title={p.title}
                destination={p.destination} nights={p.nights} days={p.days} price={p.price} rating={p.rating}
                reviewCount={p.reviews} inclusions={p.inclusions} />
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 'var(--space-2xl)' }}>
          <Pagination page={page} pageCount={4} onChange={setPage} />
        </div>
      </div>
    </main>
  );
}
Object.assign(window, { DestinationListingScreen });
