
const CartCtx = React.createContext(null);

const QTY_MAX = 999;
const sanitize = (arr) =>
  (Array.isArray(arr) ? arr : [])
    .filter((x) => x && x.name)
    .map((x) => ({ ...x, qty: Math.max(1, Math.min(QTY_MAX, parseInt(x.qty) || 1)) }));

const CART_VERSION = 'v2';
function CartProvider({ children }) {
  const [items, setItems] = React.useState(() => {
    try {
      if (localStorage.getItem('tps_cart_ver') !== CART_VERSION) {
        localStorage.removeItem('tps_cart');
        localStorage.setItem('tps_cart_ver', CART_VERSION);
        return [];
      }
      return sanitize(JSON.parse(localStorage.getItem('tps_cart') || '[]'));
    } catch { return []; }
  });
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    localStorage.setItem('tps_cart', JSON.stringify(items));
  }, [items]);

  const add = (item, qty = 1) => {
    setItems((prev) => {
      const i = prev.findIndex((x) => x.name === item.name);
      if (i >= 0) {
        const next = [...prev];
        next[i] = { ...next[i], qty: Math.min(QTY_MAX, next[i].qty + qty) };
        return next;
      }
      return [...prev, { ...item, qty: Math.min(QTY_MAX, qty) }];
    });
  };
  const remove = (name) => setItems((prev) => prev.filter((x) => x.name !== name));
  const update = (name, qty) =>
    setItems((prev) =>
      prev.map((x) => x.name === name
        ? { ...x, qty: Math.max(1, Math.min(QTY_MAX, parseInt(qty) || 1)) }
        : x));
  const clear = () => setItems([]);
  const total = items.reduce((s, x) => s + (x.price || 0) * x.qty, 0);
  const count = items.reduce((s, x) => s + x.qty, 0);
  const countDisplay = count > 99 ? '99+' : String(count);

  return (
    <CartCtx.Provider value={{ items, add, remove, update, clear, total, count, countDisplay, open, setOpen }}>
      {children}
    </CartCtx.Provider>
  );
}
const useCart = () => React.useContext(CartCtx);

function CartDrawer({ accent }) {
  const cart = useCart();
  if (!cart.open) return null;

  const fmt = (n) => new Intl.NumberFormat('ru-RU').format(Math.round(n));
  const orderMsg = () => {
    let m = 'Здравствуйте! Хочу оформить заказ:%0A%0A';
    cart.items.forEach((it, i) => {
      m += `${i+1}. ${it.name} — ${it.qty} ${it.unit}`;
      if (it.price) m += ` × ${fmt(it.price)} ₸ = ${fmt(it.price*it.qty)} ₸`;
      m += '%0A';
    });
    m += `%0AИтого: ${fmt(cart.total)} ₸ (предварительно)%0A%0AПрошу связаться для уточнения.`;
    return `https://wa.me/${window.TPS_WA}?text=${m}`;
  };

  return (
    <>
      <div className="drawer-bg" onClick={() => cart.setOpen(false)} />
      <aside className="drawer">
        <div className="drawer-head">
          <div>
            <div className="drawer-eyebrow">Корзина</div>
            <div className="drawer-title">{cart.count} {cart.count === 1 ? 'позиция' : (cart.count < 5 && cart.count > 0 ? 'позиции' : 'позиций')}</div>
          </div>
          <button className="drawer-x" onClick={() => cart.setOpen(false)}>✕</button>
        </div>

        {cart.items.length === 0 ? (
          <div className="drawer-empty">
            <div className="empty-mark">∅</div>
            <p>Корзина пуста.</p>
            <p style={{ color: '#888', fontSize: 13 }}>Откройте каталог, чтобы добавить позиции.</p>
          </div>
        ) : (
          <>
            <div className="drawer-list">
              {cart.items.map((it) => (
                <div key={it.name} className="drawer-item">
                  <div className="di-top">
                    <div className="di-name">{it.name}</div>
                    <button className="di-x" onClick={() => cart.remove(it.name)}>✕</button>
                  </div>
                  <div className="di-spec">{it.spec}</div>
                  <div className="di-row">
                    <div className="qty">
                      <button onClick={() => cart.update(it.name, it.qty - 1)}>−</button>
                      <input
                        type="number"
                        value={it.qty}
                        onChange={(e) => cart.update(it.name, parseInt(e.target.value) || 1)}
                      />
                      <span className="qty-unit">{it.unit}</span>
                      <button onClick={() => cart.update(it.name, it.qty + 1)}>+</button>
                    </div>
                    {it.price ? (
                      <div className="di-price">{fmt(it.price * it.qty)} ₸</div>
                    ) : (
                      <div className="di-price" style={{ color: '#888' }}>цена по запросу</div>
                    )}
                  </div>
                </div>
              ))}
            </div>

            <div className="drawer-total">
              <span>Предварительно</span>
              <strong>{fmt(cart.total)} ₸</strong>
            </div>
            <div className="drawer-note">
              Финальная цена — после уточнения спецификации, способа доставки и обработки.
            </div>
            <div className="drawer-actions">
              <a href={orderMsg()} target="_blank" rel="noopener" className="btn btn-wa" style={{ background: accent }}>
                <WaIcon /> Оформить через WhatsApp
              </a>
              <button className="btn-link" onClick={cart.clear}>Очистить корзину</button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function CartFab({ accent }) {
  const cart = useCart();
  if (cart.count === 0 || cart.open) return null;
  return (
    <button className="cart-fab" onClick={() => cart.setOpen(true)} style={{ background: accent }} aria-label="Корзина">
      <CartIcon />
      <span className="fab-label">Корзина</span>
      <span className="fab-badge">{cart.countDisplay}</span>
    </button>
  );
}

function CartIcon({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
      <circle cx="9" cy="21" r="1.5"/>
      <circle cx="18" cy="21" r="1.5"/>
      <path d="M3 3h2l2.4 12.5a2 2 0 0 0 2 1.5h7.7a2 2 0 0 0 2-1.5L21 8H6"/>
    </svg>
  );
}

function WaIcon({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" style={{ flexShrink: 0 }}>
      <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.4-1.5-.9-.8-1.5-1.7-1.6-2-.2-.3 0-.4.1-.6l.4-.4c.1-.1.2-.3.3-.4.1-.2 0-.3 0-.5 0-.1-.6-1.5-.9-2.1-.2-.5-.5-.4-.6-.4-.2 0-.4 0-.6 0s-.5.1-.7.3c-.3.3-1 1-1 2.4s1 2.8 1.2 3c.1.2 2 3.2 5 4.4.7.3 1.3.5 1.7.6.7.2 1.3.2 1.8.1.6-.1 1.7-.7 1.9-1.4.2-.6.2-1.2.2-1.4-.1-.2-.3-.2-.6-.4z"/>
      <path d="M20.5 3.5C18.3 1.2 15.2 0 12 0 5.4 0 0 5.4 0 12c0 2.1.6 4.2 1.6 6L0 24l6.2-1.6c1.7.9 3.7 1.4 5.8 1.4 6.6 0 12-5.4 12-12 0-3.2-1.2-6.2-3.5-8.3zM12 22c-1.8 0-3.6-.5-5.2-1.4l-.4-.2-3.7 1 1-3.6-.2-.4C2.5 15.7 2 13.9 2 12 2 6.5 6.5 2 12 2c2.7 0 5.2 1 7.1 2.9C21 6.8 22 9.3 22 12c0 5.5-4.5 10-10 10z"/>
    </svg>
  );
}

Object.assign(window, { CartProvider, useCart, CartDrawer, CartFab, WaIcon });
