// ui_kits/website/Cart.jsx
//
// Slide-in cart drawer. Reads cart state from window.Shop (shopify-feed.js),
// listens to 'tnt-cart-updated' for live updates, and on Checkout creates a
// Shopify-hosted checkout URL and redirects the browser there.
//
// Opens via a window-level 'app:open-cart' CustomEvent (Header dispatches it).
// App.jsx mounts a single <CartDrawer/> at the app shell level.

const cartStyles = {
  scrim: {
    position: 'fixed', inset: 0, zIndex: 80,
    background: 'rgba(15,15,15,0.45)',
    display: 'flex', justifyContent: 'flex-end',
    backdropFilter: 'blur(2px)',
  },
  panel: {
    width: 'min(420px, 100%)',
    height: '100%', background: '#fff',
    display: 'flex', flexDirection: 'column',
    boxShadow: '-12px 0 40px rgba(15,15,15,0.18)',
    animation: 'tntCartSlide 220ms var(--ease-out, ease-out)',
  },
  header: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '20px 22px',
    borderBottom: '1px solid var(--color-divider)',
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 22, color: 'var(--color-fg-strong)', margin: 0,
  },
  closeBtn: {
    width: 36, height: 36, borderRadius: '50%', border: 'none',
    background: 'var(--brand-cream)', cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'var(--font-sans)', fontSize: 18, color: '#151414',
  },
  body: { flex: 1, overflowY: 'auto', padding: '14px 22px' },
  empty: {
    padding: '64px 16px', textAlign: 'center',
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontSize: 18, color: 'var(--color-fg-muted)',
  },
  line: {
    display: 'grid', gridTemplateColumns: '72px 1fr auto', gap: 14,
    padding: '14px 0', borderBottom: '1px solid var(--color-divider)',
    alignItems: 'flex-start',
  },
  thumb: {
    width: 72, height: 72, borderRadius: 10, overflow: 'hidden',
    background: 'var(--brand-mint-wash)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  },
  thumbImg: { width: '100%', height: '100%', objectFit: 'cover' },
  thumbFallback: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    color: 'var(--brand-leaf)', fontSize: 22,
  },
  lineBody: { minWidth: 0 },
  lineTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 15, lineHeight: 1.3, color: 'var(--color-fg-strong)',
    margin: '0 0 4px',
  },
  linePrice: {
    fontFamily: 'var(--font-sans)', fontSize: 13,
    color: 'var(--color-fg-muted)', marginBottom: 8,
  },
  qtyRow: {
    display: 'inline-flex', alignItems: 'center', gap: 4,
    border: '1px solid var(--color-divider)', borderRadius: 999,
    padding: '2px 4px',
  },
  qtyBtn: {
    width: 26, height: 26, borderRadius: '50%', border: 'none',
    background: 'transparent', cursor: 'pointer',
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1, color: '#151414',
  },
  qtyVal: {
    minWidth: 22, textAlign: 'center',
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600, color: '#151414',
  },
  removeBtn: {
    background: 'none', border: 'none', cursor: 'pointer',
    padding: 0, marginTop: 6,
    fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
    letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
  lineRight: { textAlign: 'right' },
  lineTotal: {
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
    color: 'var(--color-fg-strong)',
  },
  foot: {
    borderTop: '1px solid var(--color-divider)',
    padding: '18px 22px 24px',
    background: '#fff',
  },
  totalsRow: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
    marginBottom: 12,
    fontFamily: 'var(--font-sans)',
  },
  totalsLabel: { fontSize: 13, color: 'var(--color-fg-muted)' },
  totalsValue: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 22, color: 'var(--color-fg-strong)',
  },
  shipRow: { display: 'flex', gap: 8, marginBottom: 12 },
  shipField: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 4 },
  shipLabel: {
    fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
    letterSpacing: '0.04em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
  shipSelect: {
    width: '100%', padding: '10px 12px',
    fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-fg-strong)',
    background: '#fff', border: '1px solid var(--color-divider)', borderRadius: 8,
    cursor: 'pointer',
  },
  checkoutBtn: {
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    width: '100%',
    padding: '14px 18px',
    background: 'var(--brand-leaf)', color: '#fff',
    border: 'none', borderRadius: 10,
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
    letterSpacing: '0.04em', cursor: 'pointer',
    transition: 'background 200ms var(--ease-out)',
  },
  hint: {
    fontFamily: 'var(--font-sans)', fontSize: 11,
    color: 'var(--color-fg-muted)', textAlign: 'center', marginTop: 10,
  },
  err: {
    fontFamily: 'var(--font-sans)', fontSize: 12,
    color: '#B33A3A', marginTop: 10, textAlign: 'center',
  },
};

// Countries we ship to (must match shipping_address_collection in functions/checkout.js).
const SHIP_COUNTRIES = [
  { code: 'US', label: 'United States' },
  { code: 'CA', label: 'Canada' },
  { code: 'MX', label: 'Mexico' },
];

// US states + DC. AK/HI map to the "remote" shipping zone in checkout.js.
const US_STATES = [
  'AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA',
  'KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM',
  'NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA',
  'WV','WI','WY',
];

// Pricing helper — fall back gracefully when the cart line was added before
// Shopify config was wired (no priceAmount, just a display price string).
function formatLineTotal(line) {
  if (!line) return '';
  const n = Number(line.priceAmount);
  if (!isNaN(n) && n > 0) {
    try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(n * (line.quantity || 0)); }
    catch (e) { return '$' + (n * (line.quantity || 0)).toFixed(2); }
  }
  return line.price || '';
}

function formatSubtotal(amount) {
  if (!amount || isNaN(amount)) return '';
  try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(amount); }
  catch (e) { return '$' + amount.toFixed(2); }
}

function CartDrawer({ open, onClose }) {
  const lang = React.useContext(LangContext);
  const [cart, setCart] = React.useState(() => (window.Shop ? window.Shop.getCart() : { lines: [], count: 0, subtotal: 0 }));
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [country, setCountry] = React.useState('US');
  const [usState, setUsState] = React.useState('');
  const [zip, setZip] = React.useState('');
  const [shipOpts, setShipOpts] = React.useState(null); // null=unknown, []=none
  const configured = window.Shop && window.Shop.isConfigured && window.Shop.isConfigured();

  // Live-update from cart engine. Always re-read via getCart() — the event
  // detail carries the raw cart (lines only); count + subtotal are computed.
  React.useEffect(() => {
    const handler = () => setCart(window.Shop ? window.Shop.getCart() : { lines: [], count: 0, subtotal: 0 });
    window.addEventListener('tnt-cart-updated', handler);
    return () => window.removeEventListener('tnt-cart-updated', handler);
  }, []);

  // Esc to close, body-scroll lock while open
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  // Fetch a live shipping preview once we have enough address info. US needs
  // state + a 5-digit ZIP; CA/MX are ready immediately. Debounced so we don't
  // hammer /shipping-rate on every keystroke.
  React.useEffect(() => {
    let live = true;
    const ready = country !== 'US' || (usState && zip.length === 5);
    if (!ready) { setShipOpts(null); return; }
    const t = setTimeout(async () => {
      const opts = await window.Shop.fetchShippingOptions({ country, state: country === 'US' ? usState : '', zip });
      if (live) setShipOpts(opts);
    }, 400);
    return () => { live = false; clearTimeout(t); };
  }, [country, usState, zip]);

  if (!open) return null;

  const T = lang === 'es' ? {
    title: 'Tu carrito', close: 'Cerrar', empty: 'Tu carrito está vacío.',
    qty: 'Cant.', remove: 'Quitar', subtotal: 'Subtotal',
    checkout: 'Pagar', checking: 'Procesando…',
    shippingHint: 'El costo de envío e impuestos se calcula en el checkout.',
    notConfigured: 'La tienda aún no está conectada. Configura Shopify en index.html para activar el checkout.',
    country: 'País', state: 'Estado', statePh: 'Selecciona…',
    needState: 'Selecciona tu estado para calcular el envío.',
    zip: 'Código postal', zipPh: '90049',
    needZip: 'Ingresa tu código postal para calcular el envío.',
    shipFrom: 'Envío:',
  } : {
    title: 'Your cart', close: 'Close', empty: 'Your cart is empty.',
    qty: 'Qty', remove: 'Remove', subtotal: 'Subtotal',
    checkout: 'Checkout', checking: 'Processing…',
    shippingHint: 'Shipping and taxes calculated at checkout.',
    notConfigured: 'The store is not connected yet. Configure Shopify in index.html to enable checkout.',
    country: 'Country', state: 'State', statePh: 'Select…',
    needState: 'Select your state to calculate shipping.',
    zip: 'ZIP code', zipPh: '90049',
    needZip: 'Enter your ZIP to calculate shipping.',
    shipFrom: 'Shipping:',
  };

  const onCheckout = async () => {
    if (!configured) { setErr(T.notConfigured); return; }
    if (country === 'US' && !usState) { setErr(T.needState); return; }
    if (country === 'US' && zip.length !== 5) { setErr(T.needZip); return; }
    setBusy(true); setErr('');
    try {
      const url = await window.Shop.createCheckoutUrl({ country, state: country === 'US' ? usState : '', zip });
      window.location.href = url;
    } catch (e) {
      setErr(e.message || 'Checkout failed.');
      setBusy(false);
    }
  };

  const lines = cart.lines || [];

  return (
    <div style={cartStyles.scrim} onClick={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
         role="dialog" aria-modal="true" aria-label={T.title}>
      <div style={cartStyles.panel}>
        <div style={cartStyles.header}>
          <h2 style={cartStyles.title}>{T.title} {cart.count ? `(${cart.count})` : ''}</h2>
          <button style={cartStyles.closeBtn} onClick={onClose} aria-label={T.close}>×</button>
        </div>

        <div style={cartStyles.body}>
          {lines.length === 0
            ? <div style={cartStyles.empty}>{T.empty}</div>
            : lines.map(line => (
                <div key={line.variantId} style={cartStyles.line}>
                  <div style={cartStyles.thumb}>
                    {line.image
                      ? <img src={line.image} alt="" style={cartStyles.thumbImg}/>
                      : <span style={cartStyles.thumbFallback}>{(line.title || '·').slice(0,1)}</span>}
                  </div>
                  <div style={cartStyles.lineBody}>
                    <h3 style={cartStyles.lineTitle}>{line.title || '—'}</h3>
                    <div style={cartStyles.linePrice}>{line.price || ''}</div>
                    <div style={cartStyles.qtyRow}>
                      <button style={cartStyles.qtyBtn} aria-label="-"
                              onClick={() => window.Shop.setLineQty(line.variantId, Math.max(0, (line.quantity || 1) - 1))}>−</button>
                      <span style={cartStyles.qtyVal}>{line.quantity}</span>
                      <button style={cartStyles.qtyBtn} aria-label="+"
                              onClick={() => window.Shop.setLineQty(line.variantId, (line.quantity || 0) + 1)}>+</button>
                    </div>
                    <div>
                      <button style={cartStyles.removeBtn}
                              onClick={() => window.Shop.removeLine(line.variantId)}>
                        {T.remove}
                      </button>
                    </div>
                  </div>
                  <div style={cartStyles.lineRight}>
                    <div style={cartStyles.lineTotal}>{formatLineTotal(line)}</div>
                  </div>
                </div>
              ))}
        </div>

        {lines.length > 0 && (
          <div style={cartStyles.foot}>
            <div style={cartStyles.totalsRow}>
              <span style={cartStyles.totalsLabel}>{T.subtotal}</span>
              <span style={cartStyles.totalsValue}>{formatSubtotal(cart.subtotal)}</span>
            </div>
            <div style={cartStyles.shipRow}>
              <div style={cartStyles.shipField}>
                <label style={cartStyles.shipLabel}>{T.country}</label>
                <select style={cartStyles.shipSelect} value={country}
                        onChange={(e) => { setCountry(e.target.value); setErr(''); }}>
                  {SHIP_COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.label}</option>)}
                </select>
              </div>
              {country === 'US' && (
                <div style={cartStyles.shipField}>
                  <label style={cartStyles.shipLabel}>{T.state}</label>
                  <select style={cartStyles.shipSelect} value={usState}
                          onChange={(e) => { setUsState(e.target.value); setErr(''); }}>
                    <option value="">{T.statePh}</option>
                    {US_STATES.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>
              )}
              {country === 'US' && (
                <div style={cartStyles.shipField}>
                  <label style={cartStyles.shipLabel}>{T.zip}</label>
                  <input
                    style={cartStyles.shipSelect}
                    value={zip}
                    inputMode="numeric"
                    maxLength={5}
                    placeholder={T.zipPh}
                    onChange={(e) => { setZip(e.target.value.replace(/\D/g, '').slice(0, 5)); setErr(''); }}
                  />
                </div>
              )}
            </div>
            <button style={{ ...cartStyles.checkoutBtn, opacity: busy ? 0.7 : 1 }}
                    onClick={onCheckout} disabled={busy}>
              {busy ? T.checking : T.checkout}
            </button>
            {err && <div style={cartStyles.err}>{err}</div>}
            <div style={cartStyles.hint}>
              {shipOpts && shipOpts.length
                ? T.shipFrom + ' ' + shipOpts.map((o) => `${o.display_name.replace(/^USPS\s+/, '')} $${(o.amount / 100).toFixed(2)}`).join(' · ')
                : T.shippingHint}
            </div>
          </div>
        )}
      </div>

      <style>{`@keyframes tntCartSlide { from { transform: translateX(24px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>
    </div>
  );
}

window.CartDrawer = CartDrawer;
