/* Home + Tasting Notes list + Detail */

const { useState: uS, useEffect: uE, useMemo: uM } = React;

function getNoteText(note, lang) {
  // returns { en, cn } - using translations.js when available, falling back
  const tr = window.NOTE_TRANSLATIONS[note.id];
  const raw = (note.notes || '').trim();
  if (tr) return tr;
  // No curated translation — detect language of raw and only fill that side
  if (window.fmt.hasCN(raw) && !window.fmt.hasEN(raw)) {
    return { cn: raw, en: '' };
  }
  if (window.fmt.hasEN(raw) && !window.fmt.hasCN(raw)) {
    return { en: raw, cn: '' };
  }
  return { en: raw, cn: raw };
}

/* ============ HOME ============ */

// Pull quote helper — take first 1–2 sentences worth, max 280 chars
function pullQuote(text, max = 280) {
  if (!text) return '';
  const t = text.replace(/\s+/g, ' ').trim();
  if (t.length <= max) return t;
  // try sentence boundary
  const slice = t.slice(0, max);
  const lastPeriod = Math.max(slice.lastIndexOf('. '), slice.lastIndexOf('.”'), slice.lastIndexOf('。'));
  if (lastPeriod > max * 0.55) return slice.slice(0, lastPeriod + 1);
  return slice.replace(/\s+\S*$/, '') + '…';
}

function Home({ lang, data, setRoute }) {
  const sortedNotes = uM(() => [...data.tastingNotes].sort((a,b)=>{
    const da = window.fmt.parseDate(a.tastingDate)?.getTime() || 0;
    const db = window.fmt.parseDate(b.tastingDate)?.getTime() || 0;
    return db - da;
  }), [data]);

  // Featured note: most recent loved + 92+, else most recent loved, else most recent 92+, else most recent
  const featuredNote = uM(() => {
    const lovedHigh = sortedNotes.find(n => n.fLikeIt && (n.rating || 0) >= 92);
    if (lovedHigh) return lovedHigh;
    const loved = sortedNotes.find(n => n.fLikeIt);
    if (loved) return loved;
    const high = sortedNotes.find(n => (n.rating || 0) >= 92);
    return high || sortedNotes[0];
  }, [sortedNotes]);

  // Featured article: most recent
  const articles = window.WINE_ARTICLES || [];
  const sortedArticles = uM(() => [...articles].sort((a, b) => {
    const da = window.fmt.parseDate(a.publishDate)?.getTime() || 0;
    const db = window.fmt.parseDate(b.publishDate)?.getTime() || 0;
    return db - da;
  }), [articles]);
  const featuredArticle = sortedArticles[0];

  // Activity stream — notes + articles merged by date
  const stream = uM(() => {
    const items = [];
    sortedNotes.slice(0, 14).forEach(n => items.push({
      type: 'note',
      date: window.fmt.parseDate(n.tastingDate)?.getTime() || 0,
      raw: n
    }));
    sortedArticles.forEach(a => items.push({
      type: 'article',
      date: window.fmt.parseDate(a.publishDate)?.getTime() || 0,
      raw: a
    }));
    return items.sort((a, b) => b.date - a.date).slice(0, 12);
  }, [sortedNotes, sortedArticles]);

  const consumed = data.consumed.length;
  const cellarCount = data.cellar.filter(c => c.quantity > 0).length;
  const regions = uM(() => {
    const s = new Set();
    [...data.consumed, ...data.cellar, ...data.tastingNotes].forEach(r => {
      const sub = (r.locale || '').split(',')[1]?.trim();
      if (sub) s.add(sub);
    });
    return s.size;
  }, [data]);
  const totalSpend = uM(() => data.purchases.reduce((s, p) => s + (p.price || 0), 0), [data]);

  const onRandom = () => {
    const all = data.tastingNotes;
    const pick = all[Math.floor(Math.random() * all.length)];
    window.location.hash = `#/note/${pick.id}`;
  };

  // Featured note pull quote
  const featText = featuredNote ? getNoteText(featuredNote, lang) : null;
  const featQuoteEn = featText ? pullQuote(featText.en, 280) : '';
  const featQuoteCn = featText ? pullQuote(featText.cn, 90) : '';

  return (
    <main>
      <section className="hero hero-tight">
        <div className="hero-decor"></div>
        <div className="hero-inner">
          <div className="hero-meta">
            <span>Vol. 01</span>
            <span>·</span>
            <span>2026 · April</span>
            <span>·</span>
            <span>{data.tastingNotes.length} notes · {articles.length} essays</span>
          </div>
          <h1 className="hero-title">
            Wine, words,<br/>and the lives<br/><em>in between.</em>
          </h1>
          <div className="hero-cn">{STR.hero_lede_cn}</div>
          <div className="hero-foot">
            <button className="random-btn" onClick={onRandom}>
              <span>{lang === 'cn' ? '随机一瓶' : 'Pour me a random one'}</span>
              <span className="arrow"></span>
            </button>
          </div>
        </div>
      </section>

      {/* EDITOR'S LETTER */}
      <section className="container editor-letter">
        <div className="editor-letter-mast">
          <span>From the editor</span>
          <span className="cn">· 主编札</span>
          <span className="dot">·</span>
          <span>April 2026</span>
        </div>
        <div className="editor-letter-body">
          <p className="el-en">
            April was a Sangiovese month — three Brunellos, a Chianti Classico Riserva,
            and a quiet evening with the 2010 Lascombes that reminded me why I started
            taking notes in the first place. Next month: a vertical I've been putting off,
            and a piece on why I've been buying less Burgundy than I thought I would.
          </p>
          <p className="el-cn">
            四月是 Sangiovese 的月份 — 三瓶 Brunello、一支 Chianti Classico Riserva、
            一个安静的晚上配着 2010 Lascombes，让我想起当初为什么要写酒评。
            下个月：一直拖着没做的垂直品鉴，以及我为什么买的 Burgundy 比想象中少。
          </p>
          <div className="editor-sig">— Michael</div>
        </div>
      </section>

      {/* MAGAZINE COVER — featured note + featured article */}
      {(featuredNote || featuredArticle) && (
        <section className="container cover-spread">
          {featuredNote && (
            <a href={`#/note/${featuredNote.id}`} className="cover-feat">
              <image-slot
                id={`cover-bottle-${featuredNote.id}`}
                class="img-cover-bottle"
                style={{width:'100%',height:'320px',display:'block',marginBottom:'28px'}}
                shape="rect"
                placeholder="Bottle photo · 主图（瓶身或倒酒特写）"
              ></image-slot>
              <div className="cover-eyebrow">
                <span>{featuredNote.fLikeIt ? '♡  This week\'s bottle' : 'This week\'s bottle'}</span>
                <span className="cn">· 本周一瓶</span>
              </div>
              <div className="cover-feat-vintage">{featuredNote.vintage}</div>
              <div className="cover-feat-wine">{featuredNote.wine}</div>
              <div className="cover-feat-producer">
                {featuredNote.producer} · {window.fmt.region(featuredNote.locale, 'en')}
              </div>
              {featQuoteEn && (
                <blockquote className="cover-feat-quote">
                  <p>"{featQuoteEn}"</p>
                  {featQuoteCn && lang !== 'en' && <p className="cn">「{featQuoteCn}」</p>}
                </blockquote>
              )}
              <div className="cover-feat-foot">
                <span className="cover-feat-rating">
                  <span className="cfr-num">{featuredNote.rating || '—'}</span>
                  <span className="cfr-max">/100</span>
                </span>
                <span className="cover-feat-date">
                  {window.fmt.longDate(featuredNote.tastingDate, 'en')}
                </span>
                <span className="cover-feat-cta">Read the full note →</span>
              </div>
            </a>
          )}

          {featuredArticle && (
            <a href={`#/article/${featuredArticle.slug}`} className="cover-essay">
              <image-slot
                id={`cover-essay-${featuredArticle.slug}`}
                class="img-cover-essay"
                style={{width:'100%',height:'180px',display:'block',marginBottom:'20px'}}
                shape="rect"
                placeholder="Essay image · 文章配图"
              ></image-slot>
              <div className="cover-eyebrow">
                <span>Now reading</span>
                <span className="cn">· 在读</span>
              </div>
              <div className="cover-essay-eyebrow">
                {lang === 'cn' ? featuredArticle.eyebrow.cn : featuredArticle.eyebrow.en}
              </div>
              <div className="cover-essay-title">
                {lang === 'cn' ? featuredArticle.title.cn : featuredArticle.title.en}
              </div>
              <div className="cover-essay-sub">
                {lang === 'cn' ? featuredArticle.subtitle.cn : featuredArticle.subtitle.en}
              </div>
              <div className="cover-essay-foot">
                <span>{featuredArticle.readMins} min</span>
                <span className="cover-feat-cta">Read essay →</span>
              </div>
            </a>
          )}
        </section>
      )}

      <section className="snapshot">
        <div className="snap-cell">
          <div className="snap-cell-num">{consumed}</div>
          <div className="snap-cell-lbl">Bottles emptied</div>
          <div className="snap-cell-cn">已饮空瓶</div>
        </div>
        <div className="snap-cell">
          <div className="snap-cell-num">{cellarCount}</div>
          <div className="snap-cell-lbl">In the cellar</div>
          <div className="snap-cell-cn">现窖库存</div>
        </div>
        <div className="snap-cell">
          <div className="snap-cell-num">{regions}</div>
          <div className="snap-cell-lbl">Regions visited</div>
          <div className="snap-cell-cn">涉猎产区</div>
        </div>
        <div className="snap-cell">
          <div className="snap-cell-num">¥{(totalSpend/1000).toFixed(0)}<span style={{fontFamily:'var(--mono)',fontStyle:'normal',fontSize:14,color:'var(--muted)',marginLeft:4}}>K</span></div>
          <div className="snap-cell-lbl">Total invested</div>
          <div className="snap-cell-cn">累计花费</div>
        </div>
      </section>

      {/* ACTIVITY STREAM */}
      <section className="container section">
        <div className="section-h">
          <div>
            <span className="section-h-title">Lately</span>
            <span className="section-h-cn">最近</span>
          </div>
          <div style={{display:'flex',gap:24}}>
            <a href="#/notes" className="eyebrow" style={{cursor:'pointer'}}>All notes →</a>
            <a href="#/articles" className="eyebrow" style={{cursor:'pointer'}}>All essays →</a>
          </div>
        </div>
        <div className="stream">
          {stream.map((item, i) => {
            if (item.type === 'note') {
              const n = item.raw;
              return (
                <a key={`n-${n.id}`} href={`#/note/${n.id}`} className="stream-row stream-row-note">
                  <span className="stream-date">{window.fmt.longDate(n.tastingDate, 'en')}</span>
                  <span className="stream-kind">Tasting</span>
                  <span className="stream-title">
                    <em>{n.vintage}</em> {n.wine}
                    {n.fLikeIt && <span className="stream-heart">♡</span>}
                  </span>
                  <span className="stream-meta">{n.producer}</span>
                  <span className="stream-rating">{n.rating || '—'}</span>
                </a>
              );
            } else {
              const a = item.raw;
              return (
                <a key={`a-${a.slug}`} href={`#/article/${a.slug}`} className="stream-row stream-row-article">
                  <span className="stream-date">{window.fmt.longDate(a.publishDate, 'en')}</span>
                  <span className="stream-kind">Reading</span>
                  <span className="stream-title">
                    {lang === 'cn' ? a.title.cn : a.title.en}
                  </span>
                  <span className="stream-meta">{lang === 'cn' ? a.subtitle.cn : a.subtitle.en}</span>
                  <span className="stream-rating">{a.readMins}<span className="stream-min">min</span></span>
                </a>
              );
            }
          })}
        </div>
      </section>
    </main>
  );
}

function NoteCard({ note, lang }) {
  const text = getNoteText(note, lang);
  const excerpt = lang === 'cn'
    ? window.fmt.excerpt(text.cn || text.en, 110)
    : window.fmt.excerpt(text.en || text.cn, 180);
  return (
    <a href={`#/note/${note.id}`} className="note-card">
      <div className="note-card-meta">
        <span>{window.fmt.region(note.locale, lang === 'cn' ? 'cn' : 'en')}</span>
        <span>{window.fmt.longDate(note.tastingDate, lang === 'cn' ? 'cn' : 'en')}</span>
      </div>
      <div className="note-card-vintage">{note.vintage}</div>
      <div className="note-card-wine">{note.wine}</div>
      <div className="note-card-region">{note.varietal}</div>
      {excerpt && <div className="note-card-excerpt">{excerpt}</div>}
      <div className="note-card-foot">
        <RatingPill value={note.rating} />
        {note.fLikeIt && <span className="heart">♡  Loved</span>}
      </div>
    </a>
  );
}

/* ============ NOTES LIST ============ */
function NotesList({ lang, data }) {
  const [q, setQ] = uS('');
  const [country, setCountry] = uS('all');
  const [sort, setSort] = uS('recent');

  const countries = uM(() => {
    const s = new Set();
    data.tastingNotes.forEach(n => {
      const c = (n.locale || '').split(',')[0].trim();
      if (c) s.add(c);
    });
    return ['all', ...Array.from(s).sort()];
  }, [data]);

  const filtered = uM(() => {
    let out = data.tastingNotes;
    if (country !== 'all') out = out.filter(n => (n.locale||'').startsWith(country));
    if (q) {
      const ql = q.toLowerCase();
      out = out.filter(n =>
        (n.wine||'').toLowerCase().includes(ql) ||
        (n.producer||'').toLowerCase().includes(ql) ||
        (n.locale||'').toLowerCase().includes(ql) ||
        (n.varietal||'').toLowerCase().includes(ql) ||
        (n.notes||'').toLowerCase().includes(ql) ||
        (n.vintage||'').includes(ql)
      );
    }
    out = [...out].sort((a, b) => {
      if (sort === 'high') return (b.rating||0) - (a.rating||0);
      if (sort === 'loved') return (b.fLikeIt?1:0) - (a.fLikeIt?1:0);
      const da = window.fmt.parseDate(a.tastingDate)?.getTime() || 0;
      const db = window.fmt.parseDate(b.tastingDate)?.getTime() || 0;
      return db - da;
    });
    return out;
  }, [data, q, country, sort]);

  return (
    <main className="container tn-page">
      <div className="tn-head">
        <div>
          <h1>Tasting notes.</h1>
          <div className="cn">酒评 — 一瓶一字。</div>
        </div>
        <div className="tn-count">{filtered.length} of {data.tastingNotes.length}</div>
      </div>
      <div className="tn-controls">
        <div className="search">
          <span className="search-icon"></span>
          <input value={q} onChange={e => setQ(e.target.value)}
            placeholder={lang === 'cn' ? '搜索酒款、酒庄、产区或关键词……' : 'Search wine, producer, region, or word…'} />
        </div>
        <div className="chip-group">
          {countries.map(c => (
            <button key={c} className={`chip ${country === c ? 'active' : ''}`} onClick={() => setCountry(c)}>
              {c === 'all' ? (lang === 'cn' ? '全部' : 'All') : c}
            </button>
          ))}
        </div>
        <select className="sort-select" value={sort} onChange={e => setSort(e.target.value)}>
          <option value="recent">{lang==='cn'?'最近':'Most recent'}</option>
          <option value="high">{lang==='cn'?'评分最高':'Highest rated'}</option>
          <option value="loved">{lang==='cn'?'喜欢':'Loved'}</option>
        </select>
      </div>
      <div className="note-table">
        {(() => {
          const groups = [];
          let curKey = null, curGroup = null;
          for (const n of filtered) {
            const d = window.fmt.parseDate(n.tastingDate);
            const key = d ? `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}` : 'undated';
            if (key !== curKey) {
              curKey = key;
              curGroup = { key, date: d, items: [] };
              groups.push(curGroup);
            }
            curGroup.items.push(n);
          }
          const monthsEN = ['January','February','March','April','May','June','July','August','September','October','November','December'];
          const monthsCN = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
          return groups.map(g => (
            <React.Fragment key={g.key}>
              <div className="archive-divider">
                {g.date ? (
                  <>
                    <span className="ad-month">{monthsEN[g.date.getMonth()]}</span>
                    <span className="ad-year">{g.date.getFullYear()}</span>
                    <span className="ad-cn">{g.date.getFullYear()}年 {monthsCN[g.date.getMonth()]}</span>
                    <span className="ad-count">{g.items.length} {g.items.length === 1 ? 'bottle' : 'bottles'}</span>
                    <span className="ad-rule"></span>
                  </>
                ) : (
                  <>
                    <span className="ad-month">Undated</span>
                    <span className="ad-count">{g.items.length}</span>
                    <span className="ad-rule"></span>
                  </>
                )}
              </div>
              {g.items.map(n => <NoteRow key={n.id} note={n} lang={lang} />)}
            </React.Fragment>
          ));
        })()}
        {filtered.length === 0 && (
          <div style={{padding:'80px 0', textAlign:'center', color:'var(--muted)', fontFamily:'var(--serif-en)', fontStyle:'italic', fontSize:22}}>
            Nothing here. The cellar is bigger than your search.
          </div>
        )}
      </div>
    </main>
  );
}

function NoteRow({ note, lang }) {
  const text = getNoteText(note, lang);
  const excerpt = lang === 'cn'
    ? window.fmt.excerpt(text.cn || text.en, 120)
    : window.fmt.excerpt(text.en || text.cn, 180);
  return (
    <a href={`#/note/${note.id}`} className="note-row">
      <div className="row-vintage">{note.vintage}</div>
      <div>
        <div className="row-wine">{note.wine}</div>
        <div className="row-region">{window.fmt.region(note.locale, 'en')} · {note.varietal}</div>
      </div>
      <div className="row-excerpt">{excerpt}</div>
      <div className="row-date">{window.fmt.longDate(note.tastingDate, 'en')}</div>
      <div className={`row-rating ${!note.rating ? 'no-rating':''}`}>{note.rating || '—'}</div>
      <div className="arrow-tiny"></div>
    </a>
  );
}

/* ============ NOTE DETAIL ============ */

const GRAPE_COLOR = {
  'Sangiovese': '#8b1e2d',
  'Cabernet Sauvignon': '#3a0a14',
  'Merlot': '#6b1b2a',
  'Cabernet Franc': '#7d2a3a',
  'Pinot Noir': '#a3354a',
  'Pinot Meunier': '#8b5a3a',
  'Petit Verdot': '#1f0710',
  'Chardonnay': '#c89b4a',
  'Canaiolo': '#993a4a',
  'Colorino': '#771e2a',
  'Carmenère': '#5a1a26',
  'Nebbiolo': '#a8453a',
  'Syrah': '#2d0813',
};
function grapeColor(g) {
  const norm = g.replace(/\s*\([^)]*\)\s*/g, '').trim();
  return GRAPE_COLOR[norm] || '#6b1b2a';
}

function findRelatedArticles(note) {
  const arts = window.WINE_ARTICLES || [];
  if (!arts.length) return [];
  // Build match candidates: wine name, producer, significant tokens
  const candidates = new Set();
  if (note.wine) candidates.add(note.wine);
  if (note.producer) {
    candidates.add(note.producer);
    const stripped = note.producer.replace(/^(Château|Ch\.|Domaine|Tenuta|Castello|Bodegas|Marchese|Marchesi)\s+/i, '');
    if (stripped !== note.producer) candidates.add(stripped);
  }
  // Significant tokens — proper-noun-looking words 5+ chars
  (note.wine || '').split(/[\s,]+/).forEach(t => {
    if (t.length >= 5 && /^[A-Z]/.test(t) && !['Château','Brunello','Riserva','Chianti','Cuvée'].includes(t)) {
      candidates.add(t);
    }
  });
  return arts.filter(a => {
    const haystack = (a.body?.en || '') + ' ' + (a.body?.cn || '') + ' ' + (a.subtitle?.en||'') + ' ' + (a.title?.en||'');
    return [...candidates].some(c => haystack.includes(c));
  });
}

function BlendBar({ blend }) {
  if (!blend || !blend.length) return null;
  return (
    <div className="blend-bar-wrap">
      <div className="blend-bar">
        {blend.map((b, i) => (
          <div key={i} className="blend-seg" style={{flex: b.pct, background: grapeColor(b.grape)}} title={`${b.grape} ${b.pct}%`} />
        ))}
      </div>
      <ul className="blend-legend">
        {blend.map((b, i) => (
          <li key={i}>
            <span className="blend-dot" style={{background: grapeColor(b.grape)}} />
            <span className="blend-grape">{b.grape}</span>
            <span className="blend-pct">{b.pct}%</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ScoreColumn({ label, sub, value, max = 100, accent }) {
  return (
    <div className="score-col">
      <div className="score-col-lbl">{label}</div>
      {sub && <div className="score-col-sub">{sub}</div>}
      <div className="score-col-val" style={accent ? {color: accent} : null}>
        {value != null ? value : '—'}
        <span className="score-col-max">/{max}</span>
      </div>
      <ScoreBar value={value || 0} max={max} />
    </div>
  );
}

function NoteDetail({ id, lang, data }) {
  const all = uM(() => [...data.tastingNotes].sort((a,b)=>{
    const da = window.fmt.parseDate(a.tastingDate)?.getTime() || 0;
    const db = window.fmt.parseDate(b.tastingDate)?.getTime() || 0;
    return db - da;
  }), [data]);
  const idx = all.findIndex(n => n.id === id);
  const note = all[idx];
  if (!note) return <main className="container" style={{padding:'120px 0'}}><div className="display" style={{fontSize:48}}>Bottle not found.</div></main>;

  const prev = all[idx - 1];
  const next = all[idx + 1];
  const text = getNoteText(note, lang);
  const purchase = data.consumed.find(c => c.wine === note.wine && c.vintage === note.vintage);

  const showBoth = lang === 'both' && text.en && text.cn && text.en !== text.cn;

  // Critics lookup
  const criticsData = (window.WINE_CRITICS || {})[note.wine + '|' + note.vintage];
  const appellation = criticsData?.appellation;
  const blend = criticsData?.blend;
  const criticScores = (criticsData?.scores || []).slice(0, 2);
  const editorialTake = criticsData?.take;

  // Related articles
  const relatedArticles = uM(() => findRelatedArticles(note), [note]);

  return (
    <main className="container note-detail">
      <a href="#/notes" className="detail-back">← {lang === 'cn' ? '返回全部酒评' : 'Back to all notes'}</a>

      {/* HEAD */}
      <div className="detail-head">
        <div className="detail-head-left">
          <image-slot
            id={`note-bottle-${note.id}`}
            class="img-note-bottle"
            style={{width:'160px',height:'220px',display:'block',marginBottom:'24px'}}
            shape="rect"
            placeholder="Bottle photo · 瓶身照片"
          ></image-slot>
          <div className="detail-vintage">{note.vintage}</div>
          <div className="detail-wine">{note.wine}</div>
          {appellation ? (
            <div className="detail-appellation">{appellation}</div>
          ) : (
            <div className="detail-appellation">{window.fmt.region(note.locale, 'en')}</div>
          )}

          <div className="detail-meta-grid">
            <div>
              <div className="meta-cell-lbl">Producer · 酒庄</div>
              <div className="meta-cell-val">
                <a href={`#/producer/${window.slugifyProducer ? window.slugifyProducer(note.producer) : ''}`} className="producer-link">
                  {note.producer}
                </a>
              </div>
            </div>
            <div>
              <div className="meta-cell-lbl">Varietal · 品种</div>
              <div className="meta-cell-val">{note.varietal}</div>
            </div>
            <div>
              <div className="meta-cell-lbl">Tasted on · 品饮</div>
              <div className="meta-cell-val mono">{window.fmt.longDate(note.tastingDate, lang==='cn'?'cn':'en')}</div>
            </div>
            <div>
              <div className="meta-cell-lbl">Paid · 购入</div>
              <div className="meta-cell-val mono">{purchase ? window.fmt.cny(purchase.price) : '—'}</div>
            </div>
          </div>

          {note.fLikeIt && (
            <div className="detail-loved">
              ♡ Loved bottle <span className="cn">· 喜爱</span>
            </div>
          )}
        </div>

        <aside className="score-card">
          <div className="score-card-h">{lang === 'cn' ? '评分对照' : 'Ratings, side by side'}</div>
          <div className="score-grid">
            <ScoreColumn label="Mine" sub="我的评分" value={note.rating || null} accent="var(--wine-fg)" />
            <ScoreColumn label="Community" sub="群体" value={note.cScore ? +note.cScore.toFixed(1) : null} />
            {criticScores.map((s, i) => (
              <ScoreColumn key={i}
                label={s.critic.replace(/\s*\([^)]*\)\s*/, '')}
                sub={s.year ? `· ${s.year}` : ''}
                value={s.value} />
            ))}
          </div>
        </aside>
      </div>

      {/* BLEND */}
      {blend && blend.length > 0 && (
        <section className="blend-section">
          <div className="section-eyebrow">
            <span>Composition</span>
            <span>· 品种构成</span>
          </div>
          <BlendBar blend={blend} />
        </section>
      )}

      {/* EDITORIAL TAKE — public reputation */}
      {editorialTake && (
        <section className="editorial-take">
          <div className="section-eyebrow">
            <span>Public reputation</span>
            <span>· 公论</span>
          </div>
          <blockquote className="take-quote">
            <p className="take-en">{editorialTake.en}</p>
            {editorialTake.cn && lang !== 'en' && <p className="take-cn">{editorialTake.cn}</p>}
          </blockquote>
        </section>
      )}

      {/* MY NOTE — private reaction */}
      <section className="my-note-section">
        <div className="section-eyebrow">
          <span>My note</span>
          <span>· 我的笔记</span>
        </div>

        {showBoth ? (
          <div className="article">
            <div>
              <div className="article-col-h">
                <span>English</span>
                <span className="lang-badge">EN</span>
              </div>
              <div className="article-body-en">{text.en}</div>
            </div>
            <div>
              <div className="article-col-h">
                <span>中文</span>
                <span className="lang-badge">中</span>
              </div>
              <div className="article-body-cn">{text.cn}</div>
            </div>
          </div>
        ) : (
          <div className="article single-col">
            <div>
              {lang === 'cn'
                ? <div className="article-body-cn">{text.cn || text.en}</div>
                : <div className="article-body-en">{text.en || text.cn}</div>}
            </div>
          </div>
        )}
      </section>

      {/* RELATED ARTICLES */}
      {relatedArticles.length > 0 && (
        <section className="related-articles">
          <div className="section-eyebrow">
            <span>Read more · Field notes that mention this</span>
            <span>· 相关札记</span>
          </div>
          <div className="related-articles-grid">
            {relatedArticles.map(a => (
              <a key={a.slug} href={`#/article/${a.slug}`} className="related-article-card">
                <div className="related-article-eyebrow">{lang === 'cn' ? a.eyebrow.cn : a.eyebrow.en} · {a.readMins} min</div>
                <div className="related-article-title">{lang === 'cn' ? a.title.cn : a.title.en}</div>
                <div className="related-article-sub">{lang === 'cn' ? a.subtitle.cn : a.subtitle.en}</div>
                <div className="related-article-arrow">Read →</div>
              </a>
            ))}
          </div>
        </section>
      )}

      <nav className="detail-nav">
        {prev ? (
          <a href={`#/note/${prev.id}`}>
            <span className="detail-nav-lbl">← {lang==='cn'?'上一篇':'Previous'}</span>
            <span className="detail-nav-title">{prev.vintage} {prev.wine}</span>
          </a>
        ) : <span></span>}
        {next ? (
          <a href={`#/note/${next.id}`}>
            <span className="detail-nav-lbl">{lang==='cn'?'下一篇':'Next'} →</span>
            <span className="detail-nav-title">{next.vintage} {next.wine}</span>
          </a>
        ) : <span></span>}
      </nav>
    </main>
  );
}

window.Home = Home;
window.NotesList = NotesList;
window.NoteDetail = NoteDetail;
