/* linked.market — Cart, Pay & Notify, Payment success/failed */
(function () {
const { useState } = React;
const h = React.createElement;
const { naira, VENDORS, PRODUCTS, feeRate, platformFee } = window.LM_DATA;
const { Icon, Avatar, ImageBlock, VMark } = window;

function groupMarked(m) {
  const g = {};
  PRODUCTS.forEach(p => { if (m[p.id]) (g[p.vendor] ||= { vendor: VENDORS[p.vendor], items: [] }).items.push({ p, ...m[p.id] }); });
  return Object.values(g);
}
const gTotal = (g) => g.items.reduce((s, it) => s + it.p.price * it.qty, 0);
const allTotal = (gs) => gs.reduce((s, g) => s + gTotal(g), 0);
const variantStr = (v) => v ? Object.values(v).join(' · ') : '';

function TrustStrip({ children }) {
  return h('div', { className: 'trust-strip' }, h(Icon, { name: 'lock' }), children || h('span', null, 'Secured by Paystack · funds split to each vendor at checkout'));
}
function Qty({ v, onDelta }) {
  return h('div', { className: 'qty' }, h('button', { onClick: () => onDelta(-1), disabled: v <= 1 }, h(Icon, { name: 'minus' })), h('span', { className: 'v' }, v), h('button', { onClick: () => onDelta(1) }, h(Icon, { name: 'plus' })));
}
function Empty({ onBrowse }) {
  return h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '64px 32px' } },
    h('div', { style: { width: 88, height: 88, borderRadius: 24, background: 'var(--bg-sunk)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-4)', marginBottom: 22 } }, h(Icon, { name: 'cart', style: { width: 38, height: 38 } })),
    h('h2', { className: 't-display', style: { fontSize: 24 } }, 'Your cart is empty'),
    h('p', { style: { fontSize: 14.5, color: 'var(--ink-2)', marginTop: 10, maxWidth: 280, lineHeight: 1.55 } }, 'Mark products as you browse and pay for everything — across any number of vendors — in one secure checkout.'),
    h('button', { className: 'btn btn-primary btn-md', style: { marginTop: 22 }, onClick: onBrowse }, 'Start browsing'));
}

/* ===================== CART ===================== */
function Cart(props) {
  const { device, markedMap, onOpen, onDelta, onRemove, onPay, onBrowse } = props;
  const desktop = device === 'desktop';
  const groups = groupMarked(markedMap);
  const count = Object.keys(markedMap).length;
  const sub = allTotal(groups), fee = platformFee(sub), total = sub + fee;

  if (count === 0) return desktop
    ? h('div', { className: 'screen-fade', style: { maxWidth: 1160, margin: '0 auto' } }, h(Empty, { onBrowse }))
    : h('div', { className: 'screen-fade' }, h('div', { className: 'mtop' }, h('h1', { className: 't-display', style: { fontSize: 24 } }, 'Cart')), h(Empty, { onBrowse }));

  const summary = h('div', { className: 'card', style: { padding: 20 } },
    h('div', { className: 'eyebrow', style: { marginBottom: 12 } }, 'Payment summary'),
    h('div', { className: 'sumrow' }, h('span', { style: { color: 'var(--ink-2)' } }, 'Subtotal · ', count, ' items'), h('span', { className: 'price', style: { fontWeight: 600 } }, naira(sub))),
    h('div', { className: 'sumrow' }, h('span', { style: { color: 'var(--ink-2)' } }, 'Platform fee · ', (feeRate * 100).toFixed(1), '%'), h('span', { className: 'price', style: { fontWeight: 600 } }, naira(fee))),
    h('div', { className: 'sumrow total' }, h('span', null, 'Total'), h('span', { className: 'price t-display', style: { fontSize: 22 } }, naira(total))),
    h('button', { className: 'btn btn-primary btn-lg btn-block', style: { marginTop: 14 }, onClick: onPay }, h(Icon, { name: 'lock' }), 'Pay & Notify · ', naira(total)),
    h('div', { style: { marginTop: 12 } }, h(TrustStrip, null, h('span', null, 'One payment · ', groups.length, ' ' + (groups.length === 1 ? 'vendor' : 'vendors') + ' paid at once'))));

  const groupCards = groups.map(g => h('div', { className: 'mgroup', key: g.vendor.handle },
    h('div', { className: 'ghead' }, h(Avatar, { name: g.vendor.name, color: g.vendor.avatar, size: 30 }),
      h('div', { style: { flex: 1, minWidth: 0, lineHeight: 1.2 } }, h('div', { style: { display: 'flex', alignItems: 'center', gap: 5 } }, h('span', { style: { fontWeight: 600, fontSize: 14 } }, g.vendor.name), g.vendor.verified && h(VMark)), h('div', { className: 't-mono', style: { fontSize: 11, color: 'var(--ink-3)' } }, '@' + g.vendor.handle)),
      h('span', { className: 'badge badge-secure' }, h(Icon, { name: 'lock' }), 'Secure Pay')),
    g.items.map(it => h('div', { className: 'mrow', key: it.p.id },
      h(ImageBlock, { duo: it.p.duo, glyph: it.p.glyph, className: 'mthumb', style: { cursor: 'pointer' }, onClick: () => onOpen(it.p) }),
      h('div', { style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' } },
        h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 10 } }, h('div', { className: 'mname', onClick: () => onOpen(it.p), style: { cursor: 'pointer' } }, it.p.name),
          h('button', { className: 'icon-btn', style: { width: 30, height: 30, marginTop: -4, marginRight: -6 }, onClick: () => onRemove(it.p.id) }, h(Icon, { name: 'x' }))),
        variantStr(it.variant) && h('div', { className: 'mvar' }, variantStr(it.variant)),
        h('div', { style: { flex: 1 } }),
        h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 } }, h('span', { className: 'mprice price' }, naira(it.p.price * it.qty)), h(Qty, { v: it.qty, onDelta: (d) => onDelta(it.p.id, d) }))))),
    h('div', { className: 'gfoot' }, h('span', { style: { fontSize: 12.5, color: 'var(--ink-3)' } }, 'Vendor subtotal'), h('span', { className: 'price', style: { fontWeight: 700 } }, naira(gTotal(g))))));

  if (desktop) return h('div', { className: 'screen-fade', style: { maxWidth: 1160, margin: '0 auto', padding: '36px 40px 64px' } },
    h('h1', { className: 't-display', style: { fontSize: 34 } }, 'Cart'),
    h('div', { style: { fontSize: 14, color: 'var(--ink-3)', margin: '6px 0 28px' } }, count, ' items · ', groups.length, ' vendors · ', h('span', null, 'one secure payment')),
    h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 340px', gap: 28, alignItems: 'start' } },
      h('div', { style: { display: 'flex', flexDirection: 'column', gap: 18 } }, groupCards),
      h('div', { style: { position: 'sticky', top: 26 } }, summary)));

  return h(React.Fragment, null,
    h('div', { className: 'lm-scroll screen-fade' },
      h('div', { className: 'mtop', style: { paddingBottom: 6 } }, h('div', null, h('h1', { className: 't-display', style: { fontSize: 24 } }, 'Cart'), h('div', { style: { fontSize: 13, color: 'var(--ink-3)', marginTop: 2 } }, count, ' items · ', groups.length, ' vendors'))),
      h('div', { style: { padding: '14px 16px 220px', display: 'flex', flexDirection: 'column', gap: 16 } }, groupCards, h(TrustStrip))),
    h('div', { className: 'msticky', style: { flexDirection: 'column', gap: 8, alignItems: 'stretch' } },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '0 2px' } }, h('span', { style: { fontSize: 13, color: 'var(--ink-3)' } }, 'Total · incl. fee'), h('span', { className: 'price t-display', style: { fontSize: 22 } }, naira(total))),
      h('button', { className: 'btn btn-primary btn-lg btn-block', onClick: onPay }, h(Icon, { name: 'lock' }), 'Pay & Notify · ', naira(total))));
}

/* ===================== PAY & NOTIFY REVIEW ===================== */
function PayReview(props) {
  const { device, markedMap, onConfirm, onBack } = props;
  const desktop = device === 'desktop';
  const [method, setMethod] = useState('paystack');
  const [busy, setBusy] = useState(false);
  const groups = groupMarked(markedMap);
  const sub = allTotal(groups), fee = platformFee(sub), total = sub + fee;
  const pay = () => { setBusy(true); setTimeout(() => onConfirm(), 1400); };

  const inner = h('div', { style: { maxWidth: 560, margin: '0 auto' } },
    h('div', { className: 'eyebrow', style: { marginBottom: 6 } }, 'Pay & Notify'),
    h('h1', { className: 't-display', style: { fontSize: desktop ? 32 : 26 } }, 'You’re paying ', naira(total)),
    h('p', { style: { fontSize: 14.5, color: 'var(--ink-2)', margin: '8px 0 22px' } }, 'across ', h('b', { style: { color: 'var(--ink)' } }, groups.length + (groups.length === 1 ? ' vendor' : ' vendors')), ' in one secure payment. Each vendor is credited directly.'),
    h('div', { className: 'eyebrow', style: { marginBottom: 8 } }, 'Split breakdown'),
    h('div', { className: 'card', style: { padding: '4px 16px', marginBottom: 20 } },
      groups.map(g => h('div', { className: 'splitrow', key: g.vendor.handle },
        h(Avatar, { name: g.vendor.name, color: g.vendor.avatar, size: 34 }),
        h('div', { style: { flex: 1, minWidth: 0, lineHeight: 1.2 } }, h('div', { style: { display: 'flex', alignItems: 'center', gap: 5 } }, h('span', { style: { fontWeight: 600, fontSize: 14 } }, g.vendor.name), g.vendor.verified && h(VMark)), h('div', { style: { fontSize: 12, color: 'var(--ink-3)' } }, g.items.length + ' item' + (g.items.length === 1 ? '' : 's'))),
        h('span', { className: 'price', style: { fontWeight: 700 } }, naira(gTotal(g)))))),
    h('div', { className: 'eyebrow', style: { marginBottom: 8 } }, 'Payment method'),
    h('div', { style: { display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 20 } },
      h('div', { className: 'method' + (method === 'paystack' ? ' on' : ''), onClick: () => setMethod('paystack') },
        h('div', { style: { width: 42, height: 42, borderRadius: 10, background: '#0AA5E9', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto', fontWeight: 800, fontFamily: 'var(--font-display)' } }, 'P'),
        h('div', { style: { flex: 1 } }, h('div', { style: { fontWeight: 600, fontSize: 14.5 } }, 'Pay with Paystack'), h('div', { style: { fontSize: 12, color: 'var(--ink-3)', marginTop: 1 } }, 'Card, bank, transfer or USSD')), h('div', { className: 'mradio' })),
      h('div', { className: 'method' + (method === 'transfer' ? ' on' : ''), onClick: () => setMethod('transfer') },
        h('div', { style: { width: 42, height: 42, borderRadius: 10, background: 'var(--bg-sunk)', color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' } }, h(Icon, { name: 'arrowUR' })),
        h('div', { style: { flex: 1 } }, h('div', { style: { fontWeight: 600, fontSize: 14.5 } }, 'Bank transfer'), h('div', { style: { fontSize: 12, color: 'var(--warning)', marginTop: 1 } }, 'Outside platform protection')), h('div', { className: 'mradio' }))),
    h('div', { className: 'card', style: { padding: '8px 16px', marginBottom: 18 } },
      h('div', { className: 'sumrow' }, h('span', { style: { color: 'var(--ink-2)' } }, 'Subtotal'), h('span', { className: 'price' }, naira(sub))),
      h('div', { className: 'sumrow' }, h('span', { style: { color: 'var(--ink-2)' } }, 'Platform fee'), h('span', { className: 'price' }, naira(fee))),
      h('div', { className: 'sumrow total' }, h('span', null, 'Total'), h('span', { className: 'price', style: { fontSize: 18 } }, naira(total)))),
    h('button', { className: 'btn btn-lg btn-block ' + (method === 'paystack' ? 'paystack-btn' : 'btn-primary'), disabled: busy, onClick: pay },
      busy ? h(React.Fragment, null, h('span', { className: 'spin' }), 'Connecting to Paystack…') : h(React.Fragment, null, h(Icon, { name: 'lock' }), method === 'paystack' ? 'Pay ' + naira(total) + ' securely' : 'Continue to transfer')),
    h('p', { style: { fontSize: 11.5, color: 'var(--ink-3)', textAlign: 'center', marginTop: 12, lineHeight: 1.5 } }, 'Payment completes on the secure Paystack page. Vendors are notified on WhatsApp the instant it clears.'));

  return h('div', { className: 'lm-scroll screen-fade', style: { padding: desktop ? '28px 40px 64px' : '46px 18px 40px' } },
    h('button', { className: 'btn btn-ghost btn-sm', style: { marginBottom: 14, paddingLeft: 8 }, onClick: onBack }, h(Icon, { name: 'chevL' }), 'Back to cart'), inner);
}

/* ===================== PAYMENT SUCCESS ===================== */
function PaySuccess(props) {
  const { device, order, onViewOrder, onBrowse } = props;
  if (!order) return null;
  const desktop = device === 'desktop';
  const names = order.groups.map(g => g.vendor.name);
  const notified = names.length === 1 ? names[0] : names.slice(0, -1).join(', ') + ' & ' + names.slice(-1);
  return h('div', { className: 'lm-scroll screen-fade', style: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: desktop ? '56px 40px' : '64px 22px 40px', background: 'var(--bg)' } },
    h('div', { style: { width: '100%', maxWidth: 460 } },
      h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' } },
        h('div', { className: 'confirm-ring' }, h(Icon, { name: 'check' })),
        h('div', { className: 'eyebrow', style: { marginTop: 22, color: 'var(--verified)' } }, 'Paid via Paystack'),
        h('h1', { className: 't-display', style: { fontSize: desktop ? 36 : 30, marginTop: 8 } }, naira(order.total), ' paid'),
        h('p', { style: { fontSize: 14.5, color: 'var(--ink-2)', marginTop: 12, maxWidth: 340, lineHeight: 1.55 } }, 'We’ve notified ', h('b', { style: { color: 'var(--ink)' } }, notified), ' on WhatsApp. They’ll confirm and arrange delivery with you shortly.')),
      h('div', { className: 'card', style: { padding: 18, marginTop: 28 } },
        h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 } }, h('span', { className: 'eyebrow' }, 'Order ' + order.ref), h('span', { className: 'badge badge-paid' }, h(Icon, { name: 'check' }), 'Paid')),
        order.groups.map(g => h('div', { key: g.vendor.handle, className: 'splitrow' },
          h(Avatar, { name: g.vendor.name, color: g.vendor.avatar, size: 32 }),
          h('div', { style: { flex: 1, minWidth: 0 } }, h('div', { style: { fontWeight: 600, fontSize: 13.5 } }, g.vendor.name), h('div', { style: { fontSize: 12, color: 'var(--ink-3)' } }, g.items.length + ' item' + (g.items.length === 1 ? '' : 's'))),
          h('span', { className: 'price', style: { fontWeight: 700 } }, naira(g.subtotal)))),
        h('div', { style: { marginTop: 12 } }, h(TrustStrip, null, h('span', null, 'Funds split to each vendor · linked.market protected')))),
      h('div', { style: { display: 'flex', gap: 10, marginTop: 22 } },
        h('button', { className: 'btn btn-secondary btn-lg', style: { flex: 1 }, onClick: onBrowse }, 'Keep browsing'),
        h('button', { className: 'btn btn-primary btn-lg', style: { flex: 1 }, onClick: onViewOrder }, h(Icon, { name: 'receipt' }), 'View order'))));
}

/* ===================== PAYMENT FAILED ===================== */
function PayFailed(props) {
  const { device, onRetry, onBack } = props;
  return h('div', { className: 'lm-scroll screen-fade', style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '100%', textAlign: 'center', padding: 32, background: 'var(--bg)' } },
    h('div', { style: { width: 78, height: 78, borderRadius: 99, background: 'var(--error-tint)', color: 'var(--error)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 } }, h(Icon, { name: 'x', style: { width: 36, height: 36 } })),
    h('h1', { className: 't-display', style: { fontSize: 28 } }, 'Payment didn’t go through'),
    h('p', { style: { fontSize: 14.5, color: 'var(--ink-2)', margin: '10px 0 6px', maxWidth: 320, lineHeight: 1.55 } }, 'Your card wasn’t charged. This is usually a network hiccup — your cart is safe.'),
    h('p', { style: { fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 24 } }, 'Ref: PSK_3F9A · declined'),
    h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10, width: '100%', maxWidth: 320 } },
      h('button', { className: 'btn btn-primary btn-lg btn-block', onClick: onRetry }, h(Icon, { name: 'lock' }), 'Try payment again'),
      h('button', { className: 'btn btn-ghost btn-md btn-block', onClick: onBack }, 'Back to cart'),
      h('button', { className: 'btn btn-ghost btn-sm btn-block', style: { color: 'var(--ink-3)' } }, 'Contact support')));
}

Object.assign(window, { CartScreen: Cart, PayReview, PaySuccess, PayFailed });
})();
