// Vival PWA — primitive components
const { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext } = React;

function Icon({ name, className = '', ...rest }) {
  return <svg className={`icon ${className}`} {...rest}><use href={`#icon-${name}`} /></svg>;
}

function Button({ variant = 'default', size, icon, iconRight, children, block, ...rest }) {
  const cls = [
    'btn',
    variant === 'primary' && 'btn-primary',
    variant === 'ghost' && 'btn-ghost',
    variant === 'outline' && 'btn-outline',
    variant === 'danger' && 'btn-danger',
    size === 'lg' && 'btn-lg',
    size === 'sm' && 'btn-sm',
    !children && 'btn-icon',
    size === 'sm' && !children && 'btn-icon-sm',
    block && 'btn-block',
  ].filter(Boolean).join(' ');
  return (
    <button className={cls} {...rest}>
      {icon && <Icon name={icon} />}
      {children}
      {iconRight && <Icon name={iconRight} />}
    </button>
  );
}

function Input({ icon, size, ...rest }) {
  if (!icon) return <input className={`input ${size === 'lg' ? 'input-lg' : ''}`} {...rest} />;
  return (
    <div className={`input-with-icon ${size === 'lg' ? 'input-lg-wrap' : ''}`}>
      <Icon name={icon} />
      <input className="input" {...rest} />
    </div>
  );
}

function Badge({ kind, children }) { return <span className={`badge badge-${kind}`}>{children}</span>; }

function Modal({ open, onClose, title, children, footer, size }) {
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={`modal ${size === 'lg' ? 'modal-lg' : ''} ${size === 'xl' ? 'modal-xl' : ''}`} onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <h3 className="modal-title">{title}</h3>
          <Button variant="ghost" size="sm" icon="close" onClick={onClose} aria-label="Fermer" />
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>
  );
}

function Drawer({ open, onClose, children }) {
  if (!open) return null;
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <div className="drawer" onClick={e => e.stopPropagation()}>{children}</div>
    </>
  );
}

function StatusPill({ status }) {
  const label = { 'en-cours':'En cours', 'prete':'Prête', 'livree':'Livrée', 'payee':'Payée', 'annulee':'Annulée' }[status] || status;
  return <span className={`status-pill status-${status}`}>{label}</span>;
}

function Avatar({ name, color }) {
  const initials = name.split(' ').slice(0,2).map(s => s[0]).join('').toUpperCase();
  return <div className="customer-avatar">{initials}</div>;
}

function PriceDisplay({ value }) {
  const { euros, cents } = formatPrice(value);
  return <span className="product-price">{euros},<span className="cents">{cents}</span>€</span>;
}

function parseQuantity(str) {
  if (!str) return null;
  const s = String(str).toLowerCase().replace(',', '.');
  // Sum packs: "pack 6×33cl", "6x330ml", "4×125g", "2 x 1l"
  const packMatch = s.match(/(\d+(?:\.\d+)?)\s*[x×*]\s*(\d+(?:\.\d+)?)\s*(kg|g|ml|cl|l)\b/);
  if (packMatch) {
    const count = parseFloat(packMatch[1]);
    const val = parseFloat(packMatch[2]);
    const unit = packMatch[3];
    return normalize(count * val, unit);
  }
  const m = s.match(/(\d+(?:\.\d+)?)\s*(kg|g|ml|cl|l)\b/);
  if (m) return normalize(parseFloat(m[1]), m[2]);
  return null;
}
function normalize(value, unit) {
  // returns { kg?: number, L?: number }
  if (unit === 'kg') return { kg: value };
  if (unit === 'g') return { kg: value / 1000 };
  if (unit === 'l') return { L: value };
  if (unit === 'cl') return { L: value / 100 };
  if (unit === 'ml') return { L: value / 1000 };
  return null;
}
function unitPrice(product) {
  const q = parseQuantity(product.format) || parseQuantity(product.name);
  if (!q || !product.price) return null;
  if (q.L && q.L > 0) return { value: product.price / q.L, unit: 'L' };
  if (q.kg && q.kg > 0) return { value: product.price / q.kg, unit: 'kg' };
  return null;
}

function ProductTile({ product, onAdd, onOpen }) {
  const isOut = product.stock === 0;
  const isLow = product.stock > 0 && product.stock <= 3;
  return (
    <div className="product" onClick={onOpen} style={isOut ? {opacity:.65} : {}}>
      <div className="product-image">
        {product.image
          ? <img src={product.image} alt="" loading="lazy" onError={(e) => { e.target.style.display = 'none'; }} style={{width:'100%',height:'100%',objectFit:'contain'}} />
          : <Icon name={product.rayon} />}
        {product.badges.length > 0 && (
          <div className="product-badges">
            {product.badges.map(b => <Badge key={b} kind={b}>{b}</Badge>)}
            {isLow && <Badge kind="stock-low">plus que {product.stock}</Badge>}
          </div>
        )}
        {product.badges.length === 0 && isLow && (
          <div className="product-badges"><Badge kind="stock-low">plus que {product.stock}</Badge></div>
        )}
        {isOut && <div className="product-stock-overlay">Rupture</div>}
      </div>
      <div className="product-info">
        <div className="product-name">{product.name}</div>
        <div className="product-format">
          {product.format}
          {(() => { const u = unitPrice(product); return u ? <span className="muted" style={{marginLeft:6}}>• {u.value.toFixed(2).replace('.', ',')} €/{u.unit}</span> : null; })()}
        </div>
      </div>
      <div className="product-row">
        <PriceDisplay value={product.price} />
        <button className="product-plus" disabled={isOut} style={isOut?{opacity:.4,cursor:'not-allowed'}:{}} onClick={(e) => { e.stopPropagation(); if(!isOut) onAdd(); }} aria-label="Ajouter">
          <Icon name="plus" />
        </button>
      </div>
    </div>
  );
}

function QtyControl({ value, onChange, step = 1, byWeight = false }) {
  return (
    <div className="qty-control">
      <button className="qty-btn" onClick={() => onChange(Math.max(0, value - step))}><Icon name="minus" /></button>
      <span className="qty-value">{byWeight ? `${value.toFixed(value % 1 === 0 ? 0 : 2)}kg` : value}</span>
      <button className="qty-btn" onClick={() => onChange(value + step)}><Icon name="plus" /></button>
    </div>
  );
}

// Expose
Object.assign(window, { Icon, Button, Input, Badge, Modal, Drawer, StatusPill, Avatar, PriceDisplay, ProductTile, QtyControl });
