// SommWine — Cotação (price comparison) + Clube (social feed)

// ═══════════════════════════════════════════════════════════════
// Helper: Sommelier rating wheel (original SommWine design)
// ═══════════════════════════════════════════════════════════════
function SWRatingWheel({ value = 4.0, onChange, P, T, size = 200, interactive = true }) {
  // value is 1.0 - 5.0 → angle from -135° (1) to +135° (5), sweeping 270°
  const toAngle = (v) => -135 + ((v - 1) / 4) * 270;
  const angle = toAngle(value);
  const r = size / 2 - 16;
  const cx = size / 2, cy = size / 2;

  // ticks
  const ticks = [];
  for (let i = 0; i < 51; i++) {
    const t = i / 50;
    const v = 1 + t * 4;
    const a = (toAngle(v) - 90) * Math.PI / 180;
    const inner = i % 10 === 0 ? r - 12 : (i % 5 === 0 ? r - 8 : r - 5);
    ticks.push({
      x1: cx + Math.cos(a) * inner, y1: cy + Math.sin(a) * inner,
      x2: cx + Math.cos(a) * r,     y2: cy + Math.sin(a) * r,
      active: v <= value, major: i % 10 === 0,
    });
  }

  // arc path from -135° to current angle
  const arcPath = (() => {
    const startA = (-135 - 90) * Math.PI / 180;
    const endA   = (angle  - 90) * Math.PI / 180;
    const x1 = cx + Math.cos(startA) * r, y1 = cy + Math.sin(startA) * r;
    const x2 = cx + Math.cos(endA)   * r, y2 = cy + Math.sin(endA)   * r;
    const large = (angle - (-135)) > 180 ? 1 : 0;
    return `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`;
  })();

  // knob position
  const knobA = (angle - 90) * Math.PI / 180;
  const kx = cx + Math.cos(knobA) * r, ky = cy + Math.sin(knobA) * r;

  // drag handling
  const svgRef = React.useRef(null);
  const setFromEvent = (e) => {
    if (!interactive || !onChange) return;
    const pt = e.touches?.[0] || e;
    const rect = svgRef.current.getBoundingClientRect();
    const dx = pt.clientX - rect.left - size / 2;
    const dy = pt.clientY - rect.top  - size / 2;
    let a = Math.atan2(dy, dx) * 180 / Math.PI + 90; // 0 at top
    if (a > 180) a -= 360;
    if (a < -135) a = -135;
    if (a > 135) a = 135;
    const v = 1 + ((a + 135) / 270) * 4;
    onChange(Math.round(v * 10) / 10);
  };

  // gradient stops based on value
  const arcColor = value < 2.5 ? P.muted : value < 3.5 ? P.gold : value < 4.5 ? P.cork : P.burgundy;

  return (
    <svg
      ref={svgRef} width={size} height={size} viewBox={`0 0 ${size} ${size}`}
      onMouseDown={setFromEvent}
      onMouseMove={(e) => e.buttons === 1 && setFromEvent(e)}
      onTouchStart={setFromEvent}
      onTouchMove={setFromEvent}
      style={{ display: 'block', touchAction: 'none', cursor: interactive ? 'pointer' : 'default' }}
    >
      {/* outer ring */}
      <circle cx={cx} cy={cy} r={r + 2} fill="none" stroke={P.line2} strokeWidth="0.5"/>
      {/* ticks */}
      {ticks.map((t, i) => (
        <line key={i} x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
          stroke={t.active ? arcColor : P.line}
          strokeWidth={t.major ? 1.4 : 0.7}
          strokeLinecap="round"
          opacity={t.active ? 1 : 0.55}
        />
      ))}
      {/* active arc */}
      <path d={arcPath} fill="none" stroke={arcColor} strokeWidth="2.5" strokeLinecap="round" opacity="0.9"/>
      {/* numeric labels at 1,2,3,4,5 */}
      {[1,2,3,4,5].map(v => {
        const a = (toAngle(v) - 90) * Math.PI / 180;
        const tr = r - 24;
        return (
          <text key={v}
            x={cx + Math.cos(a) * tr} y={cy + Math.sin(a) * tr + 4}
            textAnchor="middle" fontSize="11"
            fontFamily={T.mono} fill={P.muted}>
            {v}
          </text>
        );
      })}
      {/* knob */}
      <circle cx={kx} cy={ky} r="14" fill={arcColor} opacity="0.18"/>
      <circle cx={kx} cy={ky} r="7"  fill={arcColor}/>
      <circle cx={kx} cy={ky} r="3"  fill={P.bg}/>
      {/* center: star + number */}
      <text x={cx} y={cy - 6} textAnchor="middle" fontSize="14" fill={arcColor} fontFamily={T.display}>★</text>
      <text x={cx} y={cy + 22} textAnchor="middle"
        fontSize="36" fontFamily={T.display} fontStyle="italic" fontWeight="600" fill={P.ink}>
        {value.toFixed(1)}
      </text>
    </svg>
  );
}

// ═══════════════════════════════════════════════════════════════
// 6. COTAÇÃO — price comparison
// ═══════════════════════════════════════════════════════════════
function SWQuote({ P, T, cellar, onOpenWine }) {
  // default to first wine in cellar, else first overall
  const cellarIds = SW_WINES.filter(w => cellar.has(w.id)).map(w => w.id);
  const [selectedId, setSelectedId] = React.useState(cellarIds[0] || SW_WINES[0].id);
  const [region, setRegion] = React.useState('São Paulo');
  const [alert, setAlert] = React.useState(false);

  const wine = SW_WINES.find(w => w.id === selectedId);
  const prices = SW_RETAILERS.map(r => ({
    ...r,
    price: Math.round(wine.price * r.mult),
  })).sort((a, b) => a.price - b.price);

  const min = prices[0].price;
  const max = prices[prices.length - 1].price;
  const avg = Math.round(prices.reduce((n, p) => n + p.price, 0) / prices.length);
  const best = prices[0];
  const savings = max - min;

  const history = SW_PRICE_HISTORY.map(m => Math.round(wine.price * m));

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* vintage corks backdrop on top */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 180, overflow: 'hidden', zIndex: 0,
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url('assets/corks-vintage.jpg')`,
          backgroundSize: 'cover', backgroundPosition: 'center',
          opacity: 0.5,
        }}/>
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, rgba(20,5,8,0.35) 0%, ${P.bg} 95%)`,
        }}/>
      </div>

      {/* header */}
      <div style={{ position: 'relative', padding: '8px 24px 14px', zIndex: 1 }}>
        <div style={{ fontFamily: T.mono, fontSize: 9.5, letterSpacing: '0.2em', color: P.gold, textTransform: 'uppercase' }}>
          Preço de mercado
        </div>
        <h1 style={{
          fontFamily: T.display, fontStyle: 'italic', fontSize: 32, fontWeight: 500,
          color: '#f5efe4', margin: '4px 0 0', letterSpacing: '-0.01em',
          textShadow: '0 2px 12px rgba(0,0,0,0.5)',
        }}>Cotação</h1>
      </div>

      {/* wine selector strip */}
      <div className="sw-scroll" style={{
        display: 'flex', gap: 10, overflowX: 'auto',
        padding: '0 24px 16px',
      }}>
        {SW_WINES.map(w => {
          const active = selectedId === w.id;
          return (
            <button key={w.id} onClick={() => setSelectedId(w.id)} style={{
              all: 'unset', cursor: 'pointer',
              flexShrink: 0, padding: '10px 12px 8px', borderRadius: 14,
              background: active ? P.surface2 : P.paper,
              border: `0.5px solid ${active ? P.burgundy : P.line}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              width: 78,
            }}>
              <SWBottle color={w.color} width={26}/>
              <div style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.1em', color: active ? P.burgundy : P.muted, textTransform: 'uppercase', textAlign: 'center', lineHeight: 1.2 }}>
                {w.name.split(' ')[0]}<br/>{w.year}
              </div>
            </button>
          );
        })}
      </div>

      {/* best price card */}
      <div style={{ padding: '0 24px 14px' }}>
        <div style={{
          position: 'relative', overflow: 'hidden',
          background: P.burgundy, color: '#f5efe4', borderRadius: 18, padding: '16px 18px',
        }}>
          {/* grape texture */}
          <div style={{
            position: 'absolute', inset: 0,
            backgroundImage: `url('assets/cellar-brick.jpg')`,
            backgroundSize: 'cover', backgroundPosition: 'center',
            opacity: 0.32, mixBlendMode: 'overlay',
          }}/>
          <div style={{
            position: 'absolute', inset: 0,
            background: `linear-gradient(135deg, rgba(138,26,43,0.7) 0%, rgba(74,12,20,0.92) 100%)`,
          }}/>
          <div style={{
            position: 'absolute', right: -30, top: -30, width: 140, height: 140,
            borderRadius: '50%', border: `1px solid ${P.gold}`, opacity: 0.25, zIndex: 1,
          }}/>
          <div style={{
            position: 'absolute', right: -10, top: -10, width: 100, height: 100,
            borderRadius: '50%', border: `1px solid ${P.gold}`, opacity: 0.4, zIndex: 1,
          }}/>
          <div style={{ position: 'relative', zIndex: 2 }}>
            <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: '0.2em', color: P.gold, textTransform: 'uppercase', marginBottom: 6 }}>
              ✦ Melhor preço hoje
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <div style={{ fontFamily: T.display, fontSize: 14, opacity: 0.7 }}>R$</div>
              <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 48, fontWeight: 600, lineHeight: 1 }}>
                {min.toLocaleString('pt-BR')}
              </div>
            </div>
            <div style={{ fontFamily: T.body, fontSize: 13, marginTop: 4, fontStyle: 'italic', opacity: 0.92 }}>
              em <b style={{ fontStyle: 'normal' }}>{best.name}</b> · {best.ship}
            </div>
            <div style={{
              marginTop: 12, paddingTop: 12, borderTop: `0.5px solid rgba(245,239,228,0.25)`,
              display: 'flex', gap: 16,
            }}>
              <div>
                <div style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.16em', opacity: 0.7, textTransform: 'uppercase' }}>Economia</div>
                <div style={{ fontFamily: T.display, fontSize: 18, fontStyle: 'italic', fontWeight: 600 }}>R$ {savings}</div>
              </div>
              <div>
                <div style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.16em', opacity: 0.7, textTransform: 'uppercase' }}>Vs. média</div>
                <div style={{ fontFamily: T.display, fontSize: 18, fontStyle: 'italic', fontWeight: 600 }}>−{Math.round((1 - min/avg) * 100)}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* price history */}
      <div style={{ padding: '0 24px 14px' }}>
        <div style={{
          background: P.paper, borderRadius: 14, padding: '14px 16px',
          border: `0.5px solid ${P.line}`,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, letterSpacing: '0.16em', textTransform: 'uppercase' }}>
              Últimos 6 meses
            </div>
            <div style={{ fontFamily: T.mono, fontSize: 9, color: P.sage, letterSpacing: '0.1em' }}>
              ↘ −{Math.round((1 - history[5]/history[0]) * 100)}%
            </div>
          </div>
          <SWSparkline values={history} P={P} T={T}/>
        </div>
      </div>

      {/* retailer list */}
      <div style={{ padding: '8px 24px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
            {prices.length} ofertas encontradas
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, letterSpacing: '0.12em' }}>
            min · méd · máx
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {prices.map((r, i) => {
            const isBest = i === 0;
            const delta = r.price - avg;
            return (
              <div key={r.id} style={{
                background: P.paper, borderRadius: 14, padding: '12px 14px',
                border: `0.5px solid ${isBest ? P.gold : P.line}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                {/* rank */}
                <div style={{
                  width: 24, height: 24, borderRadius: '50%',
                  background: isBest ? P.gold : 'transparent',
                  color: isBest ? P.bg : P.muted,
                  border: isBest ? 'none' : `0.5px solid ${P.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: T.mono, fontSize: 10, fontWeight: 600,
                  flexShrink: 0,
                }}>{i + 1}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 16, color: P.ink, lineHeight: 1.1 }}>{r.name}</span>
                    <span style={{
                      fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.1em', textTransform: 'uppercase',
                      color: r.kind === 'online' ? P.sage : r.kind === 'fisica' ? P.cork : P.muted,
                      border: `0.5px solid ${P.line}`, padding: '2px 5px', borderRadius: 4,
                    }}>{r.kind === 'online' ? 'online' : r.kind === 'fisica' ? 'loja' : 'mercado'}</span>
                  </div>
                  <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, marginTop: 3, letterSpacing: '0.06em' }}>
                    {r.city} · {r.ship}
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 19, fontWeight: 600, color: isBest ? P.burgundy : P.ink, lineHeight: 1 }}>
                    R$ {r.price.toLocaleString('pt-BR')}
                  </div>
                  <div style={{
                    fontFamily: T.mono, fontSize: 8.5, marginTop: 4,
                    color: delta < 0 ? P.sage : delta > 0 ? P.wine : P.muted,
                    letterSpacing: '0.06em',
                  }}>
                    {delta < 0 ? '↘ ' : delta > 0 ? '↗ +' : ''}{delta !== 0 ? `R$ ${Math.abs(delta)}` : '= méd'}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* alert toggle */}
      <div style={{ padding: '16px 24px 0' }}>
        <button onClick={() => setAlert(!alert)} style={{
          all: 'unset', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 12,
          width: '100%', boxSizing: 'border-box',
          padding: '14px 16px', borderRadius: 14,
          background: alert ? P.surface2 : P.paper,
          border: `0.5px solid ${alert ? P.burgundy : P.line}`,
        }}>
          <div style={{
            width: 36, height: 22, borderRadius: 22, padding: 2, boxSizing: 'border-box',
            background: alert ? P.burgundy : P.line,
            transition: 'background .2s',
          }}>
            <div style={{
              width: 18, height: 18, borderRadius: '50%', background: P.bg,
              transform: `translateX(${alert ? 14 : 0}px)`, transition: 'transform .2s',
            }}/>
          </div>
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 15, color: P.ink, lineHeight: 1.1 }}>
              Avise quando o preço cair
            </div>
            <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, letterSpacing: '0.12em', marginTop: 3 }}>
              Alvo: abaixo de R$ {min.toLocaleString('pt-BR')}
            </div>
          </div>
        </button>
      </div>
    </div>
  );
}

function SWSparkline({ values, P, T }) {
  const w = 320, h = 60, pad = 8;
  const min = Math.min(...values), max = Math.max(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = pad + (i / (values.length - 1)) * (w - pad * 2);
    const y = h - pad - ((v - min) / range) * (h - pad * 2);
    return [x, y];
  });
  const path = pts.map(([x, y], i) => `${i ? 'L' : 'M'} ${x} ${y}`).join(' ');
  const area = `${path} L ${pts[pts.length-1][0]} ${h} L ${pts[0][0]} ${h} Z`;
  const months = ['nov','dez','jan','fev','mar','abr'];
  return (
    <svg viewBox={`0 0 ${w} ${h + 18}`} width="100%" height="auto" style={{ display: 'block' }}>
      <defs>
        <linearGradient id="sparkGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"  stopColor={P.burgundy} stopOpacity="0.18"/>
          <stop offset="100%" stopColor={P.burgundy} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkGrad)"/>
      <path d={path} fill="none" stroke={P.burgundy} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
      {pts.map(([x, y], i) => (
        <circle key={i} cx={x} cy={y} r={i === pts.length - 1 ? 3.5 : 2} fill={i === pts.length - 1 ? P.gold : P.burgundy}/>
      ))}
      {pts.map(([x], i) => (
        <text key={i} x={x} y={h + 14} textAnchor="middle"
          fontSize="8" fontFamily={T.mono} fill={P.muted} letterSpacing="1">
          {months[i]}
        </text>
      ))}
    </svg>
  );
}

// ═══════════════════════════════════════════════════════════════
// 7. CLUBE — social feed
// ═══════════════════════════════════════════════════════════════
function SWClub({ P, T, onOpenWine }) {
  const [composeOpen, setComposeOpen] = React.useState(false);
  const [draftRating, setDraftRating] = React.useState(4.0);
  const [draftText, setDraftText] = React.useState('');
  const [draftWineId, setDraftWineId] = React.useState(SW_WINES[0].id);
  const [feed, setFeed] = React.useState(SW_POSTS);
  const [liked, setLiked] = React.useState(new Set());

  const toggleLike = (postId) => {
    setLiked(prev => {
      const next = new Set(prev);
      if (next.has(postId)) next.delete(postId);
      else next.add(postId);
      return next;
    });
  };

  const publish = () => {
    if (!draftText.trim()) return;
    const newPost = {
      id: 'p' + Date.now(),
      userId: 'me',
      wineId: draftWineId,
      rating: draftRating,
      when: 'agora',
      text: draftText.trim(),
      likes: 0, comments: 0,
      location: 'Sua adega',
    };
    setFeed([newPost, ...feed]);
    setDraftText('');
    setDraftRating(4.0);
    setComposeOpen(false);
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* cellar arch backdrop on top */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 200, overflow: 'hidden', zIndex: 0,
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url('assets/cellar-arch.jpg')`,
          backgroundSize: 'cover', backgroundPosition: 'center 25%',
          opacity: 0.5,
        }}/>
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, rgba(20,5,8,0.45) 0%, ${P.bg} 95%)`,
        }}/>
      </div>

      {/* header */}
      <div style={{ position: 'relative', padding: '8px 24px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', zIndex: 1 }}>
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 9.5, letterSpacing: '0.2em', color: P.gold, textTransform: 'uppercase' }}>
            Entre sommeliers
          </div>
          <h1 style={{
            fontFamily: T.display, fontStyle: 'italic', fontSize: 32, fontWeight: 500,
            color: '#f5efe4', margin: '4px 0 0', letterSpacing: '-0.01em',
            textShadow: '0 2px 12px rgba(0,0,0,0.5)',
          }}>Clube SommWine</h1>
        </div>
        <div style={{
          padding: '5px 10px', borderRadius: 999, border: `0.5px solid rgba(245,239,228,0.3)`,
          fontFamily: T.mono, fontSize: 8.5, color: 'rgba(245,239,228,0.85)', letterSpacing: '0.14em', textTransform: 'uppercase',
          background: 'rgba(20,5,8,0.45)', backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', gap: 5,
        }}>
          <span style={{ width: 5, height: 5, borderRadius: 5, background: P.sage }}/>
          4 ativos
        </div>
      </div>

      {/* friends row (stories-ish) */}
      <div className="sw-scroll" style={{
        display: 'flex', gap: 14, overflowX: 'auto',
        padding: '4px 24px 18px',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0 }}>
          <div style={{
            width: 58, height: 58, borderRadius: '50%', position: 'relative',
            border: `1.5px dashed ${P.burgundy}`,
            background: P.paper,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: P.burgundy, fontSize: 22, fontFamily: T.display, fontWeight: 300,
          }}>+</div>
          <div style={{ fontFamily: T.mono, fontSize: 8, color: P.muted, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Convidar</div>
        </div>
        {SW_FRIENDS.map(f => (
          <div key={f.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0 }}>
            <div style={{
              width: 58, height: 58, borderRadius: '50%', position: 'relative',
              padding: 2, background: `conic-gradient(from 0deg, ${P.burgundy}, ${P.gold}, ${P.cork}, ${P.burgundy})`,
              boxSizing: 'border-box',
            }}>
              <div style={{
                width: '100%', height: '100%', borderRadius: '50%',
                background: f.color, color: P.bg,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: T.display, fontStyle: 'italic', fontSize: 18, fontWeight: 500,
                border: `2px solid ${P.bg}`, boxSizing: 'border-box',
              }}>{f.initials}</div>
            </div>
            <div style={{ fontFamily: T.mono, fontSize: 8, color: P.ink2, letterSpacing: '0.06em', maxWidth: 60, textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {f.name.split(' ')[0]}
            </div>
          </div>
        ))}
      </div>

      {/* compose */}
      <div style={{ padding: '0 24px 18px' }}>
        {!composeOpen ? (
          <button onClick={() => setComposeOpen(true)} style={{
            all: 'unset', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 16px', width: '100%', boxSizing: 'border-box',
            background: P.paper, borderRadius: 14,
            border: `0.5px solid ${P.line}`,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: '50%',
              background: P.burgundy, color: P.bg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: T.display, fontStyle: 'italic', fontSize: 16,
            }}>H</div>
            <div style={{ flex: 1, fontFamily: T.body, fontSize: 14, color: P.muted, fontStyle: 'italic' }}>
              Compartilhe sua próxima taça…
            </div>
            <div style={{
              padding: '6px 12px', borderRadius: 999,
              background: P.burgundy, color: P.bg,
              fontFamily: T.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
            }}>★ Avaliar</div>
          </button>
        ) : (
          <div className="sw-fade-up" style={{
            background: P.paper, borderRadius: 18, padding: '18px 16px 16px',
            border: `0.5px solid ${P.line}`,
          }}>
            {/* wine picker mini */}
            <div className="sw-scroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 8 }}>
              {SW_WINES.map(w => (
                <button key={w.id} onClick={() => setDraftWineId(w.id)} style={{
                  all: 'unset', cursor: 'pointer', flexShrink: 0,
                  padding: '6px 10px', borderRadius: 999,
                  background: draftWineId === w.id ? P.burgundy : 'transparent',
                  color: draftWineId === w.id ? P.bg : P.ink2,
                  border: `0.5px solid ${draftWineId === w.id ? P.burgundy : P.line}`,
                  fontFamily: T.mono, fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase',
                }}>{w.name.split(' ')[0]} · {w.year}</button>
              ))}
            </div>

            {/* rating wheel */}
            <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0' }}>
              <SWRatingWheel value={draftRating} onChange={setDraftRating} P={P} T={T} size={200}/>
            </div>
            <div style={{
              textAlign: 'center', fontFamily: T.mono, fontSize: 9,
              color: P.muted, letterSpacing: '0.2em', textTransform: 'uppercase', marginBottom: 12,
            }}>O que achou?</div>

            <textarea
              value={draftText}
              onChange={e => setDraftText(e.target.value)}
              placeholder="Escreva sua avaliação…"
              rows={3}
              style={{
                width: '100%', boxSizing: 'border-box',
                background: P.bg, color: P.ink,
                border: `0.5px solid ${P.line}`, borderRadius: 12,
                padding: 12, fontFamily: T.body, fontSize: 14, lineHeight: 1.5,
                outline: 'none', resize: 'none', fontStyle: 'italic',
              }}
            />
            <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
              <button onClick={() => setComposeOpen(false)} style={{
                all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center',
                padding: '11px', borderRadius: 999,
                border: `0.5px solid ${P.line}`, color: P.ink2,
                fontFamily: T.mono, fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
              }}>Cancelar</button>
              <button onClick={publish} style={{
                all: 'unset', cursor: 'pointer', flex: 2, textAlign: 'center',
                padding: '11px', borderRadius: 999,
                background: P.burgundy, color: P.bg,
                fontFamily: T.mono, fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
              }}>Publicar no clube</button>
            </div>
          </div>
        )}
      </div>

      {/* trending */}
      <div style={{ padding: '0 24px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontFamily: T.mono, fontSize: 9, color: P.muted, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
            Em alta esta semana
          </div>
        </div>
        <div className="sw-scroll" style={{ display: 'flex', gap: 10, overflowX: 'auto' }}>
          {SW_TRENDING.map(id => {
            const w = SW_WINES.find(x => x.id === id);
            return (
              <button key={id} onClick={() => onOpenWine(id)} style={{
                all: 'unset', cursor: 'pointer', flexShrink: 0,
                width: 130, padding: '12px 12px 10px',
                background: P.paper, borderRadius: 14,
                border: `0.5px solid ${P.line}`,
                display: 'flex', flexDirection: 'column', alignItems: 'center',
              }}>
                <SWBottle color={w.color} width={36} label={w.grape.split(' ')[0].toUpperCase()} vintage={String(w.year)}/>
                <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 14, color: P.ink, marginTop: 8, textAlign: 'center', lineHeight: 1.1 }}>
                  {w.name}
                </div>
                <div style={{ fontFamily: T.mono, fontSize: 8, color: P.muted, letterSpacing: '0.1em', marginTop: 4 }}>
                  ★ {w.rating.toFixed(1)} · {w.country}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* feed */}
      <div style={{ padding: '0 24px 0' }}>
        <SWOrnament P={P} mark="✦"/>
        <div style={{
          fontFamily: T.display, fontStyle: 'italic', fontSize: 20,
          textAlign: 'center', margin: '14px 0 16px', color: P.ink, fontWeight: 500,
        }}>Do feed</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {feed.map(post => (
            <SWPost key={post.id}
              post={post}
              wine={SW_WINES.find(w => w.id === post.wineId)}
              user={post.userId === 'me' ? { initials: 'H', name: 'Helena (você)', tagline: 'Sua publicação', color: P.burgundy } : SW_FRIENDS.find(f => f.id === post.userId)}
              liked={liked.has(post.id)}
              onLike={() => toggleLike(post.id)}
              onOpenWine={onOpenWine}
              P={P} T={T}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

function SWPost({ post, wine, user, liked, onLike, onOpenWine, P, T }) {
  return (
    <div style={{
      background: P.paper, borderRadius: 18, padding: '16px 16px 14px',
      border: `0.5px solid ${P.line}`,
    }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%',
          background: user.color, color: P.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: T.display, fontStyle: 'italic', fontSize: 16, fontWeight: 500,
          flexShrink: 0,
        }}>{user.initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 16, color: P.ink, lineHeight: 1.1, fontWeight: 500 }}>
            {user.name}
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 8.5, color: P.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 3 }}>
            {user.tagline} · {post.when}
          </div>
        </div>
        <div style={{
          padding: '4px 10px', borderRadius: 999,
          background: P.burgundy, color: P.bg,
          fontFamily: T.mono, fontSize: 9, letterSpacing: '0.1em',
          display: 'flex', alignItems: 'center', gap: 4,
        }}>
          <span style={{ color: P.gold }}>★</span>
          <span style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 13, fontWeight: 600 }}>{post.rating.toFixed(1)}</span>
        </div>
      </div>

      {/* wine card */}
      <button onClick={() => onOpenWine(wine.id)} style={{
        all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 12px', borderRadius: 12,
        background: P.bg, border: `0.5px solid ${P.line2}`,
        width: '100%', boxSizing: 'border-box',
      }}>
        <SWBottle color={wine.color} width={28}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: T.display, fontStyle: 'italic', fontSize: 15, color: P.ink, lineHeight: 1.1 }}>
            {wine.name}, {wine.year}
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 8.5, color: P.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 3 }}>
            {wine.grape} · {wine.region}
          </div>
        </div>
        <span style={{ color: P.muted, fontSize: 16 }}>›</span>
      </button>

      {/* text */}
      <p style={{
        fontFamily: T.body, fontSize: 14, lineHeight: 1.55, color: P.ink,
        margin: '12px 2px 0', fontStyle: 'italic',
      }}>"{post.text}"</p>

      {/* location */}
      <div style={{ fontFamily: T.mono, fontSize: 8.5, color: P.muted, letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 10 }}>
        ◐ {post.location}
      </div>

      {/* actions */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 18, marginTop: 12,
        paddingTop: 12, borderTop: `0.5px solid ${P.line2}`,
      }}>
        <button onClick={onLike} style={{
          all: 'unset', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 5,
          color: liked ? P.burgundy : P.muted,
          fontFamily: T.mono, fontSize: 10, letterSpacing: '0.06em',
        }}>
          <span style={{ fontSize: 14 }}>{liked ? '♥' : '♡'}</span>
          {post.likes + (liked ? 1 : 0)}
        </button>
        <button style={{
          all: 'unset', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 5, color: P.muted,
          fontFamily: T.mono, fontSize: 10, letterSpacing: '0.06em',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3">
            <path d="M2 4 Q2 2 4 2 L10 2 Q12 2 12 4 L12 8 Q12 10 10 10 L6 10 L3 12.5 L3.5 10 Q2 10 2 8 Z"/>
          </svg>
          {post.comments}
        </button>
        <button style={{
          all: 'unset', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 5, color: P.muted,
          fontFamily: T.mono, fontSize: 10, letterSpacing: '0.06em',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round">
            <path d="M7 2 L7 9 M4 5 L7 2 L10 5 M2 10 L2 12 L12 12 L12 10"/>
          </svg>
        </button>
        <div style={{ flex: 1 }}/>
        <button style={{
          all: 'unset', cursor: 'pointer',
          fontFamily: T.mono, fontSize: 9, color: P.burgundy,
          letterSpacing: '0.14em', textTransform: 'uppercase',
        }}>+ Salvar</button>
      </div>
    </div>
  );
}

Object.assign(window, { SWRatingWheel, SWQuote, SWClub, SWSparkline, SWPost });
