// marketplace.jsx — Estate sale listings on behalf of deceased curators.

function Marketplace({ go, lang = 'en' }) {
  const tm = window.T[lang].marketplace;
  const [cat, setCat] = React.useState('ALL');
  const [enquired, setEnquired] = React.useState({});

  const categories = ['ALL', 'PHOTOGRAPHY', 'LITERATURE', 'FURNITURE', 'INSTRUMENTS', 'EPHEMERA', 'JEWELRY', 'OBJECTS'];
  const items = cat === 'ALL'
    ? window.MARKET_ITEMS
    : window.MARKET_ITEMS.filter(i => i.category === cat);

  const fmt = (n) => n.toLocaleString('en-EU', { minimumFractionDigits: 0 });

  const howSteps = [
    { title: tm.how1Title, desc: tm.how1Desc },
    { title: tm.how2Title, desc: tm.how2Desc },
    { title: tm.how3Title, desc: tm.how3Desc },
    { title: tm.how4Title, desc: tm.how4Desc },
  ];

  return (
    <>
      {/* Page header */}
      <header style={{ borderBottom: '1px solid var(--ink)', padding: '72px 0 0' }}>
        <div className="page">
          <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr 1fr', gap: 48, alignItems: 'flex-end', paddingBottom: 56 }}>
            <div>
              <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.28em' }}>{tm.sectionTag}</div>
              <div className="mono tiny upper" style={{ color: 'var(--muted)', marginTop: 8, letterSpacing: '0.22em' }}>{tm.sectionSub}</div>
            </div>
            <h1 className="display" style={{ fontSize: 'clamp(36px,5vw,72px)', margin: 0, lineHeight: 0.95 }}>
              {tm.title.split('\n').map((line, i) => <span key={i}>{line}{i === 0 && <br />}</span>)}
            </h1>
            <p className="serif" style={{ fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.6, fontWeight: 300, margin: 0 }}>
              {tm.subtitle}{' '}
              <em style={{ color: 'var(--ice)' }}>{tm.subtitleEm}</em>
            </p>
          </div>

          {/* Commission strip */}
          <div style={{ borderTop: '1px solid var(--hairline)', padding: '20px 0', display: 'flex', gap: 24, alignItems: 'flex-start' }}>
            <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.28em', whiteSpace: 'nowrap', marginTop: 1 }}>{tm.commissionTag}</div>
            <div className="serif" style={{ fontSize: 14, color: 'var(--muted)', fontStyle: 'italic', fontWeight: 300, lineHeight: 1.6 }}>
              {tm.commissionDesc}
            </div>
          </div>

          {/* Category filter */}
          <div style={{ display: 'flex', gap: 0, borderTop: '1px solid var(--hairline)', overflowX: 'auto' }}>
            {categories.map((c, i) => (
              <button key={c} onClick={() => setCat(c)} style={{
                padding: '16px 20px', border: 'none', background: 'transparent',
                borderBottom: cat === c ? '2px solid var(--ink)' : '2px solid transparent',
                color: cat === c ? 'var(--ink)' : 'var(--muted)',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                textTransform: 'uppercase', letterSpacing: '0.24em', cursor: 'pointer',
                whiteSpace: 'nowrap', transition: 'color 0.15s, border-color 0.15s',
              }}>
                {c === 'ALL' ? tm.filterAll : c}
              </button>
            ))}
          </div>
        </div>
      </header>

      {/* Listings grid */}
      <div className="page" style={{ padding: '64px 32px 0' }}>
        {items.length === 0 ? (
          <div style={{ padding: '80px 0', textAlign: 'center' }}>
            <div className="serif" style={{ fontSize: 18, color: 'var(--muted)', fontStyle: 'italic', fontWeight: 300 }}>{tm.noItems}</div>
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, borderTop: '1px solid var(--ink)' }}>
            {items.map((item, i) => (
              <MarketCard
                key={item.id}
                item={item}
                tm={tm}
                fmt={fmt}
                borderLeft={i % 3 !== 0}
                enquired={!!enquired[item.id]}
                onEnquire={() => setTimeout(() => setEnquired(e => ({ ...e, [item.id]: true })), 1200)}
              />
            ))}
          </div>
        )}
      </div>

      {/* How it works */}
      <section style={{ padding: '120px 0 0' }}>
        <div className="page" style={{ padding: '0 32px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 56 }}>
            <div>
              <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.32em', marginBottom: 16 }}>§ 02 — Method</div>
              <h2 className="display" style={{ fontSize: 56, margin: 0, lineHeight: 1 }}>{tm.howTitle}</h2>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)' }}>
            {howSteps.map((s, i) => (
              <div key={i} style={{ padding: '40px 28px 56px', borderLeft: i === 0 ? 'none' : '1px solid var(--hairline)' }}>
                <div className="mono tiny upper" style={{ color: 'var(--ice)', marginBottom: 80, letterSpacing: '0.28em' }}>
                  {String(i + 1).padStart(2, '0')}
                </div>
                <div className="display" style={{ fontSize: 22, marginBottom: 16, lineHeight: 1.1 }}>{s.title}.</div>
                <p className="serif" style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--ink-2)', margin: 0, fontWeight: 300 }}>{s.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Notary note */}
      <div className="page" style={{ padding: '32px 32px 120px', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <span style={{ display: 'inline-block', width: 8, height: 8, background: 'var(--frost)', marginTop: 3, flexShrink: 0 }} />
        <div className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em', lineHeight: 1.8 }}>
          All estate sales are co-signed by a licensed notary. Provenance documentation available on request. R.I.P. House · Chamber 0044 · Lisbon
        </div>
      </div>

      <Footer lang={lang} />
    </>
  );
}

// ── Individual listing card ───────────────────────────────────────────────
function MarketCard({ item, tm, fmt, borderLeft, enquired, onEnquire }) {
  const isReserved = item.status === 'reserved';
  const isSold = item.status === 'sold';
  const inactive = isReserved || isSold;

  return (
    <article style={{
      padding: '36px 28px 40px',
      borderLeft: borderLeft ? '1px solid var(--hairline)' : 'none',
      borderBottom: '1px solid var(--ink)',
      background: 'var(--paper)',
      opacity: isSold ? 0.5 : 1,
    }}>
      {/* Status + estate tag */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.28em', fontSize: 9 }}>
          {tm.estateOf} · {item.estate}
        </div>
        <div className="mono tiny upper" style={{
          letterSpacing: '0.22em', fontSize: 9,
          color: isReserved ? 'var(--muted)' : isSold ? 'var(--muted)' : 'var(--ice)',
        }}>
          {isReserved
            ? <><span style={{ display: 'inline-block', width: 6, height: 6, border: '1px solid var(--muted)', marginRight: 6, transform: 'translateY(-1px)' }} />{tm.reservedLabel}</>
            : isSold
            ? tm.sold
            : <><span style={{ display: 'inline-block', width: 6, height: 6, background: 'var(--frost)', marginRight: 6, transform: 'translateY(-1px)' }} />{tm.available}</>
          }
        </div>
      </div>

      {/* Visual */}
      <div style={{ position: 'relative', height: 260, marginBottom: 28, background: item.swatch[0], overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, rgba(255,255,255,0.10), transparent 50%, rgba(0,0,0,0.10))' }} />
        <svg viewBox="0 0 200 200" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          {item.glyph === 'circle'   && <circle   cx="100" cy="100" r="55"     fill="none" stroke={item.swatch[1]} strokeWidth="0.8" opacity="0.9" />}
          {item.glyph === 'square'   && <rect      x="50"  y="50"  width="100" height="100" fill="none" stroke={item.swatch[1]} strokeWidth="0.8" opacity="0.9" />}
          {item.glyph === 'triangle' && <polygon   points="100,42 160,154 40,154" fill="none" stroke={item.swatch[1]} strokeWidth="0.8" opacity="0.9" />}
        </svg>
        <div className="mono tiny upper" style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '8px 14px', background: 'rgba(0,0,0,0.42)',
          color: 'rgba(255,255,255,0.7)', letterSpacing: '0.22em', fontSize: 9,
        }}>
          {item.year} · {item.material}
        </div>
      </div>

      {/* Name + description */}
      <div className="display" style={{ fontSize: 22, lineHeight: 1.1, marginBottom: 12 }}>{item.name}</div>
      <div className="serif" style={{ fontSize: 13, lineHeight: 1.65, color: 'var(--ink-2)', fontWeight: 300, marginBottom: 24, fontStyle: 'italic' }}>
        {item.description}
      </div>

      {/* Curator note */}
      <div style={{ borderLeft: '2px solid var(--hairline)', paddingLeft: 14, marginBottom: 28 }}>
        <div className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.22em', marginBottom: 6, fontSize: 9 }}>{tm.noteLabel}</div>
        <div className="serif" style={{ fontSize: 12, lineHeight: 1.6, color: 'var(--muted)', fontWeight: 300, fontStyle: 'italic' }}>
          "{item.note}"
        </div>
      </div>

      {/* Proceeds + price */}
      <div style={{ borderTop: '1px solid var(--hairline)', paddingTop: 20, marginBottom: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em', fontSize: 9 }}>{tm.proceedsTo}</span>
          <span className="mono tiny upper" style={{ color: 'var(--ice)', letterSpacing: '0.18em', fontSize: 9 }}>
            {item.beneficiaryType === 'institution' ? tm.institution : tm.person}
          </span>
        </div>
        <div className="display" style={{ fontSize: 15, color: 'var(--ink-2)', marginBottom: 16, lineHeight: 1.2 }}>
          {item.beneficiary}
          <span className="serif" style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 300, fontStyle: 'italic', marginLeft: 8 }}>· {item.city}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div className="mono tiny upper" style={{ color: 'var(--muted)', letterSpacing: '0.22em', fontSize: 9, marginBottom: 4 }}>{tm.askingPrice}</div>
            <div className="display" style={{ fontSize: 28, letterSpacing: '-0.02em' }}>
              {item.currency} {fmt(item.price)}
            </div>
          </div>
          <div className="serif" style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 300, fontStyle: 'italic', textAlign: 'right', lineHeight: 1.5 }}>
            {item.currency} {fmt(Math.round(item.price * 0.85))}<br />
            <span style={{ fontSize: 10 }}>to beneficiary</span>
          </div>
        </div>
      </div>

      {/* CTA */}
      {!inactive && (
        <BarSubmit
          label={tm.enquireBtn}
          done={tm.enquireBusy}
          onClick={onEnquire}
        />
      )}
    </article>
  );
}

Object.assign(window, { Marketplace });
