// Archive — concrete museum. Display case + flat catalogue.

function Archive({ go, lang = 'en' }) {
  const [cat, setCat] = React.useState('ALL');
  const [view, setView] = React.useState('shelf');
  const items = window.ITEMS.filter(i => cat === 'ALL' || i.category === cat);

  return (
    <div className="fade-in">
      <ArchiveHeader lang={lang} />
      <ArchiveControls cat={cat} setCat={setCat} view={view} setView={setView} count={items.length} go={go} lang={lang} />
      <ConcreteRoom items={items} go={go} />
      {view === 'shelf' && <ShelfGrid items={items} go={go} />}
      {view === 'index' && <IndexList items={items} go={go} />}
      <ArchiveFooter />
      <Footer lang={lang} />
    </div>
  );
}

// ── Curator header ────────────────────────────────────────────────────────
function ArchiveHeader({ lang = 'en' }) {
  const c = window.KEEPER;
  const zh = lang === 'zh';
  return (
    <section style={{ borderBottom: '1px solid var(--rule)', padding: '64px 0 56px' }}>
      <div className="page">
        <div className="flex" style={{ alignItems: 'flex-end', justifyContent: 'space-between', gap: 64 }}>
          <div>
            <div className="flex gap-2" style={{ alignItems: 'baseline', marginBottom: 24 }}>
              <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>{zh ? '典藏庫 04211' : 'Archive 04211'}</span>
              <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.32em' }}>— {zh ? '私人' : 'Private'} — {c.willStatus}</span>
            </div>
            <h1 className="display" style={{ fontSize: 80, margin: 0, lineHeight: 0.95 }}>
              {c.name}
              <span className="serif" style={{ fontStyle: 'italic', fontWeight: 300, fontSize: 48, marginLeft: 24, color: 'var(--ice)' }}>
                {zh ? '— 她的物件。' : '— her things.'}
              </span>
            </h1>
            <p className="serif" style={{ fontSize: 18, color: 'var(--ink-2)', maxWidth: 620, marginTop: 28, lineHeight: 1.6, fontWeight: 300 }}>
              {zh
                ? `${c.itemCount} 件物品，分配給 31 位指定收受人、三個機構、一座城市，以及一項開放式遺贈。上次編輯於週二下午 4:12，那時正在下雨。`
                : `${c.itemCount} objects, distributed across 31 named recipients, three institutions, one city, and one open bequest. Last edited Tuesday at 4:12pm, while it was raining.`}
            </p>
          </div>

          <aside style={{ minWidth: 280, borderTop: '1px solid var(--ice)', paddingTop: 20 }}>
            <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.28em' }}>{zh ? '持有人' : 'Keeper'}</div>
            <div className="display" style={{ fontSize: 24, marginTop: 10, marginBottom: 20 }}>H.M.</div>
            <Row label={zh ? '出生' : 'Born'}       value={`${c.born} · ${c.city}`} />
            <Row label={zh ? '物品' : 'Objects'}    value={`${c.itemCount}`} />
            <Row label={zh ? '收受人' : 'Recipients'} value="31" />
            <Row label={zh ? '封印狀態' : 'Sealed'}  value={c.willStatus} />
          </aside>
        </div>
      </div>
    </section>
  );
}

function Row({ label, value }) {
  return (
    <div className="flex" style={{ justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px dotted var(--hairline)' }}>
      <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{label}</span>
      <span className="mono tiny upper" style={{ color: 'var(--ink)', letterSpacing: '0.22em' }}>{value}</span>
    </div>
  );
}

// ── Filter + view toggle row ──────────────────────────────────────────────
function ArchiveControls({ cat, setCat, view, setView, count, go, lang = 'en' }) {
  const zh = lang === 'zh';
  return (
    <section style={{ borderBottom: '1px solid var(--rule)', padding: '20px 0', position: 'sticky', top: 68, background: 'var(--paper)', zIndex: 20 }}>
      <div className="page flex" style={{ justifyContent: 'space-between', alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
        <div className="flex" style={{ gap: 2, flexWrap: 'wrap' }}>
          {window.CATEGORIES.map(c => (
            <button key={c} onClick={() => setCat(c)} style={{
              padding: '8px 14px',
              background: c === cat ? 'var(--ink)' : 'transparent',
              color: c === cat ? 'var(--paper)' : 'var(--ink-2)',
              border: 'none',
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 10, letterSpacing: '0.22em',
              cursor: 'pointer',
              textTransform: 'uppercase',
            }}>{c}</button>
          ))}
        </div>
        <div className="flex" style={{ gap: 16, alignItems: 'center' }}>
          <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{count} / 47</span>
          <div className="flex" style={{ border: '1px solid var(--ink)' }}>
            {[['shelf', zh ? '展架' : 'shelf'], ['index', zh ? '目錄' : 'index']].map(([v, label]) => (
              <button key={v} onClick={() => setView(v)} style={{
                padding: '7px 16px',
                background: view === v ? 'var(--ink)' : 'transparent',
                color: view === v ? 'var(--paper)' : 'var(--ink)',
                border: 'none', cursor: 'pointer',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.22em',
              }}>{label}</button>
            ))}
          </div>
          <button className="btn" style={{ padding: '10px 18px' }} onClick={() => go('add-item')}>{zh ? '+ 新增物品' : '+ Add object'}</button>
        </div>
      </div>
    </section>
  );
}

// ── Display Case — concrete vitrine ───────────────────────────────────────
function DisplayCase({ items, go }) {
  return (
    <section style={{ background: 'var(--paper-2)', borderBottom: '1px solid var(--rule)', overflow: 'hidden', padding: '96px 0 96px' }}>
      <div className="page">
        <div className="flex" style={{ alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 56 }}>
          <div>
            <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>§ Display case · West wall</span>
            <h2 className="display" style={{ fontSize: 48, margin: '24px 0 0', lineHeight: 1 }}>The featured shelf.</h2>
          </div>
          <p className="serif" style={{ maxWidth: 360, color: 'var(--ink-2)', fontSize: 16, lineHeight: 1.6, fontWeight: 300 }}>
            Four objects pinned by the keeper. Click any to read the bequest.
          </p>
        </div>

        {/* The 3D vitrine */}
        <div style={{
          perspective: '2400px',
          perspectiveOrigin: '50% 30%',
          padding: '40px 0 96px',
        }}>
          <div style={{
            position: 'relative',
            transformStyle: 'preserve-3d',
            transform: 'rotateX(8deg)',
            height: 420,
          }}>
            {/* Concrete back wall — cool light gradient */}
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, #DCDCD9 0%, #C8C8C5 100%)',
              transform: 'translateZ(-220px)',
            }} />
            {/* Vertical seam — concrete pour line */}
            <div style={{
              position: 'absolute', left: '50%', top: 0, bottom: 0, width: 1,
              background: 'rgba(0,0,0,0.10)',
              transform: 'translateZ(-218px)',
            }} />
            {/* Tie holes — pairs of small dots typical of formed concrete */}
            {[0.18, 0.5, 0.82].map(x => (
              <React.Fragment key={x}>
                <div style={{
                  position: 'absolute', left: `${x*100}%`, top: 44,
                  width: 9, height: 9, borderRadius: '50%',
                  background: 'var(--frost)',
                  boxShadow: '0 0 18px 4px rgba(191,236,255,0.55), inset 0 0 0 1px rgba(102,153,204,0.55)',
                  transform: 'translateZ(-216px)',
                }} />
                <div style={{
                  position: 'absolute', left: `${x*100}%`, bottom: 116,
                  width: 9, height: 9, borderRadius: '50%',
                  background: 'var(--frost)',
                  boxShadow: '0 0 18px 4px rgba(191,236,255,0.55), inset 0 0 0 1px rgba(102,153,204,0.55)',
                  transform: 'translateZ(-216px)',
                }} />
              </React.Fragment>
            ))}
            {/* Number plates */}
            <div className="mono tiny upper" style={{
              position: 'absolute', left: 32, top: 24, color: 'rgba(17,17,17,0.42)',
              transform: 'translateZ(-218px)', letterSpacing: '0.32em',
            }}>
              West Wall · Shelf 3 / 8 · Keeper's pin
            </div>
            <div className="mono tiny upper" style={{
              position: 'absolute', right: 32, top: 24, color: 'rgba(17,17,17,0.42)',
              transform: 'translateZ(-218px)', letterSpacing: '0.32em',
            }}>
              Lit · 14:12 GMT · Lisbon
            </div>

            {/* Floor / shelf surface */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 0,
              height: 80,
              background: 'linear-gradient(to bottom, #1a1a1a, #0a0a0a)',
              transform: 'rotateX(80deg) translateZ(-40px)',
              transformOrigin: 'bottom',
            }} />

            {/* Shelf front edge — thin hairline */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 0,
              height: 2, background: 'var(--ink)',
            }} />

            {/* Items on the shelf */}
            <div style={{
              position: 'absolute', inset: 0,
              display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
              gap: 32, padding: '36px 32px 12px',
            }}>
              {items.map((it, i) => (
                <button key={it.id}
                  onClick={() => go('item', it)}
                  style={{
                    position: 'relative',
                    background: 'transparent', border: 'none', padding: 0,
                    cursor: 'pointer',
                    transformStyle: 'preserve-3d',
                    transform: `translateZ(${i * 3}px)`,
                    transition: 'transform 0.25s ease',
                  }}
                  onMouseEnter={e => e.currentTarget.style.transform = `translateZ(${i*3}px) translateY(-6px)`}
                  onMouseLeave={e => e.currentTarget.style.transform = `translateZ(${i*3}px)`}
                >
                  <ItemVisual item={it} h={300} />
                  <div style={{
                    position: 'absolute', left: '8%', right: '8%', bottom: -10, height: 14,
                    background: 'radial-gradient(ellipse, rgba(0,0,0,0.45), transparent 70%)',
                    transform: 'rotateX(80deg)',
                    transformOrigin: 'top',
                  }} />
                  <div style={{ marginTop: 16, textAlign: 'left' }}>
                    <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.28em' }}>№ {String(i+1).padStart(2,'0')}</div>
                    <div className="display" style={{ fontSize: 15, color: 'var(--ink)', marginTop: 6, textWrap: 'pretty' }}>{it.name}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Shelf grid ────────────────────────────────────────────────────────────
function ShelfGrid({ items, go }) {
  const groups = {};
  items.forEach(it => { (groups[it.category] ||= []).push(it); });
  const order = Object.keys(groups);

  return (
    <section style={{ padding: '96px 0 120px' }}>
      <div className="page">
        {order.map((cat, gi) => (
          <div key={cat} style={{ marginBottom: 96 }}>
            <div className="flex" style={{ alignItems: 'baseline', gap: 24, marginBottom: 32 }}>
              <span className="mono" style={{ color: 'var(--ice)', fontSize: 12, letterSpacing: '0.22em' }}>§ {String(gi+1).padStart(2,'0')}</span>
              <span className="display" style={{ fontSize: 28 }}>{cat.toLowerCase()}</span>
              <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
              <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.28em' }}>{groups[cat].length} object{groups[cat].length>1?'s':''}</span>
            </div>

            <div style={{ position: 'relative' }}>
              <div className="grid" style={{
                gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',
                gap: 0, borderTop: '1px solid var(--ink)',
              }}>
                {groups[cat].map((it, i) => (
                  <ShelfCard key={it.id} item={it} idx={i} go={go} />
                ))}
              </div>
              {/* shelf base — thin hairline + light cast-shadow */}
              <div style={{ height: 1, background: 'var(--ink)' }} />
              <div style={{ height: 28, background: 'linear-gradient(to bottom, rgba(0,0,0,0.12), transparent)' }} />
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function ShelfCard({ item, idx, go }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={() => go('item', item)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative',
        background: hover ? 'rgba(191,236,255,0.22)' : 'var(--paper)',
        border: 'none',
        borderRight: '1px solid var(--hairline)',
        borderBottom: hover ? '1px solid var(--ice)' : '1px solid var(--hairline)',
        padding: '24px 22px 28px',
        textAlign: 'left',
        cursor: 'pointer',
        transition: 'background 0.18s ease, border-color 0.18s ease',
      }}
    >
      <div className="flex" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
        <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.28em' }}>№ {String(idx+1).padStart(3,'0')}</span>
        <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{item.year}</span>
      </div>

      <ItemVisual item={item} h={220} />

      <div style={{ marginTop: 20 }}>
        <div className="display" style={{ fontSize: 18, marginBottom: 10, textWrap: 'pretty', lineHeight: 1.15 }}>{item.name}</div>
        <div className="mono tiny upper" style={{ color: 'var(--muted)', marginBottom: 14, letterSpacing: '0.22em' }}>
          {item.material}
        </div>
        <div className="flex" style={{ alignItems: 'center', gap: 10, paddingTop: 12, borderTop: '1px dotted var(--hairline)' }}>
          <span className="mono tiny upper" style={{ color: 'var(--ice)' }}>→</span>
          <span className="serif" style={{ fontStyle: 'italic', fontSize: 14, color: 'var(--ink-2)', fontWeight: 300 }}>{item.beneficiary}</span>
        </div>
      </div>

      {hover && (
        <div className="mono tiny upper" style={{
          position: 'absolute', top: 24, right: 22, color: 'var(--ice)', letterSpacing: '0.28em',
        }}>OPEN →</div>
      )}
    </button>
  );
}

// ── Index list ────────────────────────────────────────────────────────────
function IndexList({ items, go }) {
  return (
    <section style={{ padding: '64px 0 120px' }}>
      <div className="page">
        <div className="grid" style={{
          gridTemplateColumns: '60px 1fr 1.2fr 1fr 0.8fr 0.8fr 60px',
          borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)',
        }}>
          {['№', 'Object', 'Beneficiary', 'Category', 'Year', 'Delivery', ''].map((h, i) => (
            <div key={i} className="mono tiny upper" style={{ padding: '14px 14px', color: 'var(--muted)', borderBottom: '1px solid var(--ink)', letterSpacing: '0.28em' }}>{h}</div>
          ))}
          {items.map((it, i) => (
            <React.Fragment key={it.id}>
              <Cell><span className="mono" style={{ color: 'var(--ice)', fontSize: 12, letterSpacing: '0.18em' }}>{String(i+1).padStart(3,'0')}</span></Cell>
              <Cell><span style={{ fontWeight: 500 }}>{it.name}</span></Cell>
              <Cell><span className="serif" style={{ fontStyle: 'italic', fontWeight: 300 }}>{it.beneficiary}</span></Cell>
              <Cell><span className="mono tiny upper" style={{ color: 'var(--ink-2)', letterSpacing: '0.22em' }}>{it.category}</span></Cell>
              <Cell><span className="mono" style={{ letterSpacing: '0.05em' }}>{it.year}</span></Cell>
              <Cell><span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{it.delivery}</span></Cell>
              <Cell><button onClick={() => go('item', it)} className="mono tiny upper" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink)' }}>→</button></Cell>
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

function Cell({ children }) {
  return <div style={{ padding: '16px 14px', borderBottom: '1px solid var(--hairline)', display: 'flex', alignItems: 'center', fontSize: 14 }}>{children}</div>;
}

// ── Distribution summary — restrained, grey scale ────────────────────────
function ArchiveFooter() {
  const benefits = [
    ['Family',                 14, '#111111'],
    ['Friends & chosen kin',   11, '#3D4550'],
    ['Institutions',            4, '#6E747C'],
    ['Open bequest',            2, '#A8ABAE'],
    ['Sealed / burned',         1, '#D0D0CD'],
  ];
  const total = benefits.reduce((s, [, n]) => s + n, 0);
  return (
    <section style={{ padding: '64px 0 120px', borderTop: '1px solid var(--rule)' }}>
      <div className="page">
        <div className="grid" style={{ gridTemplateColumns: '1fr 2fr', gap: 96, alignItems: 'flex-start' }}>
          <div>
            <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>§ Distribution</span>
            <h3 className="display" style={{ fontSize: 36, margin: '24px 0 20px', lineHeight: 1 }}>Where it all goes.</h3>
            <p className="serif" style={{ fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.6, fontWeight: 300 }}>
              A breakdown of the {window.KEEPER.itemCount} objects in this archive, by class of recipient. Updated whenever a bequest changes.
            </p>
          </div>
          <div>
            <div className="flex" style={{ height: 36, marginBottom: 32, border: '1px solid var(--ink)' }}>
              {benefits.map(([l, n, color], i) => (
                <div key={l} style={{
                  flex: n,
                  background: color,
                  borderRight: i < benefits.length-1 ? '1px solid var(--ink)' : 'none',
                }} />
              ))}
            </div>
            <div className="grid" style={{ gridTemplateColumns: 'repeat(5, 1fr)', gap: 20 }}>
              {benefits.map(([l, n, color], i) => (
                <div key={l}>
                  <div className="flex gap-1" style={{ alignItems: 'center', marginBottom: 10 }}>
                    <span style={{
                      width: 10, height: 10, background: color,
                      border: i === 4 ? '1px solid var(--ink)' : 'none',
                    }} />
                    <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{l}</span>
                  </div>
                  <div className="display" style={{ fontSize: 32 }}>{n}</div>
                  <div className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em' }}>{Math.round(n/total*100)}%</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Archive });
