// Library (Brand tab) screen

// ───── LIBRARY ─────
function LibraryScreen({ onOpenDrink, initialBrand }) {
  const [mode, setMode] = React.useState('brand'); // 'brand' | 'all'
  const [activeBrand, setActiveBrand] = React.useState(initialBrand || 'all'); // brand id or 'all'
  const [attr, setAttr] = React.useState('all'); // attribute filter
  const [sort, setSort] = React.useState('match');

  const attrs = [
    { id: 'all', label: '全部' },
    { id: 'low', label: '低热量' },
    { id: 'no-sugar', label: '0 糖' },
    { id: 'coffee', label: '咖啡' },
    { id: 'fruit', label: '鲜果' },
    { id: 'tea', label: '纯茶' },
  ];
  const sorts = ['match', 'cal', 'price', 'sugar'];
  const sortLabels = { match: '匹配度', cal: '热量低', price: '价格低', sugar: '糖分低' };

  const applyAttr = (arr) => {
    let a = arr;
    if (attr === 'low') a = a.filter(d => d.cal < 250);
    if (attr === 'coffee') a = a.filter(d => d.caffeine > 0);
    if (attr === 'fruit') a = a.filter(d => d.tags.includes('鲜果'));
    if (attr === 'tea') a = a.filter(d => d.tags.includes('纯茶'));
    return a;
  };
  const applySort = (arr) => {
    const a = [...arr];
    if (sort === 'cal') a.sort((x,y) => x.cal - y.cal);
    else if (sort === 'price') a.sort((x,y) => x.price - y.price);
    else if (sort === 'sugar') a.sort((x,y) => x.sugar - y.sugar);
    else a.sort((x,y) => y.match - x.match);
    return a;
  };

  // brand-grouped data
  const drinksByBrand = BRANDS.map(b => ({
    brand: b,
    drinks: applySort(applyAttr(DRINKS.filter(d => d.brandId === b.id))),
  })).filter(g => g.drinks.length > 0);

  // flat mode data
  let flatDrinks = DRINKS;
  if (activeBrand !== 'all') flatDrinks = flatDrinks.filter(d => d.brandId === activeBrand);
  flatDrinks = applySort(applyAttr(flatDrinks));
  const activeBrandObj = BRANDS.find(b => b.id === activeBrand);

  return (
    <div style={{ paddingBottom: 100 }}>
      <MpChrome title="品牌" />

      {/* Brand rail — primary navigation */}
      <div className="scroll" style={{
        display: 'flex', gap: 14, overflowX: 'auto',
        padding: '4px 16px 14px',
      }}>
        <BrandChip all selected={activeBrand === 'all'} onClick={() => setActiveBrand('all')} />
        {BRANDS.map(b => (
          <BrandChip key={b.id} brand={b}
                     selected={activeBrand === b.id}
                     onClick={() => setActiveBrand(b.id)} />
        ))}
      </div>

      {/* Mode + attribute + sort bar */}
      <div style={{ padding: '0 16px' }}>
        {/* mode toggle only visible on "all brands" */}
        {activeBrand === 'all' && (
          <div style={{ display: 'flex', gap: 4, background: 'var(--sunken)',
                        padding: 3, borderRadius: 999, marginBottom: 12, width: 'fit-content' }}>
            {[
              { id: 'brand', label: '按品牌分组' },
              { id: 'all',   label: '全部饮品' },
            ].map(m => (
              <button key={m.id} onClick={() => setMode(m.id)} style={{
                padding: '6px 14px', borderRadius: 999, fontSize: 11,
                background: mode === m.id ? 'var(--surface)' : 'transparent',
                color: mode === m.id ? 'var(--ink-1)' : 'var(--ink-3)',
                fontWeight: mode === m.id ? 600 : 500,
                boxShadow: mode === m.id ? '0 0 0 0.5px rgba(0,0,0,0.06)' : 'none',
              }}>{m.label}</button>
            ))}
          </div>
        )}

        {/* attribute chips */}
        <div className="scroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 10 }}>
          {attrs.map(f => (
            <button key={f.id} onClick={() => setAttr(f.id)} style={{
              flexShrink: 0, padding: '6px 12px', borderRadius: 999,
              background: f.id === attr ? 'var(--ink-1)' : 'var(--surface)',
              color: f.id === attr ? 'var(--paper)' : 'var(--ink-2)',
              fontSize: 11, fontWeight: f.id === attr ? 600 : 500,
              border: f.id === attr ? 'none' : '0.5px solid var(--ink-5)',
            }}>{f.label}</button>
          ))}
        </div>

        {/* count + sort */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
            {activeBrand === 'all' ? (
              mode === 'brand'
                ? <>{drinksByBrand.length} 个品牌 · {drinksByBrand.reduce((s,g) => s + g.drinks.length, 0)} 款</>
                : <>共 <span style={{ color: 'var(--ink-1)', fontWeight: 600, fontFamily: 'var(--font-num)' }}>{flatDrinks.length}</span> 款饮品</>
            ) : (
              <>{activeBrandObj?.name} · <span style={{ color: 'var(--ink-1)', fontWeight: 600, fontFamily: 'var(--font-num)' }}>{flatDrinks.length}</span> 款</>
            )}
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            {sorts.map(s => (
              <button key={s} onClick={() => setSort(s)} style={{
                padding: '4px 10px', borderRadius: 999, fontSize: 11,
                background: s === sort ? 'var(--brand-yellow-soft)' : 'transparent',
                color: s === sort ? 'var(--brand-yellow-ink)' : 'var(--ink-3)',
                fontWeight: s === sort ? 600 : 400,
              }}>{sortLabels[s]}</button>
            ))}
          </div>
        </div>
      </div>

      {/* content */}
      {activeBrand === 'all' && mode === 'brand' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {drinksByBrand.map(({ brand, drinks }) => (
            <BrandSection key={brand.id} brand={brand} drinks={drinks}
                          onOpenDrink={onOpenDrink}
                          onViewAll={() => setActiveBrand(brand.id)} />
          ))}
        </div>
      ) : (
        <div style={{ padding: '0 16px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {flatDrinks.map(d => <DrinkCardV d={d} key={d.id} onOpenDrink={onOpenDrink} />)}
          </div>
        </div>
      )}
    </div>
  );
}

function BrandChip({ all, brand, selected, onClick }) {
  const bg = all ? 'linear-gradient(135deg, var(--brand-yellow), var(--data-match))' : brand.color;
  return (
    <button onClick={onClick} style={{
      flexShrink: 0, display: 'flex', flexDirection: 'column',
      alignItems: 'center', gap: 6, width: 52,
    }}>
      <div style={{
        width: 52, height: 52, borderRadius: 18,
        background: bg, color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 18, fontWeight: 700,
        outline: selected ? '2px solid var(--ink-1)' : '0 solid transparent',
        outlineOffset: 2,
        transition: 'outline 160ms ease',
        boxShadow: 'var(--sh-1)',
      }}>
        {all ? '全' : brand.glyph}
      </div>
      <span style={{
        fontSize: 10, color: selected ? 'var(--ink-1)' : 'var(--ink-2)',
        fontWeight: selected ? 600 : 500, whiteSpace: 'nowrap',
        maxWidth: 60, overflow: 'hidden', textOverflow: 'ellipsis',
      }}>
        {all ? '全部' : brand.name}
      </span>
    </button>
  );
}

function BrandSection({ brand, drinks, onOpenDrink, onViewAll }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10,
                    padding: '0 16px', marginBottom: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 10, background: brand.color, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 700,
        }}>{brand.glyph}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-1)' }}>{brand.name}</div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
            {drinks.length} 款饮品
          </div>
        </div>
        <button onClick={onViewAll} style={{
          fontSize: 11, color: 'var(--ink-3)',
          display: 'flex', alignItems: 'center', gap: 2,
        }}>
          查看全部
          <IconChevron size={12} color="var(--ink-3)" />
        </button>
      </div>
      <div className="scroll" style={{
        display: 'flex', gap: 10, overflowX: 'auto',
        padding: '0 16px 4px',
      }}>
        {drinks.map(d => <DrinkCardH d={d} key={d.id} onOpenDrink={onOpenDrink} />)}
      </div>
    </div>
  );
}

// Horizontal card (used in brand sections)
function DrinkCardH({ d, onOpenDrink }) {
  return (
    <button onClick={() => onOpenDrink(d)} style={{
      width: 150, flexShrink: 0,
      background: 'var(--surface)', borderRadius: 16, overflow: 'hidden',
      textAlign: 'left', boxShadow: 'var(--sh-1)',
    }}>
      <div style={{ height: 110, background: `linear-gradient(180deg, ${d.colorA}66, ${d.colorA}22)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        <CupPlaceholder colorA={d.colorA} colorB={d.colorB} size={70} />
        <div style={{ position: 'absolute', top: 6, left: 6, padding: '2px 6px',
                      background: '#fff', borderRadius: 999, fontSize: 9, fontWeight: 600,
                      color: 'var(--data-price)', boxShadow: 'var(--sh-1)' }}>
          健康 {d.health}
        </div>
      </div>
      <div style={{ padding: '8px 10px 10px' }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-1)',
                      marginBottom: 6, lineHeight: 1.3,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {d.name}
        </div>
        <div style={{ display: 'flex', gap: 8, fontSize: 10 }}>
          <Stat label="kcal" value={d.cal} color="var(--data-cal)" />
          <Stat label="¥" value={d.price} color="var(--ink-2)" />
        </div>
      </div>
    </button>
  );
}

// Vertical card (used in grid) — now with brand badge top-left
function DrinkCardV({ d, onOpenDrink }) {
  const brand = BRANDS.find(b => b.id === d.brandId);
  return (
    <button onClick={() => onOpenDrink(d)} style={{
      background: 'var(--surface)', borderRadius: 18, overflow: 'hidden',
      textAlign: 'left', boxShadow: 'var(--sh-1)',
    }}>
      <div style={{ height: 120, background: `linear-gradient(180deg, ${d.colorA}66, ${d.colorA}22)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        <CupPlaceholder colorA={d.colorA} colorB={d.colorB} size={78} />
        {brand && (
          <div style={{
            position: 'absolute', top: 8, left: 8,
            display: 'flex', alignItems: 'center', gap: 5,
            padding: '3px 8px 3px 3px',
            background: '#fff', borderRadius: 999,
            boxShadow: 'var(--sh-1)',
          }}>
            <span style={{
              width: 16, height: 16, borderRadius: 5,
              background: brand.color, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 9, fontWeight: 700,
            }}>{brand.glyph}</span>
            <span style={{ fontSize: 10, fontWeight: 600, color: 'var(--ink-1)' }}>{brand.name}</span>
          </div>
        )}
        <div style={{ position: 'absolute', top: 8, right: 8, padding: '3px 7px',
                      background: '#fff', borderRadius: 999, fontSize: 10, fontWeight: 600,
                      color: 'var(--data-price)', boxShadow: 'var(--sh-1)' }}>
          健康 {d.health}
        </div>
      </div>
      <div style={{ padding: '10px 12px 12px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 8 }}>{d.name}</div>
        <div style={{ display: 'flex', gap: 8, fontSize: 10 }}>
          <Stat label="kcal" value={d.cal} color="var(--data-cal)" />
          <Stat label="糖g"  value={d.sugar} color="var(--data-sugar)" />
          <Stat label="¥"    value={d.price} color="var(--ink-2)" />
        </div>
      </div>
    </button>
  );
}

function Stat({ label, value, color }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
      <span style={{ fontFamily: 'var(--font-num)', fontWeight: 700, color, fontSize: 13 }}>{value}</span>
      <span style={{ fontSize: 9, color: 'var(--ink-3)' }}>{label}</span>
    </div>
  );
}

Object.assign(window, { LibraryScreen, BrandChip, BrandSection, DrinkCardH, DrinkCardV, Stat });