// Single-item page — wall-text-meets-last-will-and-testament.

function ItemPage({ item, go, lang = 'en' }) {
  if (!item) { go('archive'); return null; }
  const sameRecipient = window.ITEMS.filter(i => i.beneficiary === item.beneficiary && i.id !== item.id);
  const sameCategory  = window.ITEMS.filter(i => i.category === item.category && i.id !== item.id).slice(0, 3);
  const idx = window.ITEMS.indexOf(item);
  const total = window.ITEMS.length;

  return (
    <div className="fade-in">
      <ItemBreadcrumb item={item} idx={idx} total={total} go={go} lang={lang} />
      <ItemMain item={item} go={go} lang={lang} />
      <BequestSection item={item} lang={lang} />
      <ProvenanceTimeline item={item} lang={lang} />
      {sameRecipient.length > 0 && <RecipientCluster item={item} list={sameRecipient} go={go} lang={lang} />}
      <RelatedItems list={sameCategory} go={go} lang={lang} />
      <Footer lang={lang} />
    </div>
  );
}

// ── Breadcrumb / pager ────────────────────────────────────────────────────
function ItemBreadcrumb({ item, idx, total, go, lang = 'en' }) {
  const ti = window.T[lang].item;
  const prev = window.ITEMS[(idx - 1 + total) % total];
  const next = window.ITEMS[(idx + 1) % total];
  return (
    <section style={{ borderBottom: '1px solid var(--rule)', padding: '24px 0' }}>
      <div className="page flex" style={{ justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="flex gap-2" style={{ alignItems: 'baseline' }}>
          <a className="mono tiny upper" onClick={() => go('archive')} style={{ cursor: 'pointer', color: 'var(--ink)', letterSpacing: '0.28em' }}>{ti.backToArchive}</a>
          <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.28em' }}>· Helena M. · {item.category} · № {String(idx+1).padStart(3,'0')} / {String(total).padStart(3,'0')}</span>
        </div>
        <div className="flex gap-3">
          <a onClick={() => go('item', prev)} className="mono tiny upper" style={{ cursor: 'pointer', letterSpacing: '0.22em' }}>← {prev.name}</a>
          <span style={{ color: 'var(--hairline)' }}>|</span>
          <a onClick={() => go('item', next)} className="mono tiny upper" style={{ cursor: 'pointer', letterSpacing: '0.22em' }}>{next.name} →</a>
        </div>
      </div>
    </section>
  );
}

// ── Main: large image + spec column ───────────────────────────────────────
function ItemMain({ item, go, lang = 'en' }) {
  const ti = window.T[lang].item;
  return (
    <section style={{ padding: '80px 0 96px', borderBottom: '1px solid var(--rule)' }}>
      <div className="page">
        <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 96, alignItems: 'flex-start' }}>
          {/* Image column */}
          <div>
            <div style={{ position: 'relative' }}>
              <ItemVisual item={item} h={620} />
              <div className="mono tiny upper" style={{
                position: 'absolute', left: -1, bottom: -32,
                background: 'var(--ink)', color: 'var(--paper)', padding: '10px 16px',
                letterSpacing: '0.28em',
              }}>
                Plate {String(window.ITEMS.indexOf(item)+1).padStart(2, '0')} · {ti.catalogueRaisonne}
              </div>
            </div>
            {/* alt views */}
            <div className="grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginTop: 56 }}>
              {[0,1,2,3].map(i => (
                <div key={i} style={{
                  height: 96, background: item.swatch[i % 2],
                  position: 'relative', overflow: 'hidden',
                  cursor: 'pointer',
                  outline: i === 0 ? '1px solid var(--ink)' : 'none',
                  outlineOffset: -1,
                }}>
                  <div style={{
                    position: 'absolute', inset: 0,
                    background: 'linear-gradient(135deg, rgba(255,255,255,0.10), transparent 50%, rgba(0,0,0,0.10))',
                  }} />
                  <span className="mono tiny" style={{ position: 'absolute', left: 10, bottom: 8, color: item.swatch[1], letterSpacing: '0.22em' }}>
                    {ti.viewLabel} 0{i+1}
                  </span>
                </div>
              ))}
            </div>
          </div>

          {/* Spec column */}
          <div style={{ position: 'sticky', top: 96 }}>
            <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>{item.category} · № {String(window.ITEMS.indexOf(item)+1).padStart(3, '0')}</span>
            <h1 className="display" style={{ fontSize: 56, margin: '20px 0 12px', lineHeight: 0.98, textWrap: 'pretty' }}>
              {item.name}
            </h1>
            <div className="serif" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--ink-2)', marginBottom: 36, fontWeight: 300 }}>
              {item.year} · {item.material}
            </div>

            <p className="serif" style={{ fontSize: 17, lineHeight: 1.65, color: 'var(--ink-2)', fontWeight: 300 }}>
              {item.description}
            </p>

            <div style={{ marginTop: 40 }}>
              <SpecRow label={ti.year}      value={item.year} />
              <SpecRow label={ti.material}  value={item.material} />
              <SpecRow label={ti.category}  value={item.category} />
              <SpecRow label={ti.location}  value={item.location} />
              <SpecRow label={ti.condition} value={ti.conditionValue} />
              <SpecRow label="Status"       value={ti.sealedStatus} sealed sealedLabel={ti.sealedLabel} />
            </div>

            <div className="flex gap-2" style={{ marginTop: 40 }}>
              <button className="btn" onClick={() => go('add-item')}>{ti.editObject}</button>
              <button className="btn ghost" onClick={() => go('bequest', item)}>{ti.editBequest}</button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function SpecRow({ label, value, sealed, sealedLabel }) {
  return (
    <div className="flex" style={{ padding: '12px 0', borderBottom: '1px dotted var(--hairline)' }}>
      <span className="mono tiny upper" style={{ color: 'var(--muted)', width: 120, letterSpacing: '0.24em' }}>{label}</span>
      {sealed ? (
        <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.22em' }}>
          <span style={{ display: 'inline-block', width: 6, height: 6, background: 'var(--frost)', marginRight: 8, transform: 'translateY(-1px)' }}></span>
          {sealedLabel}
        </span>
      ) : (
        <span className="mono tiny upper" style={{ color: 'var(--ink)', letterSpacing: '0.22em' }}>{value}</span>
      )}
    </div>
  );
}

// ── The Bequest — the actual will text ────────────────────────────────────
function BequestSection({ item, lang = 'en' }) {
  const ti = window.T[lang].item;
  return (
    <section style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '140px 0' }}>
      <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' }}>{ti.bequestTag}</span>
            <h2 className="display" style={{ fontSize: 52, margin: '28px 0 32px', lineHeight: 1, color: 'var(--paper)' }}>
              {ti.bequestTitle}
            </h2>
            <p className="serif" style={{ fontSize: 16, lineHeight: 1.65, color: 'rgba(239,239,237,0.65)', fontWeight: 300 }}>
              {ti.bequestDesc}
            </p>

            <div style={{ marginTop: 48, paddingTop: 28, borderTop: '1px solid rgba(239,239,237,0.20)' }}>
              <KV label={ti.kvTo}       value={item.beneficiary} large />
              <KV label={ti.kvRelation} value={item.relation} />
              <KV label={ti.kvDelivery} value={item.delivery} />
              <KV label={ti.kvWitness}  value="A. Pereira, notary" />
              <KV label={ti.kvSeal}     value="14 May 2026 · 14:12 GMT" />
            </div>
          </div>

          {/* The will text — no border, just space */}
          <div style={{ position: 'relative' }}>
            <div className="mono tiny upper" style={{ color: 'var(--ice)', marginBottom: 32, letterSpacing: '0.32em' }}>{ti.verbatim}</div>

            <div style={{
              position: 'relative',
              paddingLeft: 40,
              borderLeft: '1px solid var(--ice)',
            }}>
              <p className="serif" style={{ fontSize: 32, lineHeight: 1.45, margin: 0, color: 'var(--paper)', fontWeight: 300 }}>
                {item.will}
              </p>
              <div className="flex" style={{ marginTop: 48, paddingTop: 24, borderTop: '1px solid rgba(239,239,237,0.18)', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span className="serif" style={{ fontStyle: 'italic', fontSize: 17, color: 'rgba(239,239,237,0.55)', fontWeight: 300 }}>
                  — Helena Marković, Lisbon
                </span>
                <span className="mono tiny upper" style={{ color: 'rgba(239,239,237,0.42)', letterSpacing: '0.28em' }}>{ti.signedIn}</span>
              </div>
            </div>

            {/* Receipt stub */}
            <div className="flex" style={{
              marginTop: 40, padding: '16px 24px',
              border: '1px dashed var(--frost)',
              alignItems: 'center', justifyContent: 'space-between',
            }}>
              <span className="mono tiny upper" style={{ color: 'rgba(239,239,237,0.55)', letterSpacing: '0.22em' }}>
                {ti.deliveryCard} {item.beneficiary}{ti.deliveryCardSuffix}
              </span>
              <span className="mono tiny upper" style={{ color: 'var(--frost)', letterSpacing: '0.28em' }}>RIP-{item.id.slice(0, 6).toUpperCase()}</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function KV({ label, value, large }) {
  return (
    <div className="flex" style={{ padding: '12px 0', borderBottom: '1px dotted rgba(239,239,237,0.18)' }}>
      <span className="mono tiny upper" style={{ color: 'rgba(239,239,237,0.45)', width: 120, letterSpacing: '0.24em' }}>{label}</span>
      <span className={large ? 'serif' : 'mono tiny upper'} style={{
        color: 'var(--paper)',
        fontStyle: large ? 'italic' : 'normal',
        fontSize: large ? 18 : 11,
        fontWeight: large ? 300 : 'normal',
        letterSpacing: large ? '0' : '0.22em',
      }}>{value}</span>
    </div>
  );
}

// ── Provenance timeline ───────────────────────────────────────────────────
function ProvenanceTimeline({ item, lang = 'en' }) {
  const ti = window.T[lang].item;
  const events = [
    [item.year, ti.eventManufactured, item.provenance.split('.')[0] || '—'],
    ['1979', ti.eventAcquired,  'Feira da Ladra, Lisbon. Paid 2,400 escudos.'],
    ['1989', ti.eventRepaired,  'Carriage return reset. Ribbon replacement #3.'],
    ['2014', ti.eventCatalogued,'Photographed by keeper. First entry in archive.'],
    ['2026', ti.eventBequeathed,'Sealed will to ' + item.beneficiary + '.'],
  ];
  return (
    <section style={{ padding: '140px 0' }}>
      <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' }}>{ti.provenanceTag}</span>
            <h2 className="display" style={{ fontSize: 48, margin: '24px 0 0', lineHeight: 1 }}>{ti.provenanceTitle}</h2>
          </div>
          <p className="serif" style={{ maxWidth: 360, color: 'var(--ink-2)', fontSize: 16, lineHeight: 1.6, fontWeight: 300 }}>
            {ti.provenanceSub}
          </p>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: `repeat(${events.length}, 1fr)`,
          gap: 0, borderTop: '1px solid var(--ink)',
          position: 'relative',
        }}>
          {events.map(([year, title, body], i) => {
            const isLast = i === events.length - 1;
            return (
              <div key={i} style={{
                padding: '28px 22px 40px',
                borderLeft: i === 0 ? 'none' : '1px solid var(--hairline)',
                position: 'relative',
              }}>
                <div style={{
                  position: 'absolute', top: -6, left: 22,
                  width: 11, height: 11,
                  background: isLast ? 'var(--paper)' : 'var(--ink)',
                  border: isLast ? '1px solid var(--ice)' : 'none',
                  borderRadius: isLast ? '50%' : 0,
                }} />
                {isLast && (
                  <div style={{
                    position: 'absolute', top: -2, left: 26,
                    width: 3, height: 3, background: 'var(--frost)', borderRadius: '50%',
                  }} />
                )}
                <div className="mono" style={{ fontSize: 14, color: 'var(--ice)', marginBottom: 12, marginTop: 22, letterSpacing: '0.18em' }}>{year}</div>
                <div className="display" style={{ fontSize: 22, marginBottom: 12 }}>{title}</div>
                <p className="serif" style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)', margin: 0, fontWeight: 300 }}>{body}</p>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ── Recipient cluster ────────────────────────────────────────────────────
function RecipientCluster({ item, list, go, lang = 'en' }) {
  const ti = window.T[lang].item;
  return (
    <section style={{ padding: '96px 0', background: 'var(--paper-2)', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)' }}>
      <div className="page">
        <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>{ti.alsoForPrefix} {item.beneficiary}</span>
        <h2 className="display" style={{ fontSize: 44, margin: '24px 0 40px', lineHeight: 1.02 }}>
          {list.length === 1 ? ti.otherThingsSingular : `${list.length} ${ti.otherThingsPlural}`}
        </h2>
        <div className="grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: 28 }}>
          {list.map(it => (
            <button key={it.id} onClick={() => go('item', it)} style={{
              padding: 0, border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
            }}>
              <ItemVisual item={it} h={200} />
              <div className="display" style={{ fontSize: 16, marginTop: 16 }}>{it.name}</div>
              <div className="mono tiny upper" style={{ color: 'var(--muted)', marginTop: 6, letterSpacing: '0.22em' }}>{it.category} · {it.year}</div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Related items ────────────────────────────────────────────────────────
function RelatedItems({ list, go, lang = 'en' }) {
  const ti = window.T[lang].item;
  if (!list.length) return null;
  return (
    <section style={{ padding: '120px 0 80px' }}>
      <div className="page">
        <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em' }}>{ti.continueTag}</span>
        <h2 className="display" style={{ fontSize: 36, margin: '24px 0 36px' }}>{ti.adjacentTitle}</h2>
        <div className="grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, borderTop: '1px solid var(--ink)' }}>
          {list.map((it, i) => (
            <button key={it.id} onClick={() => go('item', it)} style={{
              padding: '24px 22px 28px',
              borderLeft: i === 0 ? 'none' : '1px solid var(--hairline)',
              borderBottom: '1px solid var(--ink)',
              background: 'var(--paper)',
              cursor: 'pointer',
              textAlign: 'left',
            }}>
              <ItemVisual item={it} h={220} />
              <div className="display" style={{ fontSize: 20, marginTop: 20 }}>{it.name}</div>
              <div className="serif" style={{ fontStyle: 'italic', fontSize: 14, color: 'var(--ink-2)', marginTop: 8, fontWeight: 300 }}>
                → {it.beneficiary}
              </div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ItemPage });
