// THE EPIZODE — cart (Корзина). Article-based (SKU + optional variant + size).

function EpzCartPage() {
  const F = EPZ_FONTS;
  const [theme, setTheme, T] = useEpzTheme();
  const store = useEpzStore();
  const cart = store.cart;

  function updateQty(idx, delta) {
    const next = cart.map((c, i) => i === idx ? { ...c, qty: Math.max(0, (c.qty || 1) + delta) } : c).filter((c) => c.qty > 0);
    store.setCart(next);
  }
  function removeItem(idx) {
    store.setCart(cart.filter((_, i) => i !== idx));
  }

  const lines = cart.map((c) => {
    const a = epzArticle(c.id);
    if (!a) return null;
    const ep = epzEpisode(a.episode);
    const v = a.variants && c.variant ? a.variants.find((x) => x.key === c.variant) : null;
    const price = v ? v.price : a.price;
    return { ...c, a, ep, v, price, lineTotal: price * (c.qty || 1) };
  }).filter(Boolean);
  const grouped = epzGroupCart(cart);
  const subtotal = grouped.subtotal;
  const bundleSavings = grouped.savings;
  const total = subtotal;
  const fmt = epzFmt;

  return (
    <div style={{
      width: '100%', minHeight: '100vh',
      background: T.bg, color: T.text,
      fontFamily: F.mono, fontSize: 13, lineHeight: 1.5,
      WebkitFontSmoothing: 'antialiased',
      transition: 'background 0.3s ease, color 0.3s ease',
    }}>
      <style>{`
        .cart-qty-btn { transition: opacity 0.2s; cursor: pointer; }
        .cart-qty-btn:hover { opacity: 1; }
        @keyframes cartFade { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        .cart-line { animation: cartFade 0.3s cubic-bezier(.2,.7,.2,1) both; }
      `}</style>

      <EpzHeader theme={theme} setTheme={setTheme} T={T} current="episodes" cartCount={lines.reduce((s, l) => s + l.qty, 0)} />

      {lines.length === 0 ? (
        <EmptyCart T={T} />
      ) : (
        <>
        <section style={{ padding: '60px 32px 30px', borderBottom: `1px solid ${T.border}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16, fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.6 }}>
            <span>// корзина</span>
            <span>{lines.length} {plural(lines.length, 'вещь', 'вещи', 'вещей')} в корзине</span>
          </div>
          <h1 style={{ fontFamily: F.display, fontSize: 'clamp(64px, 8vw, 120px)', fontWeight: 300, lineHeight: 0.92, letterSpacing: '-0.02em', margin: 0 }}>
            Ваша <span style={{ fontStyle: 'italic' }}>корзина.</span>
          </h1>
        </section>
        <section style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr' }}>
          <div style={{ borderRight: `1px solid ${T.border}` }}>
            {lines.map((l, i) => (
              <CartLine key={l.id + (l.variant || '') + l.size} line={l} idx={i} T={T} onQtyChange={updateQty} onRemove={removeItem} />
            ))}
            <div style={{ padding: '32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <a href="/catalog/" style={{ color: 'inherit', textDecoration: 'none', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.85 }}>
                ← вернуться в каталог
              </a>
              <span style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.55 }}>цены включают НДС</span>
            </div>
          </div>

          <aside style={{ padding: '40px 36px', position: 'sticky', top: 70, alignSelf: 'flex-start' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 18 }}>// итог заказа</div>

            <div style={{ borderTop: `1px solid ${T.border}`, paddingTop: 18 }}>
              {lines.map((l) => (
                <div key={l.id + (l.variant || '') + l.size} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 12, letterSpacing: '0.02em', fontFamily: F.body, textTransform: 'none' }}>
                  <span style={{ opacity: 0.85 }}>
                    {((l.a.variantNames && l.variant && l.a.variantNames[l.variant]) || l.a.title)} <span style={{ opacity: 0.55 }}>· {l.size} × {l.qty}</span>
                  </span>
                  <span style={{ fontFamily: F.display, fontSize: 16 }}>{fmt(l.lineTotal)}</span>
                </div>
              ))}
            </div>

            <div style={{ borderTop: `1px solid ${T.border}`, marginTop: 18, paddingTop: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
              <Row label="подытог" value={fmt(subtotal + bundleSavings)} T={T} />
              {bundleSavings > 0 && <Row label="✦ комплект" value={`−${fmt(bundleSavings)}`} T={T} small />}
              <Row label="доставка" value="рассчитается при оформлении" T={T} small />
            </div>

            <div style={{ marginTop: 18, paddingTop: 18, borderTop: `1px solid ${T.text}`, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase' }}>итого</span>
              <span style={{ fontFamily: F.display, fontSize: 36, lineHeight: 1 }}>{fmt(total)}</span>
            </div>

            <a href="/checkout/" style={{
              marginTop: 26, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              width: '100%', background: T.btnPrimary, color: T.btnPrimaryFg, border: 0, padding: '22px 24px',
              fontFamily: F.mono, fontSize: 12, letterSpacing: '0.22em', textTransform: 'uppercase', textDecoration: 'none',
            }}>
              <span>оформить заказ</span><span>→</span>
            </a>

            <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', opacity: 0.6 }}>
              <span>СДЭК 3–7 дней</span><span style={{ textAlign: 'right' }}>доставка по миру</span>
              <span>возврат 14 дней</span><span style={{ textAlign: 'right' }}>оплата картой / СБП</span>
            </div>

            <div style={{ marginTop: 28, padding: '14px 16px', border: `1px dashed ${T.border}`, display: 'flex', alignItems: 'center', gap: 12 }}>
              <input placeholder="промокод" style={{ flex: 1, border: 0, background: 'transparent', fontFamily: F.mono, fontSize: 12, color: T.text, outline: 'none', padding: 0 }} />
              <button style={{ background: 'transparent', color: T.text, border: `1px solid ${T.border}`, padding: '6px 12px', fontFamily: F.mono, fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer' }}>применить</button>
            </div>
          </aside>
        </section>
        </>
      )}

      <EpzFooter T={T} />
    </div>
  );
}

function plural(n, one, few, many) {
  const m10 = n % 10, m100 = n % 100;
  if (m10 === 1 && m100 !== 11) return one;
  if (m10 >= 2 && m10 <= 4 && (m100 < 10 || m100 >= 20)) return few;
  return many;
}

function Row({ label, value, T, small }) {
  const F = EPZ_FONTS;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: small ? 10 : 11, letterSpacing: '0.18em', textTransform: 'uppercase', opacity: small ? 0.6 : 0.95 }}>
      <span>{label}</span>
      <span style={small ? {} : { fontFamily: F.display, fontSize: 18, letterSpacing: 0, textTransform: 'none' }}>{value}</span>
    </div>
  );
}

function CartLine({ line, idx, T, onQtyChange, onRemove }) {
  const F = EPZ_FONTS;
  const { a, ep, v, size, qty, lineTotal } = line;
  const img = epzVariantImage(a.id, line.variant);
  const fmt = epzFmt;
  const href = `/product/?id=${a.id}`;

  return (
    <div className="cart-line" style={{ display: 'grid', gridTemplateColumns: '160px 1fr auto auto', gap: 28, alignItems: 'center', padding: '32px', borderBottom: `1px solid ${T.border}` }}>
      <a href={href} style={{ position: 'relative', display: 'block', textDecoration: 'none' }}>
        {img ? (
          <div style={{ aspectRatio: '4/5', backgroundColor: '#ffffff', backgroundImage: `url(${img})`, backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }} />
        ) : (
          <EpzPlaceholder label={a.title} sub={ep.title} ratio="4/5" tone={T.placeholderTone} />
        )}
      </a>

      <div>
        <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.6, marginBottom: 6 }}>
          эпизод {ep.id} · {ep.title}
        </div>
        <a href={href} style={{ color: 'inherit', textDecoration: 'none' }}>
          <div style={{ fontFamily: F.display, fontSize: 34, lineHeight: 1.05 }}>
            {(a.variantNames && v && a.variantNames[v.key]) || a.title}
          </div>
        </a>
        <div style={{ marginTop: 14, display: 'flex', gap: 18, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', opacity: 0.75 }}>
          <span>размер · <span style={{ color: T.text, opacity: 1 }}>{size}</span></span>
          <span>ткань · {a.fabric}</span>
        </div>
        <button onClick={() => onRemove(idx)} style={{ marginTop: 18, padding: 0, background: 'transparent', color: T.text, border: 0, opacity: 0.55, fontFamily: F.mono, fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 3 }}>
          убрать ×
        </button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', border: `1px solid ${T.border}` }}>
        <button className="cart-qty-btn" onClick={() => onQtyChange(idx, -1)} style={{ width: 36, height: 36, background: 'transparent', color: T.text, border: 0, fontFamily: F.mono, fontSize: 16, cursor: 'pointer', opacity: 0.7 }}>−</button>
        <div style={{ width: 32, textAlign: 'center', fontFamily: F.display, fontSize: 20 }}>{qty}</div>
        <button className="cart-qty-btn" onClick={() => onQtyChange(idx, 1)} style={{ width: 36, height: 36, background: 'transparent', color: T.text, border: 0, fontFamily: F.mono, fontSize: 16, cursor: 'pointer', opacity: 0.7 }}>+</button>
      </div>

      <div style={{ textAlign: 'right', fontFamily: F.display, fontSize: 28, lineHeight: 1 }}>{fmt(lineTotal)}</div>
    </div>
  );
}

function EmptyCart({ T }) {
  const F = EPZ_FONTS;
  return (
    <section style={{ padding: '0 32px', textAlign: 'center', minHeight: 'calc(100vh - 64px)', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
      <div style={{ fontFamily: F.display, fontSize: 56, fontStyle: 'italic', fontWeight: 300, lineHeight: 1.05 }}>
        {epzT('Здесь пока пусто')}
      </div>
      <p style={{ marginTop: 22, fontFamily: F.body, fontSize: 15, lineHeight: 1.6, letterSpacing: 0, textTransform: 'none', opacity: 0.7, maxWidth: 480, margin: '22px auto 0' }}>
        {epzT('Загляните в каталог — 4 эпизода первой коллекции уже здесь')}
      </p>
      <a href="/catalog/" style={{ display: 'inline-block', marginTop: 36, background: T.btnPrimary, color: T.btnPrimaryFg, textDecoration: 'none', padding: '18px 32px', fontFamily: F.mono, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase' }}>
        {epzT('смотреть каталог')} →
      </a>
    </section>
  );
}

window.EpzCartPage = EpzCartPage;
