// Sold archive — header stats + table + gallery

const SoldPage = ({ showToast }) => {
  useLucide();
  const [view, setView] = React.useState('gallery');
  const [yearFilter, setYearFilter] = React.useState('all');

  const filtered = SITE_DATA.sold.filter(s => {
    if (yearFilter === 'all') return true;
    return (s.soldDate || '').startsWith(yearFilter);
  });

  const totalSold = SITE_DATA.sold.length;
  const totalValue = SITE_DATA.sold.reduce((a, b) => a + b.soldPrice, 0);
  // Days-on-market and ask price aren't always available (e.g. rew-scraped sales).
  // Compute over just the rows that have them, and show "—" when there's nothing.
  const domItems = SITE_DATA.sold.filter(s => s.daysOnMarket != null);
  const avgDays = domItems.length ? Math.round(domItems.reduce((a, b) => a + b.daysOnMarket, 0) / domItems.length) : null;
  const askItems = SITE_DATA.sold.filter(s => s.askPrice && s.askPrice !== s.soldPrice);
  const overAsk = SITE_DATA.sold.filter(s => s.soldPrice > s.askPrice).length;
  const overAskPct = askItems.length ? Math.round((overAsk / totalSold) * 100) : null;

  return (
    <div className="page">
      <div className="page-head container">
        <span className="eyebrow">Closed transactions</span>
        <h1 style={{ marginTop: 14 }}>Sold properties</h1>
        <p className="lead">Twenty years of negotiated outcomes. The detail page for each sale shows the days on market, the gap to ask, and what made the property move. Browse the highlights below — the full archive is available on request.</p>
      </div>

      {/* Stats strip */}
      <section className="section-tight container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, padding: '32px 0', borderBottom: '1px solid var(--line)' }}>
          <div>
            <span className="serif" style={{ fontSize: 'clamp(36px, 4vw, 56px)', display: 'block', fontWeight: 300 }}>{totalSold}+</span>
            <span className="eyebrow" style={{ display: 'block', marginTop: 6 }}>Recent sales shown</span>
          </div>
          <div>
            <span className="serif" style={{ fontSize: 'clamp(36px, 4vw, 56px)', display: 'block', fontWeight: 300 }}>${(totalValue / 1_000_000).toFixed(1)}M</span>
            <span className="eyebrow" style={{ display: 'block', marginTop: 6 }}>Combined sale value</span>
          </div>
          <div>
            <span className="serif" style={{ fontSize: 'clamp(36px, 4vw, 56px)', display: 'block', fontWeight: 300 }}>{avgDays != null ? avgDays : '—'}</span>
            <span className="eyebrow" style={{ display: 'block', marginTop: 6 }}>Avg days on market</span>
          </div>
          <div>
            <span className="serif" style={{ fontSize: 'clamp(36px, 4vw, 56px)', display: 'block', fontWeight: 300 }}>{overAskPct != null ? overAskPct + '%' : '—'}</span>
            <span className="eyebrow" style={{ display: 'block', marginTop: 6 }}>Sold at or over ask</span>
          </div>
        </div>
      </section>

      <section className="section-tight container">
        <div className="filter-bar">
          <span className="eyebrow" style={{ marginRight: 8 }}>Filter by year</span>
          <button className={`filter-chip ${yearFilter === 'all' ? 'active' : ''}`} onClick={() => setYearFilter('all')}>All</button>
          <button className={`filter-chip ${yearFilter === '2025' ? 'active' : ''}`} onClick={() => setYearFilter('2025')}>2025</button>
          <button className={`filter-chip ${yearFilter === '2024' ? 'active' : ''}`} onClick={() => setYearFilter('2024')}>2024</button>
          <span className="filter-results">{filtered.length} sales</span>
          <div className="view-toggle">
            <button className={view === 'gallery' ? 'active' : ''} onClick={() => setView('gallery')}>
              <Icon name="grid-3x3" size={14} /> Gallery
            </button>
            <button className={view === 'table' ? 'active' : ''} onClick={() => setView('table')}>
              <Icon name="list" size={14} /> Table
            </button>
          </div>
        </div>

        {view === 'gallery' && (
          <div className="sold-grid">
            {filtered.map(s => (
              <SoldTile key={s.id} item={s} onClick={() => showToast(s.daysOnMarket != null ? `${s.address} — sold ${formatFullPrice(s.soldPrice)} in ${s.daysOnMarket} days` : `${s.address} — sold ${formatFullPrice(s.soldPrice)}`)} />
            ))}
          </div>
        )}

        {view === 'table' && (
          <div className="sold-table">
            <div className="row head">
              <span>Property</span>
              <span>Neighbourhood</span>
              <span>Sold</span>
              <span>Specs</span>
              <span>DOM</span>
              <span>Date</span>
            </div>
            {filtered.map(s => {
              const overAsk = s.soldPrice - s.askPrice;
              const overAskPct = ((overAsk / s.askPrice) * 100).toFixed(1);
              return (
                <div className="row" key={s.id}>
                  <div className="addr">{s.address}<div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 400 }}>{s.city}</div></div>
                  <span>{s.neighbourhood}</span>
                  <span>
                    <span className="price">{formatFullPrice(s.soldPrice)}</span>
                    {overAsk > 0 && <div className="over-ask">+{overAskPct}% over ask</div>}
                    {overAsk < 0 && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{overAskPct}% under ask</div>}
                  </span>
                  <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{s.beds}bd · {s.baths}ba · {s.sqft.toLocaleString()} sf</span>
                  <span>{s.daysOnMarket != null ? s.daysOnMarket + 'd' : '—'}</span>
                  <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{s.soldDate ? new Date(s.soldDate).toLocaleDateString('en-CA', { month: 'short', year: 'numeric' }) : '—'}</span>
                </div>
              );
            })}
          </div>
        )}
      </section>
    </div>
  );
};
window.SoldPage = SoldPage;
