/* AIWine — EXPLORE */
function WineRow({ w, onWine, sub }) {
  return (
    <div onClick={() => onWine(w)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 0', borderTop: '1px solid var(--line-soft)', cursor: 'pointer' }}>
      <div style={{ width: 30, flex: 'none' }}><Bottle wine={w} h={62} glow={false} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ ...S.serif, fontSize: 18, lineHeight: 1.2, color: 'var(--ink)' }}>{w.name}</div>
        <div style={{ ...S.sans, fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{w.winery}{w.vintage ? ' · ' + w.vintage : ''}{w.region ? ' · ' + w.region : ''}</div>
        {sub && <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 6, lineHeight: 1.45 }}>{sub}</div>}
      </div>
      <div style={{ textAlign: 'right', flex: 'none' }}>
        <Match v={w.match} size={38} />
        {w.price > 0 && <div style={{ marginTop: 6 }}><Price v={w.price} size={13} /></div>}
      </div>
    </div>
  );
}

function ExploreIndex({ open, onRegion, onAsk, onWine }) {
  const [q, setQ] = React.useState('');
  const hits = q.trim().length > 1 ? AIW.wines.filter(w => (w.winery + ' ' + w.name + ' ' + w.variety + ' ' + w.region).toLowerCase().includes(q.toLowerCase())).slice(0, 8) : [];
  const regions = AIW.REGIONS.filter(r => AIW.wines.some(w => (w.region || '').includes(r.name))).concat(AIW.REGIONS.filter(r => !AIW.wines.some(w => (w.region || '').includes(r.name))));
  return (
    <Screen top={0} pad={0}>
      <div style={{ position: 'relative', height: 380 }}>
        <img src={AIW.IMG + 'hero-vineyard.jpg'} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(20,12,8,.55) 0%, rgba(20,12,8,.18) 40%, var(--bg) 99%)' }} />
        <div style={{ position: 'absolute', left: 22, right: 22, bottom: 26 }}>
          <Eyebrow color="rgba(244,239,229,.8)">Explore</Eyebrow>
          <div style={{ ...S.serif, fontSize: 40, lineHeight: 1.02, color: 'var(--ink)', marginTop: 10, textShadow: '0 1px 0 rgba(255,255,255,.4)' }}>What are you<br /><i>looking for?</i></div>
          <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--card-2)', border: '1px solid var(--line)', borderRadius: 100, padding: '13px 18px', boxShadow: '0 8px 20px rgba(27,20,16,.10)' }}>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search wine, winery, grape, region…" style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', ...S.sans, fontSize: 13.5, color: 'var(--ink)' }} />
            <button onClick={() => onAsk(q || '')} style={{ ...S.mono, fontSize: 9, color: 'var(--claret)', background: 'none', border: 'none', cursor: 'pointer' }}>Or ask</button>
          </div>
        </div>
      </div>

      <div style={{ padding: '10px 22px 0' }}>
        {hits.length > 0 && (
          <div style={{ marginBottom: 30 }}>
            <Eyebrow style={{ marginBottom: 4 }}>{hits.length} match{hits.length === 1 ? '' : 'es'}</Eyebrow>
            {hits.map(w => <WineRow key={w.id} w={w} onWine={onWine} />)}
          </div>
        )}

        <SectionHead eyebrow="By mood" title="How do you want to feel?" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {AIW.MOODS.map((m, i) => (
            <div key={m.n} onClick={() => open({ kind: 'mood', value: m.n })} style={{ gridColumn: i === 0 ? 'span 2' : 'span 1', borderRadius: 16, border: '1px solid var(--line)', background: 'var(--card)', padding: 16, cursor: 'pointer', minHeight: i === 0 ? 108 : 96, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: ['#8FA88C', '#8C4A2F', '#B9A6C4', '#3A0E18', '#E2C98C', '#6E6446', '#C9A45A'][i], opacity: .85 }} />
              <div>
                <div style={{ ...S.serif, fontSize: i === 0 ? 24 : 19, lineHeight: 1.1, color: 'var(--ink)' }}>{m.n}</div>
                <div style={{ ...S.sans, fontSize: 11.5, color: 'var(--muted)', marginTop: 5 }}>{m.d}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ height: 34 }} />
        <SectionHead eyebrow="By occasion" title="What’s the evening?" />
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
          {AIW.OCCASIONS.map(o => <Chip key={o} onClick={() => open({ kind: 'occasion', value: o })}>{o}</Chip>)}
        </div>

        <div style={{ height: 34 }} />
        <SectionHead eyebrow="By food" title="What are you eating?" />
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
          {AIW.FOODS.map(f => <Chip key={f} onClick={() => open({ kind: 'food', value: f })}>{f}</Chip>)}
        </div>
        <div onClick={() => onAsk('I’m making lamb with rosemary and garlic.')} style={{ marginTop: 14, borderRadius: 16, border: '1px dashed var(--line)', padding: 16, cursor: 'pointer', display: 'flex', gap: 12, alignItems: 'center' }}>
          <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--claret)', color: 'var(--bone)', display: 'flex', alignItems: 'center', justifyContent: 'center', ...S.serif, fontSize: 14, flex: 'none' }}>A</div>
          <div style={{ ...S.serif, fontSize: 17, fontStyle: 'italic', color: 'var(--ink-soft)' }}>“I’m making lamb with rosemary and garlic.”</div>
        </div>
      </div>

      <div style={{ height: 38 }} />
      <div style={{ padding: '0 22px' }}><SectionHead eyebrow="By place" title="Wine country" /></div>
      <Rail>
        {regions.map(r => {
          const n = AIW.wines.filter(w => (w.region || '').includes(r.name)).length;
          return (
            <div key={r.slug} onClick={() => onRegion(r)} style={{ flex: 'none', width: 220, scrollSnapAlign: 'start', cursor: 'pointer' }}>
              <div style={{ position: 'relative', height: 280, borderRadius: 18, overflow: 'hidden' }}>
                <img src={r.img} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(20,12,8,.85) 8%, transparent 60%)' }} />
                {n > 0 && <div style={{ position: 'absolute', top: 12, right: 12, ...S.mono, fontSize: 8, color: 'var(--bone)', border: '1px solid rgba(244,239,229,.5)', borderRadius: 100, padding: '4px 8px' }}>{n} wines</div>}
                <div style={{ position: 'absolute', left: 16, right: 16, bottom: 16 }}>
                  <div style={{ ...S.serif, fontSize: 24, color: 'var(--bone)', lineHeight: 1.1 }}>{r.name}</div>
                  <div style={{ ...S.mono, fontSize: 8.5, color: 'var(--brass-soft)', marginTop: 6 }}>{r.grape}</div>
                </div>
              </div>
            </div>
          );
        })}
      </Rail>
      <div style={{ height: 30 }} />
    </Screen>
  );
}

function ExploreResults({ q, onBack, onWine, onAsk }) {
  const test = w => q.kind === 'mood' ? (w.mood || []).includes(q.value)
    : q.kind === 'occasion' ? AIW.matchesOccasion(w, q.value)
      : AIW.matchesFood(w, q.value);
  const list = AIW.wines.filter(test).sort((a, b) => b.match - a.match);
  const top = list[0];
  return (
    <Screen top={104}>
      <BackBar onBack={onBack} />
      <Eyebrow>{q.kind === 'food' ? 'Wine for' : q.kind}</Eyebrow>
      <div style={{ ...S.serif, fontSize: 34, lineHeight: 1.05, marginTop: 10, color: 'var(--ink)' }}>{q.value}</div>
      {!top ? (
        <div style={{ marginTop: 26 }}>
          <div style={{ ...S.sans, fontSize: 14, lineHeight: 1.6, color: 'var(--ink-soft)' }}>Nothing in the library fits that yet — the wineries publishing here don’t currently have one. Ask me and I’ll find the nearest thing.</div>
          <div style={{ marginTop: 16 }}><Btn onClick={() => onAsk('What’s the closest thing to ' + q.value + '?')}>Ask AIWine</Btn></div>
        </div>
      ) : (
        <React.Fragment>
          <div style={{ marginTop: 22, borderRadius: 18, background: 'var(--ink)', padding: 20 }}>
            <Eyebrow color="var(--brass-soft)">I’d choose this one</Eyebrow>
            <div style={{ display: 'flex', gap: 16, marginTop: 14, alignItems: 'center' }}>
              <div style={{ width: 46, flex: 'none' }}><Bottle wine={top} h={96} glow={false} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ ...S.serif, fontSize: 22, lineHeight: 1.15, color: 'var(--bone)' }}>{top.name}</div>
                <div style={{ ...S.sans, fontSize: 12, color: 'rgba(244,239,229,.6)', marginTop: 3 }}>{top.winery}{top.vintage ? ' · ' + top.vintage : ''}</div>
                <div style={{ ...S.sans, fontSize: 12.5, lineHeight: 1.5, color: 'rgba(244,239,229,.8)', marginTop: 9 }}>{top.why}</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 9, marginTop: 18 }}>
              <Btn small kind="gilt" onClick={() => onWine(top)}>Explore wine</Btn>
              <Btn small kind="onDark" onClick={() => onAsk('Why this one for ' + q.value + '?')}>Ask why</Btn>
            </div>
          </div>
          <div style={{ height: 26 }} />
          <Eyebrow style={{ marginBottom: 4 }}>{list.length} wines · sorted by your taste</Eyebrow>
          {list.map(w => <WineRow key={w.id} w={w} onWine={onWine} />)}
        </React.Fragment>
      )}
    </Screen>
  );
}

function RegionDetail({ r, onBack, onWine, onAsk }) {
  const wines = AIW.wines.filter(w => (w.region || '').includes(r.name)).sort((a, b) => b.match - a.match);
  const wineries = [...new Set(wines.map(w => w.winery))];
  return (
    <Screen top={0} pad={0}>
      <BackBar onBack={onBack} dark />
      <div style={{ position: 'relative', height: 420 }}>
        <img src={r.img} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(20,12,8,.5) 0%, rgba(20,12,8,.1) 45%, var(--bg) 99%)' }} />
        <div style={{ position: 'absolute', left: 22, right: 22, bottom: 24 }}>
          <Eyebrow color="var(--claret)">{r.grape} country</Eyebrow>
          <div style={{ ...S.serif, fontSize: 44, lineHeight: 1, color: 'var(--ink)', marginTop: 8 }}>{r.name}</div>
        </div>
      </div>
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{ ...S.serif, fontSize: 21, fontStyle: 'italic', lineHeight: 1.4, color: 'var(--ink-soft)' }}>{r.line}</div>
        <div style={{ display: 'flex', gap: 26, marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
          {[['Signature', r.grape], ['Wineries here', String(wineries.length)], ['Wines', String(wines.length)]].map(([k, v]) => (
            <div key={k}><Eyebrow>{k}</Eyebrow><div style={{ ...S.serif, fontSize: 19, marginTop: 6, color: 'var(--ink)' }}>{v}</div></div>
          ))}
        </div>
        <div onClick={() => onAsk('I’m spending Saturday in ' + r.name + '. What should I do?')} style={{ marginTop: 24, borderRadius: 18, background: 'linear-gradient(150deg,#4A1520,var(--claret-deep))', padding: 20, cursor: 'pointer' }}>
          <Eyebrow color="var(--brass-soft)">Wine travel</Eyebrow>
          <div style={{ ...S.serif, fontSize: 24, color: 'var(--bone)', marginTop: 10, lineHeight: 1.15 }}>Build me a Saturday in {r.name}</div>
          <div style={{ ...S.sans, fontSize: 12.5, color: 'rgba(244,239,229,.7)', marginTop: 8 }}>A personal itinerary — cellar doors, lunch, and what to taste at each.</div>
        </div>
        <div style={{ height: 32 }} />
        {wines.length ? (
          <React.Fragment>
            <SectionHead eyebrow="From here" title="Wines to start with" />
            {wines.slice(0, 8).map(w => <WineRow key={w.id} w={w} onWine={onWine} />)}
          </React.Fragment>
        ) : (
          <div style={{ borderRadius: 16, border: '1px dashed var(--line)', padding: 20 }}>
            <div style={{ ...S.serif, fontSize: 20, color: 'var(--ink)' }}>No {r.name} wines in the library yet.</div>
            <div style={{ ...S.sans, fontSize: 12.5, color: 'var(--muted)', marginTop: 8, lineHeight: 1.5 }}>As wineries from this region publish, they’ll appear here automatically.</div>
          </div>
        )}
        <div style={{ height: 20 }} />
      </div>
    </Screen>
  );
}

function Explore(props) {
  const [q, setQ] = React.useState(null);
  const [region, setRegion] = React.useState(null);
  if (region) return <RegionDetail r={region} onBack={() => setRegion(null)} onWine={props.onWine} onAsk={props.onAsk} />;
  if (q) return <ExploreResults q={q} onBack={() => setQ(null)} onWine={props.onWine} onAsk={props.onAsk} />;
  return <ExploreIndex open={setQ} onWine={props.onWine} onRegion={setRegion} onAsk={props.onAsk} />;
}

Object.assign(window, { Explore, WineRow });
