/* eslint-disable */
/* cityform — The Collection (browse) — v1 density · v3 brand */

function AtlasPage({ go, t }) {
  const [view, setView] = React.useState('grid');
  const [type, setType] = React.useState('All');
  const [region, setRegion] = React.useState('All Regions');
  const [sort, setSort] = React.useState('curated');
  const [density, setDensity] = React.useState(t.density || 'standard');

  React.useEffect(() => setDensity(t.density || 'standard'), [t.density]);

  let items = window.CATALOG.filter(it =>
    (type === 'All' || it.type === type) &&
    (region === 'All Regions' || it.region === region));
  if (sort === 'name') items = [...items].sort((a,b) => a.name.localeCompare(b.name));
  if (sort === 'coords') items = [...items].sort((a,b) => a.coords.lat - b.coords.lat);

  return (
    <div data-density={density}>
      {/* Header */}
      <section style={{ background:'var(--mist)', borderBottom:'1px solid var(--line)' }}>
        <div className="container" style={{ paddingTop:72, paddingBottom:48 }}>
          <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
            <div>
              <div className="label">The catalogue</div>
              <h1 className="h1" style={{ fontSize:96, marginTop:14 }}>The Collection.</h1>
              <p className="body" style={{ fontSize:17, color:'var(--stone)', marginTop:18, maxWidth:540 }}>
                Twelve cities locked into the system, plus an archive of commissions. Each is a 9 cm crop centred on a chosen point, rendered at 1:11000.
              </p>
            </div>
            <div style={{ textAlign:'right' }}>
              <div className="label">Showing</div>
              <div style={{ fontSize:32, fontWeight:600, letterSpacing:'-0.01em', fontVariantNumeric:'tabular-nums', marginTop:6 }}>{items.length} / {window.CATALOG.length}</div>
              <div className="caption" style={{ marginTop:4, fontSize:10 }}>UPDATED 14 MAY 2026</div>
            </div>
          </div>
        </div>
      </section>

      {/* Collections strip */}
      <section style={{ background:'var(--bone)', borderBottom:'1px solid var(--line)' }}>
        <div className="container" style={{ paddingTop:32, paddingBottom:32 }}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:18 }}>
            {window.COLLECTIONS.map((c) => (
              <button key={c.id}
                onClick={() => {
                  if (c.id === 'cities') setType('City');
                  else if (c.id === 'districts') setType('District');
                  else if (c.id === 'topography') setType('Topography');
                  else if (c.id === 'coast') setType('Coast');
                  else if (c.id === 'landmarks') setType('Landmark');
                }}
                style={{
                  border:'1px solid var(--line)',
                  padding:'18px 18px', textAlign:'left',
                  background:'var(--mist)', transition:'border-color .15s',
                }}
                onMouseEnter={e => e.currentTarget.style.borderColor='var(--ink)'}
                onMouseLeave={e => e.currentTarget.style.borderColor='var(--line)'}
              >
                <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
                  <div className="h3" style={{ fontSize:20, fontWeight:600 }}>{c.name}</div>
                  <div style={{ fontSize:11, color:'var(--stone)', fontVariantNumeric:'tabular-nums', letterSpacing:'0.06em' }}>{String(c.n).padStart(2,'0')}</div>
                </div>
                <div className="body" style={{ fontSize:13, color:'var(--stone)', marginTop:8 }}>{c.blurb}</div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Filter bar */}
      <section style={{ background:'var(--mist)', borderBottom:'1px solid var(--line)', position:'sticky', top:72, zIndex:30 }}>
        <div className="container" style={{ display:'flex', alignItems:'center', gap:18, height:64, flexWrap:'wrap' }}>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {window.TYPES.map(typ => (
              <button key={typ} className={`chip ${type===typ ? 'active' : ''}`} onClick={() => setType(typ)}>{typ}</button>
            ))}
          </div>
          <div style={{ flex:1 }}/>
          <select value={region} onChange={e => setRegion(e.target.value)}
            style={{
              border:'1px solid var(--line)', background:'var(--bone)', padding:'8px 12px',
              fontFamily:'Inter, sans-serif', fontSize:12, color:'var(--ink)',
            }}>
            {window.REGIONS.map(r => <option key={r}>{r}</option>)}
          </select>
          <select value={sort} onChange={e => setSort(e.target.value)}
            style={{
              border:'1px solid var(--line)', background:'var(--bone)', padding:'8px 12px',
              fontFamily:'Inter, sans-serif', fontSize:12, color:'var(--ink)',
            }}>
            <option value="curated">Sort · Curated</option>
            <option value="name">Sort · A → Z</option>
            <option value="coords">Sort · South → North</option>
          </select>
          {/* density */}
          <div style={{ display:'flex', gap:0, border:'1px solid var(--line)', overflow:'hidden' }}>
            {[
              ['cozy', 'COZY'],
              ['standard', 'STD'],
              ['dense', 'DENSE'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setDensity(k)}
                style={{
                  padding:'8px 10px', fontSize:10, letterSpacing:'0.22em', fontWeight:500,
                  background: density === k ? 'var(--ink)' : 'transparent',
                  color: density === k ? 'var(--mist)' : 'var(--stone)',
                }}>{l}</button>
            ))}
          </div>
          {/* view */}
          <div style={{ display:'flex', gap:0, border:'1px solid var(--line)', overflow:'hidden' }}>
            {[
              ['grid',    Icon.grid, 'Photo'],
              ['sticker', <span style={{ width:14, height:14, display:'flex', alignItems:'center', justifyContent:'center', border:'1.5px solid currentColor' }}><span style={{ width:5, height:5, background:'currentColor' }}/></span>, 'Marks'],
              ['list',    Icon.list, 'List'],
              ['map',     Icon.map, 'Map'],
            ].map(([k, ic, title]) => (
              <button key={k} onClick={() => setView(k)} title={title}
                style={{
                  padding:'10px', display:'flex',
                  background: view === k ? 'var(--ink)' : 'transparent',
                  color: view === k ? 'var(--mist)' : 'var(--stone)',
                }}>{ic}</button>
            ))}
          </div>
        </div>
      </section>

      {/* RESULTS */}
      <section style={{ background:'var(--mist)' }}>
        <div className="container" style={{ paddingTop:48, paddingBottom:96 }}>
          {view === 'grid' && (
            <div style={{
              display:'grid',
              gridTemplateColumns: density === 'dense' ? 'repeat(5, minmax(0, 1fr))' :
                                    density === 'cozy'  ? 'repeat(3, minmax(0, 1fr))' : 'repeat(4, minmax(0, 1fr))',
              gridAutoRows: '1fr',
              gap: density === 'dense' ? 14 : density === 'cozy' ? 40 : 24,
            }}>
              {items.map(item => (
                <ProductCard key={item.id} item={item} onClick={() => go('product', item.id)} density={density}/>
              ))}
            </div>
          )}

          {view === 'sticker' && (
            <div style={{
              display:'grid',
              gridTemplateColumns: density === 'cozy' ? 'repeat(3, 1fr)' : density === 'dense' ? 'repeat(6, 1fr)' : 'repeat(4, 1fr)',
              gap: density === 'cozy' ? 40 : density === 'dense' ? 16 : 28,
            }}>
              {items.map(item => (
                <button key={item.id} onClick={() => go('product', item.id)} style={{ textAlign:'left' }}>
                  {item.accent ? (
                    <CitySticker city={item} size={280}/>
                  ) : (
                    <div style={{ aspectRatio:'1/1', background:'var(--bone)', border:'1px dashed var(--line-strong)',
                      display:'flex', alignItems:'center', justifyContent:'center', padding:'14%', flexDirection:'column' }}>
                      <div className="h3" style={{ fontSize:20, fontWeight:600, textAlign:'center' }}>{item.name}</div>
                      <div className="label" style={{ marginTop:12, fontSize:9 }}>
                        {item.status === 'soon' ? 'AWAITING SIGNATURE' : 'COMMISSION'}
                      </div>
                    </div>
                  )}
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginTop:14 }}>
                    <span className="h3" style={{ fontSize:16, fontWeight:600 }}>{item.name}</span>
                    <span style={{ fontSize:12, color:'var(--stone)', fontVariantNumeric:'tabular-nums' }}>{item.price ? `£${item.price}` : '—'}</span>
                  </div>
                  {item.landmark && (
                    <div style={{ marginTop:4, display:'flex', alignItems:'center', gap:8 }}>
                      <span style={{ width:8, height:8, background:`var(--${item.accent})` }}/>
                      <span style={{ fontSize:10, color:'var(--stone)', letterSpacing:'0.22em', fontWeight:500 }}>{item.landmark.toUpperCase()}</span>
                    </div>
                  )}
                </button>
              ))}
            </div>
          )}

          {view === 'list' && (
            <div style={{ border:'1px solid var(--line)', background:'var(--bone)' }}>
              <div style={{
                display:'grid',
                gridTemplateColumns:'52px 1.5fr 1fr 1fr 1fr 1fr 80px',
                gap:20, padding:'12px 20px',
                borderBottom:'1px solid var(--ink)',
                fontSize:9, letterSpacing:'0.22em', fontWeight:500, color:'var(--stone)',
              }}>
                <span>—</span><span>CITY</span><span>REGION</span><span>TYPE</span><span>SIGNATURE</span><span>COORDINATES</span><span style={{ textAlign:'right' }}>PRICE</span>
              </div>
              {items.map((item, i) => (
                <button key={item.id} onClick={() => go('product', item.id)}
                  style={{
                    display:'grid',
                    gridTemplateColumns:'52px 1.5fr 1fr 1fr 1fr 1fr 80px',
                    alignItems:'center',
                    gap:20, padding:'14px 20px',
                    background: i % 2 ? 'var(--mist)' : 'var(--bone)',
                    borderBottom: i < items.length - 1 ? '1px dotted var(--line-strong)' : 'none',
                    textAlign:'left', width:'100%',
                  }}>
                  <div style={{ width:42, height:42, background:'var(--bone)', border:'1px solid var(--line)',
                    display:'flex', alignItems:'center', justifyContent:'center' }}>
                    {item.landmarkId
                      ? <Landmark id={item.landmarkId} color={`var(--${item.accent})`} size={28}/>
                      : <span style={{ fontSize:8, color:'var(--stone)', letterSpacing:'0.22em', fontWeight:500 }}>—</span>}
                  </div>
                  <div>
                    <div className="h3" style={{ fontSize:16, fontWeight:600 }}>{item.name}</div>
                    {item.landmark && <div className="label" style={{ marginTop:3, fontSize:9 }}>{item.landmark.toUpperCase()}</div>}
                  </div>
                  <div style={{ fontSize:13, color:'var(--stone)' }}>{item.region}</div>
                  <div style={{ fontSize:13, color:'var(--stone)' }}>{item.type}</div>
                  <div style={{ fontSize:13 }}>
                    {item.accent ? (
                      <span style={{ display:'flex', alignItems:'center', gap:8 }}>
                        <span style={{ width:10, height:10, background:`var(--${item.accent})` }}/>
                        {window.ACCENTS[item.accent].name}
                      </span>
                    ) : <span style={{ color:'var(--stone)' }}>—</span>}
                  </div>
                  <div className="caption" style={{ fontSize:11 }}>{item.coords.lat.toFixed(3)}° · {Math.abs(item.coords.lng).toFixed(3)}°</div>
                  <div style={{ fontSize:13, textAlign:'right', fontVariantNumeric:'tabular-nums' }}>{item.price ? `£${item.price}` : '—'}</div>
                </button>
              ))}
            </div>
          )}

          {view === 'map' && <AtlasMap items={items} t={t} go={go}/>}
        </div>
      </section>

      <Footer go={go}/>
    </div>
  );
}

function AtlasMap({ items, t, go }) {
  const [hovered, setHovered] = React.useState(null);
  const toXY = (lat, lng) => {
    const x = ((lng + 8) / 10) * 700 + 60;
    const y = 800 - ((lat - 49.8) / 9) * 740;
    return [x, y];
  };
  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 360px', gap:32, alignItems:'flex-start' }}>
      <div style={{ border:'1px solid var(--ink)', background:'var(--bone)', position:'relative', overflow:'hidden' }}>
        <svg viewBox="0 0 820 860" style={{ width:'100%', display:'block' }}>
          <path d="
            M 360 80 L 410 70 L 460 100 L 510 130 L 540 180 L 530 230 L 480 260
            L 520 310 L 550 360 L 530 410 L 480 440 L 460 480 L 480 520 L 530 540
            L 560 590 L 540 640 L 510 690 L 460 720 L 420 740 L 380 760 L 340 780
            L 290 770 L 250 740 L 220 700 L 200 650 L 180 590 L 170 530 L 180 470
            L 200 420 L 230 380 L 250 340 L 270 300 L 280 260 L 290 220 L 310 180
            L 330 140 Z
            M 130 180 L 180 170 L 220 200 L 240 250 L 230 290 L 200 310 L 160 290 L 130 240 Z"
            fill="var(--mist)" stroke="var(--ink)" strokeWidth="0.8"/>
          {[100,200,300,400,500,600,700,800].map(y => (
            <line key={'h'+y} x1="0" y1={y} x2="820" y2={y} stroke="var(--ink)" strokeWidth="0.4" opacity="0.15" strokeDasharray="2,4"/>
          ))}
          {[100,200,300,400,500,600,700].map(x => (
            <line key={'v'+x} x1={x} y1="0" x2={x} y2="860" stroke="var(--ink)" strokeWidth="0.4" opacity="0.15" strokeDasharray="2,4"/>
          ))}
          {items.map(item => {
            const [x, y] = toXY(item.coords.lat, item.coords.lng);
            const active = hovered === item.id;
            const pinColor = item.accent ? `var(--${item.accent})` : 'var(--ink)';
            return (
              <g key={item.id} style={{ cursor:'pointer' }}
                onMouseEnter={() => setHovered(item.id)}
                onMouseLeave={() => setHovered(null)}
                onClick={() => go('product', item.id)}>
                {item.accent ? (
                  <rect x={x - 5} y={y - 5} width="10" height="10" fill={pinColor}/>
                ) : (
                  <rect x={x - 3} y={y - 3} width="6" height="6" fill="none" stroke="var(--ink)" strokeWidth="1"/>
                )}
                {active && (
                  <g>
                    <rect x={x + 14} y={y - 28} width="200" height="46" fill="var(--bone)" stroke="var(--ink)" strokeWidth="0.8"/>
                    <rect x={x + 14} y={y - 28} width="6" height="46" fill={pinColor}/>
                    <text x={x + 26} y={y - 12} fontFamily="Inter, sans-serif" fontSize="13" fontWeight="600" fill="var(--ink)">{item.name}</text>
                    <text x={x + 26} y={y + 6} fontFamily="Inter, sans-serif" fontSize="9" letterSpacing="2" fill="var(--stone)">{item.landmark ? item.landmark.toUpperCase() : item.type.toUpperCase()}</text>
                  </g>
                )}
              </g>
            );
          })}
          <g transform="translate(740, 80)" opacity="0.7">
            <line x1="0" y1="-22" x2="0" y2="22" stroke="var(--ink)" strokeWidth="1"/>
            <path d="M 0 -22 L 6 -10 L 0 -16 L -6 -10 Z" fill="var(--ink)"/>
            <text x="0" y="-30" textAnchor="middle" fontFamily="Inter" fontSize="11" letterSpacing="3" fontWeight="500" fill="var(--ink)">N</text>
          </g>
        </svg>
      </div>
      <div style={{ position:'sticky', top:152 }}>
        <div className="label">Pin a place</div>
        <h3 className="h1" style={{ fontSize:32, marginTop:14 }}>Every cityform we've made, on one chart.</h3>
        <p className="body" style={{ fontSize:14, color:'var(--stone)', lineHeight:1.55, marginTop:14 }}>
          Filled markers ship from the collection. Outlined markers are commissions or in development.
        </p>
        <button className="btn btn-ghost" style={{ marginTop:24 }} onClick={() => go('atelier')}>
          Suggest a new place &nbsp;{Icon.plus}
        </button>
        <div style={{ marginTop:36, padding:'18px 0', borderTop:'1px solid var(--line)' }}>
          <div className="label" style={{ marginBottom:14 }}>Signature index</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px 18px' }}>
            {Object.entries(window.ACCENTS).map(([k, v]) => (
              <div key={k} style={{ display:'flex', alignItems:'center', gap:10, fontSize:12 }}>
                <span style={{ width:12, height:12, background:v.hex }}/>
                <span>{v.name}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

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