/* global React, Icon */
const { useState, useEffect, useMemo } = React;

const M_ITEMS_FULL = [
  { id: 1, brand: 'NaMaximum', name: 'WPC 80 – whey proteín', flavor: 'Čokoláda', size: '1 kg', packColor: '#0077BC', packLabel: 'WPC 80', packSub: '1 KG', visual: 'tub-lg', unit: 24.90, orig: 27.90, qty: 2, flag: 'NOVÉ' },
  { id: 2, brand: 'NaMaximum', name: 'BCAA 2:1:1 drink', flavor: 'Grep', size: '500 g', packColor: '#F96628', packLabel: 'BCAA', packSub: '500 G', visual: 'tub', unit: 19.90, orig: null, qty: 1, flag: null },
  { id: 3, brand: 'NaMaximum', name: 'Kreatín Creapure® monohydrát – premium švajčiarska kvalita 99,99 % čistota s vitamínom B6', flavor: 'Bez príchuti', size: '500 g', packColor: '#1A5282', packLabel: 'CREATINE', packSub: '500 G', visual: 'tub', unit: 16.90, orig: 21.90, qty: 1, flag: '-23 %' },
  { id: 4, brand: 'NaMaximum', name: 'Vitamín D3 + K2', flavor: null, size: '90 kaps.', packColor: '#F9C80E', packLabel: 'D3+K2', packSub: '90 KAPS', visual: 'bottle', unit: 8.90, orig: null, qty: 1, flag: null },
];

const M_ITEMS_MID = [
  { id: 3, brand: 'NaMaximum', name: 'Kreatín Creapure® monohydrát – premium švajčiarska kvalita 99,99 % čistota s vitamínom B6', flavor: 'Bez príchuti', size: '500 g', packColor: '#1A5282', packLabel: 'CREATINE', packSub: '500 G', visual: 'tub', unit: 16.90, orig: 21.90, qty: 1, flag: '-23 %' },
  { id: 2, brand: 'NaMaximum', name: 'BCAA 2:1:1 drink', flavor: 'Grep', size: '500 g', packColor: '#F96628', packLabel: 'BCAA', packSub: '500 G', visual: 'tub', unit: 19.90, orig: null, qty: 1, flag: null },
  { id: 4, brand: 'NaMaximum', name: 'Vitamín D3 + K2', flavor: null, size: '90 kaps.', packColor: '#F9C80E', packLabel: 'D3+K2', packSub: '90 KAPS', visual: 'bottle', unit: 8.90, orig: null, qty: 1, flag: null },
];

const M_ITEMS_SMALL = [
  { id: 2, brand: 'NaMaximum', name: 'BCAA 2:1:1 drink', flavor: 'Grep', size: '500 g', packColor: '#F96628', packLabel: 'BCAA', packSub: '500 G', visual: 'tub', unit: 19.90, orig: null, qty: 1, flag: null },
];

const M_ITEMS_BY_STATE = { full: M_ITEMS_FULL, mid: M_ITEMS_MID, small: M_ITEMS_SMALL };

const M_CROSS = [
  { id: 101, brand: 'NaMaximum', name: 'Shaker 700 ml', packColor: '#1B1B1B', packLabel: 'SHAKE', packSub: '700 ML', visual: 'shaker', unit: 3.90, orig: null, rating: 4.7, reviews: 412, flag: null },
  { id: 102, brand: 'NaMaximum', name: 'L-Glutamín 500 g', packColor: '#26BB59', packLabel: 'GLUT', packSub: '500 G', visual: 'tub', unit: 14.90, orig: 17.90, rating: 4.8, reviews: 289, flag: '-17 %' },
  { id: 103, brand: 'NaMaximum', name: 'Omega 3 – 120 kaps.', packColor: '#00AEEF', packLabel: 'OMEGA 3', packSub: '120 KAPS', visual: 'bottle', unit: 11.90, orig: null, rating: 4.9, reviews: 524, flag: null },
  { id: 104, brand: 'NaMaximum', name: 'Magnézium bis-glycinát', packColor: '#8E44AD', packLabel: 'MAG', packSub: '90 KAPS', visual: 'bottle', unit: 9.90, orig: null, rating: 4.8, reviews: 201, flag: 'NOVÉ' },
];

const M_SHIP = [
  { id: 'zbox',    name: 'Packeta Z-BOX (24/7)', logo: 'Z', cls: 'box', price: 1.99, eta: 'Ut 28. – st 29. 4.', fast: true },
  { id: 'packeta', name: 'Packeta výdajňa', logo: 'PKT', cls: 'pkt', price: 2.49, eta: 'Ut 28. – st 29. 4.', fast: true },
  { id: 'dpd',     name: 'DPD kuriér', logo: 'DPD', cls: 'dpd', price: 3.90, eta: 'St 29. 4.', fast: false },
  { id: 'gls',     name: 'GLS kuriér', logo: 'GLS', cls: 'gls', price: 3.90, eta: 'St 29. 4.', fast: false },
];

const M_PROMO = {
  'LETO10': { type: 'pct', value: 10, label: '-10 % Leto 2026' },
  'PROTEIN5': { type: 'eur', value: 5, label: '-5 € welcome' },
};

const M_FREE = 59;

// Reward ladder — tiered unlocks
const M_REWARDS = [
  { amt: 30, kind: 'sample', label: 'Vzorka', sub: 'BCAA Grep 10 g' },
  { amt: 40, kind: 'gift', label: 'Darček', sub: 'vyber si 1 z 3', pickable: true },
  { amt: 59, kind: 'shipping', label: 'Doprava zadarmo', sub: 'Packeta Z-BOX' },
];

const M_GIFTS = [
  { id: 'g1', name: 'Shaker NaMaximum 700 ml', packColor: '#1B1B1B', packLabel: 'SHAKE', packSub: '700 ML', visual: 'shaker', origPrice: 5.90 },
  { id: 'g2', name: 'Vzorka BCAA 20 g', packColor: '#F96628', packLabel: 'BCAA', packSub: '20 G', visual: 'sachet', origPrice: 2.40 },
  { id: 'g3', name: 'Proteínová tyčinka Choco', packColor: '#6B3410', packLabel: 'BAR', packSub: '60 G', visual: 'bar', origPrice: 2.90 },
];

// ============ Status bar (iOS-ish) ============
function MStatusBar() {
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 44,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 28px', zIndex: 50, color: '#000',
      fontFamily: '-apple-system, "SF Pro", system-ui', fontWeight: 590, fontSize: 15,
    }}>
      <span>9:41</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <svg width="16" height="10" viewBox="0 0 16 10"><rect x="0" y="6" width="2.5" height="4" rx="0.6" fill="#000"/><rect x="4" y="4" width="2.5" height="6" rx="0.6" fill="#000"/><rect x="8" y="2" width="2.5" height="8" rx="0.6" fill="#000"/><rect x="12" y="0" width="2.5" height="10" rx="0.6" fill="#000"/></svg>
        <svg width="22" height="10" viewBox="0 0 22 10"><rect x="0.5" y="0.5" width="18" height="9" rx="2.5" stroke="#000" strokeOpacity=".35" fill="none"/><rect x="2" y="2" width="15" height="6" rx="1.5" fill="#000"/></svg>
      </div>
    </div>
  );
}

function MobileCart() {
  const initialState = (window.__TWEAKS?.cartState) || 'full';
  const [items, setItems] = useState(M_ITEMS_BY_STATE[initialState] || M_ITEMS_FULL);
  const [removing, setRemoving] = useState(null);
  const [shipping, setShipping] = useState('zbox');
  const [promoInput, setPromoInput] = useState('');
  const [promo, setPromo] = useState(null);
  const [note, setNote] = useState('');
  const [openCard, setOpenCard] = useState(null); // 'promo' | 'note' | null
  const [toasts, setToasts] = useState([]);
  const [addedIds, setAddedIds] = useState(new Set());
  const [pickedGift, setPickedGift] = useState(() => (window.__TWEAKS?.giftPicked === false ? null : 'g1'));
  const [giftSheet, setGiftSheet] = useState(false);

  // React to tweaks toggle
  useEffect(() => {
    const handler = (e) => {
      const t = e.detail || window.__TWEAKS || {};
      if (t.giftPicked === false) setPickedGift(null);
      else if (t.giftPicked === true) setPickedGift((p) => p || 'g1');
      if (t.cartState && M_ITEMS_BY_STATE[t.cartState]) {
        setItems(M_ITEMS_BY_STATE[t.cartState].map(it => ({ ...it })));
        if (t.cartState === 'small') setPickedGift(null);
      }
    };
    window.addEventListener('tweakschange', handler);
    return () => window.removeEventListener('tweakschange', handler);
  }, []);

  const { subtotal, productSavings } = useMemo(() => {
    let s = 0, o = 0;
    for (const it of items) { s += it.unit * it.qty; o += (it.orig ?? it.unit) * it.qty; }
    return { subtotal: s, productSavings: o - s };
  }, [items]);

  const promoDiscount = useMemo(() => {
    if (!promo) return 0;
    if (promo.type === 'pct') return subtotal * (promo.value / 100);
    return Math.min(subtotal, promo.value);
  }, [promo, subtotal]);

  const selShip = M_SHIP.find(s => s.id === shipping);
  const freeReached = subtotal >= M_FREE;
  // In cart step: show only items subtotal minus promo. Shipping is selected in next step.
  const cartTotal = subtotal - promoDiscount;
  const cartSavings = productSavings + promoDiscount;
  const itemCount = items.reduce((s, it) => s + it.qty, 0);
  const toEur = (n) => n.toLocaleString('sk-SK', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';

  const push = (msg, kind = 'ok') => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, msg, kind }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2200);
  };

  const updateQty = (id, d) => setItems(p => p.map(it => it.id === id ? { ...it, qty: Math.max(1, Math.min(99, it.qty + d)) } : it));
  const removeItem = (id) => {
    setRemoving(id);
    setTimeout(() => { setItems(p => p.filter(it => it.id !== id)); setRemoving(null); push('Odstránené'); }, 280);
  };

  const applyPromo = () => {
    const c = promoInput.trim().toUpperCase();
    if (!c) return;
    if (M_PROMO[c]) { setPromo({ code: c, ...M_PROMO[c] }); setPromoInput(''); push(`Kód ${c} aktivovaný`); }
    else push('Neplatný kód', 'err');
  };

  const addCross = (p) => {
    const a = items.find(it => it.id === p.id);
    if (a) setItems(prev => prev.map(it => it.id === p.id ? { ...it, qty: it.qty + 1 } : it));
    else setItems(prev => [...prev, { ...p, flavor: null, size: p.packSub.toLowerCase(), qty: 1 }]);
    setAddedIds(s => { const n = new Set(s); n.add(p.id); return n; });
    setTimeout(() => setAddedIds(s => { const n = new Set(s); n.delete(p.id); return n; }), 1000);
    push('Pridané');
  };

  const toggleCard = (k) => setOpenCard(o => o === k ? null : k);
  const isEmpty = items.length === 0;

  return (
    <div className="m">
      <MStatusBar />
      <div className="m-hd">
        <div className="m-hd-top">
          <button className="m-back" aria-label="Späť"><Icon name="chev" size={18} stroke={2.5} style={{ transform: 'rotate(180deg)' }} /></button>
          <h1>Košík {!isEmpty && <small>· {itemCount} {itemCount === 1 ? 'ks' : 'ks'}</small>}</h1>
          <div className="spacer" aria-hidden="true" />
        </div>
        <div className="m-stepper">
          <div className="m-step active"><div className="bar" /><div className="lbl">Košík</div></div>
          <div className="m-step"><div className="bar" /><div className="lbl">Doprava</div></div>
          <div className="m-step"><div className="bar" /><div className="lbl">Zhrnutie</div></div>
        </div>
      </div>

      <div className="m-body">
        {isEmpty ? (
          <div className="m-empty">
            <div className="ic"><Icon name="cart" size={28} /></div>
            <h2>Košík je prázdny</h2>
            <p>Pozri si proteíny, vitamíny a športovú výživu.</p>
          </div>
        ) : (
          <>
            <div className="m-rewards">
              {(() => {
                const next = M_REWARDS.find(r => subtotal < r.amt);
                const pickedG = pickedGift ? M_GIFTS.find(g => g.id === pickedGift) : null;
                return (
                  <div className="m-rewards-msg">
                    {!next ? (
                      <><span className="emoji">🎉</span><span>Máš <strong>všetky odmeny</strong> odomknuté</span></>
                    ) : (
                      <><span>Ešte <strong>{toEur(next.amt - subtotal)}</strong> a získaš <strong className="reward">{next.kind === 'shipping' ? 'dopravu zadarmo' : next.kind === 'gift' ? 'darček' : 'vzorku'}</strong></span></>
                    )}
                  </div>
                );
              })()}
              <div className="m-chain">
                {(() => {
                  const stopPct = (i) => (i / (M_REWARDS.length - 1)) * 100;
                  let fillPct = 0;
                  for (let i = 0; i < M_REWARDS.length; i++) {
                    const r = M_REWARDS[i];
                    if (subtotal >= r.amt) {
                      fillPct = stopPct(i);
                      const next = M_REWARDS[i + 1];
                      if (next) {
                        const segFrac = Math.min(1, Math.max(0, (subtotal - r.amt) / (next.amt - r.amt)));
                        fillPct += (stopPct(i + 1) - stopPct(i)) * segFrac;
                      }
                    }
                  }
                  return (
                    <>
                      <div className="m-chain-line">
                        <div className={"m-chain-fill" + (freeReached ? ' done' : '')} style={{ width: fillPct + '%' }} />
                      </div>
                      {M_REWARDS.map((r, i) => {
                        const unlocked = subtotal >= r.amt;
                        return (
                          <div key={r.amt} className={"m-chain-stop" + (unlocked ? ' unlocked' : '')} style={{ left: `${stopPct(i)}%` }}>
                            <div className="dot">
                              <Icon name={unlocked ? 'check' : (r.kind === 'shipping' ? 'truck' : r.kind === 'gift' ? 'gift' : 'sparkles')} size={14} />
                            </div>
                            <div className="amt">{r.amt} €</div>
                          </div>
                        );
                      })}
                    </>
                  );
                })()}
              </div>
              {subtotal >= 40 && (() => {
                const g = pickedGift ? M_GIFTS.find(x => x.id === pickedGift) : null;
                return (
                  <button className={"m-gift-cta" + (g ? ' picked' : '')} onClick={() => setGiftSheet(true)} type="button">
                    <span className="gic"><Icon name="gift" size={18} /></span>
                    {g ? (
                      <>
                        <span className="label">
                          <strong>{g.name}</strong>
                          <small>tvoj darček · zmeniť</small>
                        </span>
                        <span className="trail-chev"><Icon name="chev" size={14} /></span>
                      </>
                    ) : (
                      <>
                        <span className="label">
                          <strong>Vyber si darček zadarmo</strong>
                        </span>
                        <span className="cta-arrow"><Icon name="chev" size={14} /></span>
                      </>
                    )}
                  </button>
                );
              })()}
            </div>

            <div className="m-items">
              {items.map(it => (
                <div key={it.id} className={"m-item" + (removing === it.id ? ' removing' : '')}>
                  <div className="m-item-img" style={{ background: `linear-gradient(135deg, ${it.packColor}10, #F7F8FA)` }}>
                    {it.flag && <div className={"flag" + (it.flag === 'NOVÉ' ? ' new' : '')}>{it.flag}</div>}
                    <ProductVisual kind={it.visual || 'tub'} color={it.packColor} label={it.packLabel} sub={it.packSub} />
                  </div>
                  <div className="m-item-info">
                    <div className="m-item-name">{it.name}</div>
                    <div className="m-item-meta">
                      {it.flavor && <span className="chip">{it.flavor}</span>}
                      <span className="chip">{it.size}</span>
                    </div>
                  </div>
                  <div className="m-item-right">
                    <div className="m-item-price">
                      {toEur(it.unit * it.qty)}
                      {it.orig && <span className="orig">{toEur(it.orig * it.qty)}</span>}
                    </div>
                    <div className="m-qty">
                      <button
                        onClick={() => it.qty <= 1 ? removeItem(it.id) : updateQty(it.id, -1)}
                        aria-label={it.qty <= 1 ? 'Odstrániť položku' : 'Znížiť množstvo'}
                        className={it.qty <= 1 ? 'danger' : ''}
                      >
                        <Icon name={it.qty <= 1 ? 'trash' : 'minus'} size={12} />
                      </button>
                      <span className="val">{it.qty}</span>
                      <button onClick={() => updateQty(it.id, 1)} aria-label="Zvýšiť množstvo"><Icon name="plus" size={12} /></button>
                    </div>
                  </div>
                </div>
              ))}
              {subtotal >= 40 && pickedGift && (() => {
                const g = M_GIFTS.find(x => x.id === pickedGift);
                if (!g) return null;
                return (
                  <div className="m-gift">
                    <span className="m-gift-pill"><Icon name="gift" size={11} />DARČEK</span>
                    <span className="m-gift-name">{g.name}</span>
                    <span className="m-gift-price">ZADARMO</span>
                  </div>
                );
              })()}
            </div>

            {/* Accordion cards */}
            <div className={"m-card" + (openCard === 'promo' ? ' open' : '')}>
              <div className="m-card-head" onClick={() => toggleCard('promo')}>
                <div className="ic"><Icon name="tag" size={18} /></div>
                <div className="title">Zľavový kód</div>
                <div className={"val" + (promo ? ' ok' : '')}>{promo ? `✓ ${promo.code}` : 'pridať'}</div>
                <div className="chev"><Icon name="chev" size={16} /></div>
              </div>
              <div className="m-card-body">
                {!promo ? (
                  <>
                    <div className="m-promo">
                      <input type="text" placeholder="napr. LETO10" value={promoInput}
                        onChange={e => setPromoInput(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && applyPromo()} />
                      <button onClick={applyPromo}>Použiť</button>
                    </div>
                    <div style={{ marginTop: 8, fontSize: 11, color: 'var(--muted)' }}>
                      Tip: <strong style={{ color: 'var(--color-1)' }}>LETO10</strong> = -10 %
                    </div>
                  </>
                ) : (
                  <div className="m-promo-applied">
                    <span className="tag">{promo.code}</span>
                    <span>{promo.label}</span>
                    <button className="x" onClick={() => setPromo(null)}><Icon name="x" size={12} /></button>
                  </div>
                )}
              </div>
            </div>

            <div className="m-sum">
              <div className="m-sum-row"><span>Medzisúčet</span><span className="v">{toEur(subtotal)}</span></div>
              {productSavings > 0 && <div className="m-sum-row discount"><span>Zľava produktov</span><span className="v">-{toEur(productSavings)}</span></div>}
              {promo && <div className="m-sum-row discount"><span>Kód {promo.code}</span><span className="v">-{toEur(promoDiscount)}</span></div>}
              <div className="m-sum-row" style={{ color: 'var(--muted)' }}>
                <span>Doprava</span>
                <span className="v" style={{ color: 'var(--muted)', fontWeight: 500 }}>vyberieš v ďalšom kroku</span>
              </div>
            </div>

            {/* Cross-sell */}
            <div className="m-cross">
              <h2>Často kupované spolu<small>k proteínu a kreatínu</small></h2>
              <div className="m-cross-scroll">
                {M_CROSS.map(p => (
                  <div key={p.id} className="m-prod">
                    <div className="img" style={{ background: `linear-gradient(135deg, ${p.packColor}10, #F7F8FA)` }}>
                      {p.flag && <div className={"flag-top" + (p.flag === 'NOVÉ' ? ' new' : '')}>{p.flag}</div>}
                      <ProductVisual kind={p.visual || 'tub'} color={p.packColor} label={p.packLabel} sub={p.packSub} />
                    </div>
                    <div className="m-prod-brand">{p.brand}</div>
                    <div className="m-prod-name">{p.name}</div>
                    <div className="m-prod-rating"><span className="s">★</span> {p.rating} ({p.reviews})</div>
                    <div className="m-prod-bottom">
                      <div>
                        <span className="m-prod-price">{toEur(p.unit)}</span>
                        {p.orig && <span className="m-prod-orig">{toEur(p.orig)}</span>}
                      </div>
                      <button className={"m-prod-add" + (addedIds.has(p.id) ? ' added' : '')} onClick={() => addCross(p)}>
                        <Icon name={addedIds.has(p.id) ? 'check' : 'plus'} size={16} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="m-trust">
              <div className="t"><Icon name="shield" size={14} /><div><strong>HACCP + GMP</strong> výroba v Spišskej Novej Vsi</div></div>
              <div className="t"><Icon name="flask" size={14} /><div><strong>Lab-testované</strong>, certifikáty pri produktoch</div></div>
              <div className="t"><Icon name="rotate" size={14} /><div><strong>14 dní na vrátenie</strong> bez udania dôvodu</div></div>
            </div>

            <div className="m-pay">
              <span className="chip visa">VISA</span>
              <span className="chip mc">MC</span>
              <span className="chip apay">Pay</span>
              <span className="chip gpay">G Pay</span>
              <span className="chip tb">TB</span>
              <span className="chip cod">Dobierka</span>
            </div>
          </>
        )}
      </div>

      {/* Toasts */}
      <div className="m-toast-wrap">
        {toasts.map(t => (
          <div key={t.id} className={"m-toast" + (t.kind === 'err' ? ' err' : '')}>
            <span className="ic"><Icon name={t.kind === 'err' ? 'x' : 'checkCircle'} size={14} /></span>{t.msg}
          </div>
        ))}
      </div>

      {/* Sticky bottom CTA */}
      {!isEmpty && (
        <div className="m-bottom">
          <div className="m-bottom-row">
            <div className="lbl">
              Medzisúčet<small className={freeReached ? 'ok' : ''}>{freeReached ? '+ doprava zadarmo ✓' : 'bez dopravy'}</small>
              {cartSavings > 0.01 && (
                <span className="m-bottom-saved"><Icon name="sparkles" size={11} />ušetril si <strong>{toEur(cartSavings)}</strong></span>
              )}
            </div>
            <div className="total">{toEur(cartTotal)}</div>
          </div>
          <button className="m-cta" onClick={() => push('Pokračujem na dopravu...')}>
            Pokračovať k doprave
            <Icon name="arrowRight" size={18} />
          </button>
        </div>
      )}
      {/* Gift picker bottom sheet */}
      {giftSheet && (
        <div className="m-sheet-root" onClick={() => setGiftSheet(false)}>
          <div className="m-sheet" onClick={e => e.stopPropagation()}>
            <div className="m-sheet-handle" />
            <div className="m-sheet-head">
              <div>
                <h3>Vyber si darček</h3>
                <p>Odomknutý pri nákupe nad 40 €</p>
              </div>
              <button className="m-sheet-x" onClick={() => setGiftSheet(false)} aria-label="Zavrieť"><Icon name="x" size={16} /></button>
            </div>
            <div className="m-sheet-gifts">
              {M_GIFTS.map(g => (
                <button
                  key={g.id}
                  className={"m-sheet-gift" + (pickedGift === g.id ? ' picked' : '')}
                  onClick={() => { setPickedGift(g.id); setGiftSheet(false); push('Darček pridaný'); }}
                  type="button"
                >
                  <div className="img" style={{ background: `linear-gradient(135deg, ${g.packColor}10, #F7F8FA)` }}>
                    <ProductVisual kind={g.visual || 'tub'} color={g.packColor} label={g.packLabel} sub={g.packSub} />
                  </div>
                  <div className="info">
                    <div className="nm">{g.name}</div>
                    <div className="pr"><span className="orig">{toEur(g.origPrice)}</span><span className="free">ZADARMO</span></div>
                  </div>
                  <div className="radio">{pickedGift === g.id && <Icon name="check" size={12} />}</div>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.MobileCart = MobileCart;
