/* =============================================================
   KASDAP ONE — PRODUCT DETAIL
============================================================= */
const { useState: useStatePD, useMemo: useMemoPD, useEffect: useEffectPD } = React;

function ProductScreen({ id }) {
  const { productById, products, mode, priceOf, addToCart, toast, go, pricing, user, roleMeta } = useStore();
  const p = productById[id];
  const [qty, setQty] = useStatePD(mode === 'b2b' ? 1 : 1);
  useEffectPD(() => { setQty(1); }, [id, mode]);
  if (!p) return React.createElement('div', { className: 'page-wrap' }, 'Product not found');

  const pr = priceOf(p, mode, qty);
  const related = useMemoPD(() => products.filter(x => x.category === p.category && x.id !== p.id).slice(0, 6), [p, products]);

  const add = () => { addToCart(p.id, qty, mode); toast(`${qty} × ${p.name} added to ${mode.toUpperCase()} order`, 'ok'); };

  // b2b slab table
  const tier = user ? roleMeta(user.role).tier : 'distributor';
  const slabRows = mode === 'b2b' ? [{ min: 1, off: 0 }, ...pricing.slabs].map(s => {
    const boxPr = priceOf(p, 'b2b', s.min).unit;
    return { min: s.min, off: s.off, boxPr };
  }) : [];
  const activeSlab = slabRows.reduce((a, s) => qty >= s.min ? s.min : a, 1);

  const specs = [
    ['Salt composition', p.salt], ['Dosage form', p.type], ['Pack', p.packing],
    ['Packaging', p.packedIn], ['SKU code', p.sku], ['Product code', p.pcode || '—'],
    ['Division', p.manufacturer], ['Therapeutic class', (p.therapeutic || '').toLowerCase()],
  ];

  return React.createElement('div', { className: 'page-wrap' },
    React.createElement('div', { className: 'crumb' },
      React.createElement('button', { onClick: () => go('catalog') }, React.createElement(Icon, { name: 'back', size: 14 }), 'Catalogue'),
      React.createElement(Icon, { name: 'chevron', size: 13 }),
      React.createElement('span', null, p.category),
      React.createElement(Icon, { name: 'chevron', size: 13 }),
      React.createElement('span', { style: { color: 'var(--text-2)' } }, p.name)
    ),
    React.createElement('div', { className: 'pd' },
      /* media */
      React.createElement('div', { className: 'pd-media' },
        React.createElement('div', { className: 'pd-img' }, React.createElement(ProductImage, { p, radius: 24 })),
        React.createElement('div', { className: 'pd-badges' },
          React.createElement('span', { className: 'tag' }, React.createElement(Icon, { name: p.rx ? 'shield' : 'check', size: 13 }), p.rx ? 'Prescription (Rx)' : 'OTC'),
          React.createElement('span', { className: 'tag' }, React.createElement(Icon, { name: 'box', size: 13 }), (p.stock > 0 ? p.stock.toLocaleString('en-IN') + ' in stock' : 'Backorder')),
          React.createElement('span', { className: 'tag' }, React.createElement(Icon, { name: 'shieldCheck', size: 13 }), 'GMP certified')
        )
      ),
      /* info */
      React.createElement('div', { className: 'pd-info' },
        React.createElement('div', { className: 'pcat' }, p.manufacturer + ' · ' + p.category),
        React.createElement('h1', null, p.name),
        React.createElement('div', { className: 'pd-salt' }, p.salt),
        React.createElement('div', { className: 'pd-rate' },
          React.createElement(Stars, { value: p.rating, size: 15 }),
          React.createElement('b', null, p.rating), React.createElement('span', null, '(' + p.reviews + ' reviews)'),
          React.createElement('span', { className: 'dotsep', style: { width: 3, height: 3, borderRadius: '50%', background: 'var(--text-3)' } }),
          React.createElement('span', null, 'SKU ' + p.sku)
        ),
        /* price card */
        React.createElement('div', { className: 'pd-price-card' },
          React.createElement('div', { className: 'eyebrow', style: { marginBottom: 10 } }, mode === 'd2c' ? 'Retail price · per pack' : (roleMeta(user.role).label + ' price · per box of ' + p.ppb + ' packs')),
          React.createElement('div', { className: 'pd-price-top' },
            React.createElement('div', null,
              React.createElement('span', { className: 'pd-now' }, fmt(pr.unit), React.createElement('small', null, mode === 'd2c' ? ' /pack' : ' /box')),
              React.createElement('div', { style: { marginTop: 6, display: 'flex', gap: 10, alignItems: 'center' } },
                React.createElement('span', { className: 'pd-mrp' }, mode === 'd2c' ? fmt(pr.mrp) + ' MRP' : fmt(pr.boxMrp) + ' MRP'),
                pr.savePct > 0 && React.createElement('span', { className: 'pd-savechip' }, React.createElement(Icon, { name: 'tag', size: 12 }), pr.savePct + '% off'))
            ),
            mode === 'b2b' && React.createElement('div', { style: { textAlign: 'right' } },
              React.createElement('div', { className: 'faint', style: { fontSize: '.66rem' } }, 'Effective per pack'),
              React.createElement('div', { className: 'mono', style: { fontSize: '1.1rem', fontWeight: 700 } }, fmt(pr.packPrice)))
          ),
          React.createElement('div', { className: 'pd-buy' },
            React.createElement('div', { className: 'qty' },
              React.createElement('button', { onClick: () => setQty(q => Math.max(1, q - 1)) }, React.createElement(Icon, { name: 'minus', size: 16 })),
              React.createElement('input', { value: qty, onChange: e => setQty(Math.max(1, parseInt(e.target.value) || 1)) }),
              React.createElement('button', { onClick: () => setQty(q => q + 1) }, React.createElement(Icon, { name: 'plus', size: 16 }))),
            React.createElement('button', { className: 'btn btn-accent btn-lg', style: { flex: 1 }, onClick: add },
              React.createElement(Icon, { name: mode === 'b2b' ? 'layers' : 'cart', size: 17 }),
              mode === 'b2b' ? 'Add ' + qty + ' box' + (qty > 1 ? 'es' : '') + ' to order' : 'Add to cart'),
            React.createElement('div', { style: { textAlign: 'right', minWidth: 90 } },
              React.createElement('div', { className: 'faint', style: { fontSize: '.64rem' } }, 'Line total'),
              React.createElement('div', { className: 'mono', style: { fontWeight: 800, fontSize: '1.05rem', color: 'var(--accent)' } }, fmt(pr.unit * qty)))
          ),
          mode === 'b2b' && React.createElement('table', { className: 'tier-table' },
            React.createElement('thead', null, React.createElement('tr', null,
              React.createElement('th', null, 'Order qty'), React.createElement('th', null, 'Extra off'), React.createElement('th', null, 'Price / box'))),
            React.createElement('tbody', null, slabRows.map(s => React.createElement('tr', { key: s.min, className: activeSlab === s.min ? 'active' : '' },
              React.createElement('td', null, s.min + (s.min === 1 ? ' box' : '+ boxes')),
              React.createElement('td', null, s.off ? (s.off * 100) + '%' : '—'),
              React.createElement('td', null, fmt(s.boxPr)))))
          )
        ),
        /* specs */
        React.createElement('div', { className: 'sec-title-row' }, React.createElement('h3', null, 'Composition & details')),
        React.createElement('div', { className: 'spec-grid' },
          specs.map(([k, v]) => React.createElement('div', { className: 'sp', key: k },
            React.createElement('div', { className: 'k' }, k),
            React.createElement('div', { className: 'v', style: k === 'Therapeutic class' ? { textTransform: 'capitalize' } : null }, v || '—')))
        ),
        React.createElement('div', { style: { marginTop: 18, padding: 16, borderRadius: 14, background: 'var(--surface-2)', border: '1px solid var(--line)', fontSize: '.8rem', color: 'var(--text-2)', lineHeight: 1.6, display: 'flex', gap: 10 } },
          React.createElement(Icon, { name: 'shield', size: 18, style: { color: 'var(--amber)', flexShrink: 0, marginTop: 1 } }),
          React.createElement('span', null, p.rx ? 'This is a prescription medicine. A valid prescription is required at checkout. Self-medication can be harmful — consult a registered medical practitioner.' : 'Store in a cool, dry place away from direct sunlight. Keep out of reach of children. Read the label before use.'))
      )
    ),
    /* related */
    related.length > 0 && React.createElement(React.Fragment, null,
      React.createElement('div', { className: 'sec-title-row', style: { marginTop: 44 } },
        React.createElement('h3', null, 'More in ', p.category),
        React.createElement('button', { className: 'chip', onClick: () => go('catalog') }, 'View all', React.createElement(Icon, { name: 'arrow', size: 13 }))),
      React.createElement('div', { className: 'grid' }, related.map(rp => React.createElement(ProductCard, { key: rp.id, p: rp })))
    )
  );
}
Object.assign(window, { ProductScreen });
