// Wines of Texas — Database page
// Exports: window.Database
//
// Renders all 809 unclaimed TABC G-permit holders as a thin phonebook view.
// Clicking a row routes to WineryProfile (which falls back to permits when
// the winery isn't in the curated TX_DATA.wineries array).
//
// This is the comprehensive index that backstops the curated Directory.
// Honest about scale; visually clearly LESS rich than the Directory, which
// creates the upgrade pressure when an unclaimed winery owner finds their page.

function Database({ onNav }) {
  const D = window.TX_DATA;
  const P = window.TX_PERMITS || [];
  const [q, setQ] = React.useState('');
  const [letter, setLetter] = React.useState('all');
  const [region, setRegion] = React.useState('all');
  const [page, setPage] = React.useState(0);
  const PER_PAGE = 50;

  // Reset page when filters change
  React.useEffect(() => { setPage(0); }, [q, letter, region]);

  // Filter
  const filtered = P.filter(p => {
    if (q) {
      const needle = q.toLowerCase();
      if (!p.name.toLowerCase().includes(needle) &&
          !p.town.toLowerCase().includes(needle) &&
          !p.county.toLowerCase().includes(needle)) return false;
    }
    if (letter !== 'all') {
      const first = (p.name[0] || '').toUpperCase();
      if (letter === '#') {
        if (/[A-Z]/.test(first)) return false;
      } else if (first !== letter) return false;
    }
    if (region !== 'all') {
      if (p.ava !== region && p.region !== region) return false;
    }
    return true;
  });

  const pageCount = Math.max(1, Math.ceil(filtered.length / PER_PAGE));
  const start = page * PER_PAGE;
  const slice = filtered.slice(start, start + PER_PAGE);

  // Region options: AVAs + non-AVA regions present in the data
  const regionOptions = React.useMemo(() => {
    const fromAva = D.avas.map(a => ({ v: a.id, l: a.short }));
    const fromRegion = Array.from(new Set(P.map(p => p.region).filter(Boolean)));
    return [
      { v: 'all', l: 'All Texas' },
      ...fromAva,
      ...fromRegion.map(r => ({ v: r, l: r })),
    ];
  }, [D, P]);

  return (
    <main className="container" style={{ paddingTop: 48, paddingBottom: 64 }}>
      <div className="section-label">The Database</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 56, alignItems: 'end', marginBottom: 40 }}>
        <h1 className="h-display" style={{ fontSize: 'clamp(44px, 6vw, 92px)' }}>
          Every Texas winery,<br/>indexed.
        </h1>
        <p className="lede">
          {D.stats.wineries.toLocaleString()} active TABC G-permits, as of May 2026.
          The complete legal universe of bonded Texas wineries — including
          urban tasting rooms, make-your-own producers, and importers.{' '}
          <a onClick={() => onNav('directory')} style={{ color: 'var(--accent)', cursor: 'pointer', textDecoration: 'underline' }}>
            Looking for places to visit? Try our curated Directory.
          </a>
        </p>
      </div>

      {/* Search + region row */}
      <div style={{
        display: 'grid', gridTemplateColumns: '2fr 1fr auto', gap: 16,
        padding: '20px 24px', background: 'var(--paper)',
        border: '1px solid var(--rule)', marginBottom: 24, alignItems: 'center',
      }}>
        <div>
          <div className="kicker" style={{ marginBottom: 6 }}>Search</div>
          <input value={q} onChange={e => setQ(e.target.value)}
            placeholder="Winery name, town, or county"
            style={{
              width: '100%', padding: '10px 12px', fontSize: 14,
              border: '1px solid var(--rule)', borderRadius: 'var(--radius)',
              fontFamily: 'var(--font-ui)', background: 'var(--page-bg)',
            }} />
        </div>
        <div>
          <div className="kicker" style={{ marginBottom: 6 }}>Region</div>
          <select value={region} onChange={e => setRegion(e.target.value)}
            style={{
              width: '100%', padding: '10px 12px', fontSize: 14,
              border: '1px solid var(--rule)', borderRadius: 'var(--radius)',
              fontFamily: 'var(--font-ui)', background: 'var(--page-bg)',
            }}>
            {regionOptions.map(o => (
              <option key={o.v} value={o.v}>{o.l}</option>
            ))}
          </select>
        </div>
        <button className="btn btn-ghost"
          style={{ padding: '10px 14px', alignSelf: 'end', height: 39 }}
          onClick={() => { setQ(''); setLetter('all'); setRegion('all'); }}>
          Reset
        </button>
      </div>

      {/* Letter index */}
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 24,
        padding: '14px 16px', borderTop: '1px solid var(--rule)',
        borderBottom: '1px solid var(--rule)',
      }}>
        <span className="kicker" style={{ marginRight: 12, alignSelf: 'center' }}>Jump to</span>
        {['all', '#', ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')].map(L => (
          <button key={L}
            onClick={() => setLetter(L)}
            style={{
              padding: '4px 9px', fontSize: 12,
              fontFamily: 'var(--font-mono)', fontWeight: 600,
              border: '1px solid ' + (letter === L ? 'var(--ink)' : 'transparent'),
              background: letter === L ? 'var(--ink)' : 'transparent',
              color: letter === L ? 'var(--paper)' : 'var(--ink-soft)',
              cursor: 'pointer', borderRadius: 'var(--radius)',
            }}>
            {L === 'all' ? 'ALL' : L}
          </button>
        ))}
      </div>

      {/* Result count + pagination top */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '12px 0', marginBottom: 8,
      }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-mute)', letterSpacing: '0.08em' }}>
          {filtered.length.toLocaleString()} RESULTS
          {filtered.length > PER_PAGE && (
            <> · SHOWING {start + 1}–{Math.min(start + PER_PAGE, filtered.length)}</>
          )}
        </span>
        {pageCount > 1 && <Pager page={page} pageCount={pageCount} onPage={setPage} />}
      </div>

      {/* Table */}
      <table style={{
        width: '100%', borderCollapse: 'collapse',
        fontFamily: 'var(--font-body)', fontSize: 14,
        background: 'var(--paper)', border: '1px solid var(--rule)',
      }}>
        <thead>
          <tr style={{ borderBottom: '2px solid var(--ink)' }}>
            {['Winery', 'Town', 'County', 'AVA / Region', 'Permit Year', ''].map((h, i) => (
              <th key={h} style={{
                textAlign: 'left', padding: '14px 14px',
                fontFamily: 'var(--font-ui)', fontSize: 10,
                letterSpacing: '0.14em', textTransform: 'uppercase',
                color: 'var(--ink-mute)', fontWeight: 600,
                width: i === 0 ? '32%' : (i === 5 ? 80 : 'auto'),
              }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {slice.map(p => {
            const ava = p.ava ? D.avas.find(a => a.id === p.ava) : null;
            const regionLabel = ava?.short || p.region || '—';
            return (
              <tr key={p.id}
                onClick={() => onNav('winery', p.id)}
                style={{ borderBottom: '1px solid var(--rule)', cursor: 'pointer' }}>
                <td style={{ padding: '14px 14px' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500 }}>{p.name}</div>
                  {p.owner && p.owner.toUpperCase() !== p.name.toUpperCase() && (
                    <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>
                      {p.owner}
                    </div>
                  )}
                </td>
                <td style={{ padding: '14px 14px', color: 'var(--ink-soft)' }}>{p.town}</td>
                <td style={{ padding: '14px 14px', color: 'var(--ink-soft)' }}>{p.county}</td>
                <td style={{ padding: '14px 14px', color: 'var(--ink-soft)' }}>{regionLabel}</td>
                <td style={{ padding: '14px 14px', fontFamily: 'var(--font-mono)', color: 'var(--ink-soft)', fontSize: 12 }}>
                  {p.founded || '—'}
                </td>
                <td style={{ padding: '14px 14px' }}>
                  <span style={{
                    display: 'inline-block', padding: '3px 8px',
                    fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.12em',
                    color: 'var(--ink-mute)', border: '1px solid var(--rule)',
                    borderRadius: 99, whiteSpace: 'nowrap',
                  }}>
                    ◇ UNCLAIMED
                  </span>
                </td>
              </tr>
            );
          })}
          {slice.length === 0 && (
            <tr>
              <td colSpan={6} style={{ padding: 48, textAlign: 'center', color: 'var(--ink-mute)', fontFamily: 'var(--font-body)' }}>
                No permits match those filters.
              </td>
            </tr>
          )}
        </tbody>
      </table>

      {/* Pagination bottom */}
      {pageCount > 1 && (
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 32 }}>
          <Pager page={page} pageCount={pageCount} onPage={setPage} />
        </div>
      )}

      {/* Footer note */}
      <div style={{
        marginTop: 56, padding: 28, background: 'var(--chip)',
        display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center',
      }}>
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>About this index</div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.6, color: 'var(--ink-soft)', margin: 0 }}>
            Sourced directly from the Texas Alcoholic Beverage Commission G-permit roster, May 2026.
            Not every entry has a public-facing tasting room — some are urban wine bars,
            make-your-own-wine operations, or producers without public premises.
            If you're a winery owner and want to replace your auto-generated listing
            with your real story, photos, and contact info,{' '}
            <a onClick={() => onNav('plans')} style={{ color: 'var(--accent)', cursor: 'pointer', textDecoration: 'underline' }}>
              see our listing plans
            </a>.
          </p>
        </div>
        <button className="btn" onClick={() => onNav('plans')}>
          Claim your listing →
        </button>
      </div>
    </main>
  );
}

function Pager({ page, pageCount, onPage }) {
  // Show first, last, current, and neighbors
  const pages = [];
  const window2 = 2;
  for (let i = 0; i < pageCount; i++) {
    if (i === 0 || i === pageCount - 1 || Math.abs(i - page) <= window2) {
      pages.push(i);
    } else if (pages[pages.length - 1] !== '…') {
      pages.push('…');
    }
  }
  return (
    <div style={{ display: 'flex', gap: 4, fontFamily: 'var(--font-mono)', fontSize: 12 }}>
      <button onClick={() => onPage(Math.max(0, page - 1))}
        disabled={page === 0}
        style={pagerBtnStyle(false)}>‹</button>
      {pages.map((p, i) => p === '…' ? (
        <span key={i} style={{ padding: '6px 6px', color: 'var(--ink-mute)' }}>…</span>
      ) : (
        <button key={i} onClick={() => onPage(p)}
          style={pagerBtnStyle(p === page)}>
          {p + 1}
        </button>
      ))}
      <button onClick={() => onPage(Math.min(pageCount - 1, page + 1))}
        disabled={page === pageCount - 1}
        style={pagerBtnStyle(false)}>›</button>
    </div>
  );
}

function pagerBtnStyle(active) {
  return {
    minWidth: 30, padding: '6px 9px',
    border: '1px solid ' + (active ? 'var(--ink)' : 'var(--rule)'),
    background: active ? 'var(--ink)' : 'var(--paper)',
    color: active ? 'var(--paper)' : 'var(--ink-soft)',
    cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 12,
    borderRadius: 'var(--radius)',
  };
}

window.Database = Database;
