// The Atlas (/destinations) + destination chapters (/destinations/{slug}).
// Typographic index — no card grids (PRD §7). Chapters reuse the feature entry.
const { useMemo: useMemoDs } = React;

function destProperties(d) {
  return window.PROPERTIES
    .filter(p => p.destination === d.name)
    .sort((a, b) => a.rank - b.rank);
}

function AtlasPage() {
  const groups = useMemoDs(() => {
    const byRegion = new Map();
    window.DESTINATIONS.forEach(d => {
      const key = destProperties(d)[0]?.region || d.region;
      if (!byRegion.has(key)) byRegion.set(key, []);
      byRegion.get(key).push(d);
    });
    return [...byRegion.entries()].sort((a, b) => a[0].localeCompare(b[0]));
  }, []);

  return (
    <div data-screen-label="05 The Atlas">
      <ChapterOpener eyebrow={`${window.DESTINATIONS.length} destinations · ${window.EDITION} Edition`} title="The Atlas.">
        <p className="prose" style={{ margin: 0, fontSize: 19 }}>
          Every destination we cover, and every hotel we've slept in when we
          got there. Chapters are ranked internally; the numbers refer to the
          global 100.
        </p>
      </ChapterOpener>

      <section className="container" style={{ paddingTop: 72 }}>
        {groups.map(([region, dests]) => (
          <div key={region} style={{ marginBottom: 72 }}>
            <Eyebrow accent>{region}</Eyebrow>
            <div style={{ borderTop: '1px solid var(--ink)', marginTop: 20 }}>
              {dests.map(d => {
                const props = destProperties(d);
                const best = props[0];
                return (
                  <a key={d.id} href={`#/destinations/${d.id}`} className="atlas-row">
                    <span style={{ fontFamily: 'var(--display)', fontSize: 26 }}>{d.name}</span>
                    <span className="caption atlas-lede" style={{ fontFamily: 'var(--body)', fontStyle: 'italic', fontSize: 14.5 }}>
                      {best ? `Led by ${best.name}${window.isRanked(best) ? ` — № ${best.rank}` : ''}` : '—'}
                    </span>
                    <span className="caption num" style={{ textAlign: 'right' }}>{props.length || d.count} reviewed</span>
                    <span aria-hidden="true" style={{ color: 'var(--folio)' }}>→</span>
                  </a>
                );
              })}
            </div>
          </div>
        ))}
      </section>
    </div>
  );
}

function DestinationChapter({ destId }) {
  const d = window.DESTINATIONS.find(x => x.id === destId) || window.DESTINATIONS[0];
  const props = destProperties(d);
  const region = props[0]?.region || d.region;
  const siblings = window.DESTINATIONS.filter(x => x.id !== d.id && (destProperties(x)[0]?.region || x.region) === region);

  return (
    <div data-screen-label={`05 Chapter — ${d.name}`}>
      {/* Chapter-opener spread */}
      <header style={{ height: '78vh', minHeight: 560, position: 'relative', color: 'var(--paper)' }}>
        <div className="plate-img plate-grain" style={{ position: 'absolute', inset: 0 }}>
          <div className="slow-zoom" style={{ position: 'absolute', inset: 0, background: d.tint }}>
            {props[0]?.image && (
              <img src={props[0].image} alt="" aria-hidden="true"
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
                onError={e => { e.currentTarget.style.display = 'none'; }} />
            )}
          </div>
        </div>
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(10,10,12,0.36) 0%, transparent 40%, rgba(10,10,12,0.6) 100%)' }} />
        <div className="container" style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', paddingBottom: 64 }}>
          <div className="eyebrow" style={{ color: 'var(--paper-on-plate)' }}>Chapter · {region}</div>
          <h1 className="display-xl" style={{ margin: '18px 0 0', color: 'var(--paper)' }}>{d.name}</h1>
        </div>
      </header>
      <div className="container photo-caption caption" style={{ paddingTop: 10 }}>
        <span>{props[0] ? `${props[0].name} · ` : ''}{d.name}, {region}</span>
        <span className="credit" style={{ opacity: 0.7 }}>{props[0]?.image ? 'Courtesy of the property' : 'Imagery pending'}</span>
      </div>

      <div className="container-text" style={{ paddingTop: 80 }}>
        <p className="prose dropcap" style={{ fontSize: 19 }}>
          {props.length === 1 ? 'One property carries' : `${['', '', 'Two', 'Three', 'Four', 'Five'][props.length] || props.length} properties carry`} this
          chapter, and the order below is the order we would book them.
          {' '}{d.name} rewards the traveler who chooses lodging as carefully as
          the season: the gap between the right address and the nearly-right
          one here is the gap between being somewhere and merely staying
          somewhere. Scores refer to the global hundred; the ranks are citable.
        </p>
      </div>

      <section className="container" style={{ paddingTop: 24 }}>
        {props.map((p, i) => <FeatureEntry key={p.id} p={p} flip={i % 2 === 1} />)}
        {props.length === 0 && (
          <p className="prose" style={{ padding: '64px 0' }}>Reviews for this chapter publish with the next edition.</p>
        )}
      </section>

      {/* Elsewhere in region */}
      {siblings.length > 0 && (
        <section className="container" style={{ paddingTop: 88 }}>
          <Eyebrow accent>Elsewhere in {region}</Eyebrow>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 24 }}>
            {siblings.map(s => (
              <a key={s.id} href={`#/destinations/${s.id}`} className="filter-chip">{s.name}</a>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { AtlasPage, DestinationChapter });
