// Directory + Winery profile
// Exports: window.Directory, window.WineryProfile

function Directory({ state, onNav }) {
  const D = window.TX_DATA;
  const [q, setQ] = React.useState('');
  const [ava, setAva] = React.useState('all');
  const [price, setPrice] = React.useState('all');
  const [dogs, setDogs] = React.useState(false);

  const filtered = D.wineries.filter(w => {
    if (q && !w.name.toLowerCase().includes(q.toLowerCase())) return false;
    if (ava !== 'all' && w.ava !== ava) return false;
    if (price !== 'all' && w.price !== price) return false;
    if (dogs && !w.dogFriendly) return false;
    return true;
  });

  return (
    <main className="container" style={{ paddingTop: 48, paddingBottom: 64 }}>
      <div className="section-label">The Directory</div>
      <h1 className="h1" style={{ maxWidth: 18 + 'ch', marginBottom: 16 }}>
        {D.wineries.length} wineries, hand-picked.
      </h1>
      <p className="lede" style={{ marginBottom: 40 }}>
        Wineries worth the drive — currently {D.wineries.length} curated listings.
        For the full universe of {D.stats.wineries}+ TABC-licensed wineries in Texas,{' '}
        <a onClick={() => onNav('database')} style={{ color: 'var(--accent)', cursor: 'pointer', textDecoration: 'underline' }}>
          see the Database
        </a>. Listings are independent; promoted placements are clearly marked.
      </p>

      <div style={{
        display: 'grid', gridTemplateColumns: '280px 1fr', gap: 40, alignItems: 'start',
      }}>
        {/* Filters */}
        <aside style={{ position: 'sticky', top: 80, borderTop: '2px solid var(--ink)', paddingTop: 20 }}>
          <FilterGroup label="Search">
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Winery name"
              style={fieldStyle} />
          </FilterGroup>

          <FilterGroup label="Region">
            <RadioList name="ava" value={ava} onChange={setAva}
              options={[{v:'all',l:'All regions'}, ...D.avas.slice(0,5).map(a => ({v:a.id, l:a.short}))]} />
          </FilterGroup>

          <FilterGroup label="Price">
            <RadioList name="price" value={price} onChange={setPrice}
              options={[{v:'all',l:'Any'},{v:'$',l:'$ · tasting $15–20'},{v:'$$',l:'$$ · $25–35'},{v:'$$$',l:'$$$ · $40+'}]} />
          </FilterGroup>

          <FilterGroup label="Amenities">
            <label style={checkRow}>
              <input type="checkbox" checked={dogs} onChange={e => setDogs(e.target.checked)} />
              <span>Dog-friendly</span>
            </label>
            <label style={checkRow}>
              <input type="checkbox" />
              <span>Food menu</span>
            </label>
            <label style={checkRow}>
              <input type="checkbox" />
              <span>Estate-grown only</span>
            </label>
            <label style={checkRow}>
              <input type="checkbox" />
              <span>Walk-ins welcome</span>
            </label>
          </FilterGroup>

          <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}
            onClick={() => { setQ(''); setAva('all'); setPrice('all'); setDogs(false); }}>
            Reset
          </button>
        </aside>

        {/* Results */}
        <div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            borderBottom: '1px solid var(--rule)', paddingBottom: 14, marginBottom: 8,
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-mute)' }}>
              {filtered.length} RESULTS
            </span>
            <select style={{ ...fieldStyle, width: 180, padding: '8px 12px' }}>
              <option>Sort: Alphabetical</option>
              <option>Founded (oldest)</option>
              <option>Nearest Fredericksburg</option>
            </select>
          </div>

          {filtered.map((w, i) => (
            <WineryRow key={w.id} w={w} onClick={() => onNav('winery', w.id)} promoted={i === 0} />
          ))}

          {filtered.length === 0 && (
            <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-mute)', fontFamily: 'var(--font-body)' }}>
              No wineries match those filters.
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

const fieldStyle = {
  width: '100%', padding: '10px 12px', fontSize: 13,
  border: '1px solid var(--rule)', borderRadius: 'var(--radius)',
  fontFamily: 'var(--font-ui)', background: 'var(--paper)', color: 'var(--ink)',
};
const checkRow = {
  display: 'flex', alignItems: 'center', gap: 10,
  padding: '6px 0', fontSize: 13, fontFamily: 'var(--font-body)', color: 'var(--ink-soft)',
  cursor: 'pointer',
};

function FilterGroup({ label, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-mute)', marginBottom: 10, fontWeight: 600 }}>
        {label}
      </div>
      {children}
    </div>
  );
}

function RadioList({ name, value, onChange, options }) {
  return (
    <div>
      {options.map(o => (
        <label key={o.v} style={checkRow}>
          <input type="radio" name={name} checked={value === o.v} onChange={() => onChange(o.v)} />
          <span>{o.l}</span>
        </label>
      ))}
    </div>
  );
}

function WineryRow({ w, onClick, promoted }) {
  const D = window.TX_DATA;
  const ava = D.avas.find(a => a.id === w.ava);
  return (
    <article onClick={onClick} style={{
      display: 'grid', gridTemplateColumns: '140px 1fr auto', gap: 24, alignItems: 'center',
      padding: '22px 0',
      borderBottom: '1px solid var(--rule)',
      cursor: 'pointer',
    }}>
      <window.Ph label="winery photo" aspect="4/3" />
      <div>
        {promoted && <span className="chip" style={{ background: 'var(--accent)', color: 'var(--paper)', marginBottom: 10 }}>Promoted</span>}
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 24, margin: '6px 0 6px', letterSpacing: '-0.015em' }}>{w.name}</h3>
        <div style={{ display: 'flex', gap: 16, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
          <span>{w.town.toUpperCase()}</span>
          <span>·</span>
          <span>{ava?.short.toUpperCase()} AVA</span>
          <span>·</span>
          <span>EST. {w.founded}</span>
          <span>·</span>
          <span>{w.price}</span>
        </div>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-soft)', fontFamily: 'var(--font-body)' }}>
          {w.focus}. {w.acres > 0 ? `${w.acres} estate acres.` : 'Sources from single-vineyard High Plains fruit.'}
        </p>
        <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
          <span className="chip">{w.tag}</span>
          {w.dogFriendly && <span className="chip">Dog-friendly</span>}
          {w.tasting && <span className="chip">Tasting room</span>}
        </div>
      </div>
      <button className="btn btn-ghost" style={{ padding: '10px 16px', fontSize: 11 }}>View →</button>
    </article>
  );
}

/* ========================================================== */
/* WineryProfile — parameterized by wineryId prop              */
/* Falls back to william-chris if no id passed (back compat)   */
/* ========================================================== */
function WineryProfile({ onNav, wineryId }) {
  const D = window.TX_DATA;
  // Look in curated wineries first; fall back to TX_PERMITS (the 809 unclaimed
  // TABC entries), mapping each permit into the winery-shape with safe defaults
  // so the rest of this component doesn't have to special-case stubs.
  const fromPermits = (window.TX_PERMITS || []).find(x => x.id === wineryId);
  const w = D.wineries.find(x => x.id === wineryId)
    || (fromPermits && {
         ...fromPermits,
         focus: 'Texas wine',
         acres: 0,
         tasting: '',
         dogFriendly: false,
         price: '$$',
         tag: '',
         bottles: [],
       })
    || D.wineries.find(x => x.id === 'william-chris');
  const ava = D.avas.find(a => a.id === w.ava);

  // Nearby wineries: same AVA, not self, up to 4
  const nearby = D.wineries.filter(x => x.ava === w.ava && x.id !== w.id).slice(0, 4);

  // Bottles from this producer (match producer name flexibly)
  const producerKey = w.name.replace(/\s+(Vineyards?|Winery|Cellars?|Estate|Family)$/i, '').trim();
  const bottles = D.bottles.filter(b =>
    b.producer.toLowerCase().includes(producerKey.toLowerCase()) ||
    producerKey.toLowerCase().includes(b.producer.toLowerCase().split(' ')[0])
  );

  // If no bottles match, fall back to a few representative ones so the
  // page never looks empty (clearly marked as editor's selection).
  const bottlesToShow = bottles.length > 0 ? bottles : D.bottles.slice(0, 2);
  const bottlesIsCurated = bottles.length === 0;

  const blurb = w.blurb ||
    `${w.name} sits in ${w.town}, ${ava?.short ? ava.short + ' AVA' : 'Texas'}. ` +
    `Founded in ${w.founded}, the focus is ${w.focus.toLowerCase()}.`;
  const firstSentence = blurb.split('. ')[0] + (blurb.includes('. ') ? '.' : '');

  return (
    <main>
      <div style={{ position: 'relative' }}>
        <window.Ph label={`hero · ${w.name.toLowerCase()} · winery façade or barrel room`} aspect="21/9" style={{ aspectRatio: 'auto', height: 420 }} />
      </div>

      <div className="container" style={{ marginTop: -60, position: 'relative' }}>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--rule)', padding: '40px 48px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <div className="section-label" style={{ marginBottom: 0 }}>Winery Profile</div>
            {!w.claimed && (
              <button className="chip"
                onClick={() => onNav('claim', w.id)}
                style={{ background: 'transparent', border: '1px solid var(--ink-mute)', color: 'var(--ink-mute)', cursor: 'pointer', padding: '4px 10px' }}>
                ◇ Claim this listing
              </button>
            )}
            {w.claimed && (
              <span className="chip" style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
                ◆ Verified
              </span>
            )}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 48, alignItems: 'end' }}>
            <div>
              <h1 className="h-display" style={{ fontSize: 'clamp(48px, 6vw, 88px)' }}>
                {w.name.split(' ').map((word, i, arr) => (
                  <React.Fragment key={i}>
                    {word}
                    {i === Math.floor(arr.length / 2) - 1 && arr.length > 2 ? <br/> : (i < arr.length - 1 ? ' ' : '')}
                  </React.Fragment>
                ))}
              </h1>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 18, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-mute)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                <span>{w.town.toUpperCase()}, TX</span><span>·</span>
                <span>{ava?.short} AVA</span><span>·</span>
                <span>EST. {w.founded}</span>
                {w.acres > 0 && (<><span>·</span><span>{w.acres} ACRES ESTATE</span></>)}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button className="btn">Book a tasting</button>
              <button className="btn btn-ghost">Directions</button>
            </div>
          </div>
        </div>
      </div>

      <div className="container" style={{ paddingTop: 56, paddingBottom: 64 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 56 }}>
          <div>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 22, lineHeight: 1.45, color: 'var(--ink)', fontStyle: 'italic', marginTop: 0 }}>
              "{firstSentence}"
            </p>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.65, color: 'var(--ink-soft)' }}>
              <p>{blurb}</p>
              {!w.blurb && (
                <p style={{ fontSize: 13, color: 'var(--ink-mute)', fontStyle: 'italic', marginTop: 24, padding: 16, background: 'var(--chip)', borderLeft: '2px solid var(--accent)' }}>
                  Editor's note: This winery hasn't claimed its listing yet. The narrative above is a placeholder. <a href="#" onClick={(e) => { e.preventDefault(); onNav('claim', w.id); }} style={{ color: 'var(--accent)', textDecoration: 'underline' }}>If this is your winery, claim the page</a> to publish a full profile.
                </p>
              )}
            </div>

            <h3 className="h2" style={{ marginTop: 48, marginBottom: 18 }}>
              {bottlesIsCurated ? "Editor's selection from the region" : "The bottles to know"}
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20 }}>
              {bottlesToShow.slice(0, 4).map(b => (
                <article key={b.id} style={{ display: 'grid', gridTemplateColumns: '60px 1fr', gap: 16, padding: 18, border: '1px solid var(--rule)', background: 'var(--paper)' }}>
                  <div style={{
                    width: 60, height: 140, background: 'var(--accent)',
                    borderRadius: '4px 4px 2px 2px', alignSelf: 'start',
                    position: 'relative',
                    boxShadow: 'inset 0 0 0 3px rgba(0,0,0,0.15)',
                  }}>
                    <div style={{ position: 'absolute', top: '35%', left: 2, right: 2, bottom: '25%', background: 'var(--paper)', fontSize: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', color: 'var(--ink)', textAlign: 'center', padding: 2 }}>
                      {b.producer.split(' ').map(s => s[0]).join('').slice(0, 2)}
                    </div>
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{b.vintage} · {b.rating} PTS</div>
                    <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 18, margin: '4px 0 6px' }}>{b.name}</h4>
                    <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: '0 0 10px', fontFamily: 'var(--font-body)', lineHeight: 1.45 }}>{b.notes}</p>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>${b.price}</span>
                      <button className="btn" style={{ padding: '6px 14px', fontSize: 10 }}>Add</button>
                    </div>
                  </div>
                </article>
              ))}
            </div>

            <h3 className="h2" style={{ marginTop: 48, marginBottom: 18 }}>Tasting room</h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <window.Ph label="tasting room interior" aspect="4/3" />
              <window.Ph label="barrel room" aspect="4/3" />
            </div>
          </div>

          {/* Sidebar */}
          <aside>
            <div style={{ padding: 28, border: '1px solid var(--ink)', background: 'var(--paper)' }}>
              <h4 style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-mute)', margin: '0 0 16px' }}>Plan a visit</h4>
              <dl style={{ margin: 0, fontFamily: 'var(--font-body)', fontSize: 14 }}>
                {[
                  ['Town', `${w.town}, TX`],
                  ['AVA', ava?.short],
                  ['Tasting', w.price === '$' ? '$15–20' : w.price === '$$' ? '$25–35' : '$40+'],
                  ['Reservations', 'Recommended'],
                  ['Kids', 'Welcome'],
                  ['Dogs', w.dogFriendly ? 'Outdoor area' : 'Not on premises'],
                ].map(([k,v]) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px dotted var(--rule)' }}>
                    <dt style={{ color: 'var(--ink-mute)' }}>{k}</dt>
                    <dd style={{ margin: 0, color: 'var(--ink)', fontWeight: 500, textAlign: 'right' }}>{v}</dd>
                  </div>
                ))}
              </dl>
              <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 18 }}>Reserve tasting</button>
            </div>

            {nearby.length > 0 && (
              <div style={{ marginTop: 24, padding: 24, background: 'var(--chip)' }}>
                <div className="kicker" style={{ marginBottom: 10 }}>Nearby in {ava?.short}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-soft)', lineHeight: 1.8 }}>
                  {nearby.map(n => (
                    <div key={n.id}
                      onClick={() => onNav('winery', n.id)}
                      style={{ cursor: 'pointer', padding: '2px 0' }}>
                      {n.name} <span style={{ color: 'var(--ink-mute)' }}>· {n.town}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </aside>
        </div>
      </div>
    </main>
  );
}

window.Directory = Directory;
window.WineryProfile = WineryProfile;
