// ============================================================
// Casa IS — shared components
// ============================================================
const { useState, useEffect, useRef, useCallback } = React;

// ---- t() helper: pick es/en from a {es,en} object or pass through strings
function t(lang, val) {
  if (val == null) return '';
  if (typeof val === 'string') return val;
  return val[lang] ?? val.en ?? '';
}

// ---- Placeholder image with optional palette wash and label tag.
//      If `src` is provided, renders a real <img> instead.
function Placeholder({ palette = ['#FAE3B1', '#998731'], label, ratio, style, className = '', src, alt }) {
  if (src) {
    return (
      <div className={`ph ph--img ${className}`} style={{ aspectRatio: ratio, ...style }}>
        <img
          src={src}
          alt={alt || label || ''}
          loading="lazy"
          style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center' }}
        />
      </div>
    );
  }
  const [a, b] = palette;
  const bg = {
    background: `linear-gradient(135deg, ${a} 0%, ${b} 100%)`,
    backgroundImage: `
      repeating-linear-gradient(135deg,
        rgba(35,31,32,0.06) 0 1px,
        transparent 1px 14px),
      linear-gradient(135deg, ${a} 0%, ${b} 100%)`,
  };
  return (
    <div className={`ph ${className}`} style={{ ...bg, aspectRatio: ratio, ...style }}>
      {label && <div className="ph__tag">{label}</div>}
    </div>
  );
}

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

// ---- Bilingual stacked text (used in poetic spots when paired mode is on)
function BiText({ lang, value, pairedMode = false, className = '' }) {
  if (!value || typeof value === 'string') {
    return <span className={className}>{value}</span>;
  }
  if (pairedMode) {
    return (
      <span className={`bilingual-pair ${className}`}>
        <span className="es">{value.es}</span>
        <span className="en">{value.en}</span>
      </span>
    );
  }
  return <span className={className}>{value[lang]}</span>;
}

// ---- Product Card
function ProductCard({ item, lang, onOpen, cart, accent = 'accent' }) {
  // Use Shopify CDN image if available, fall back to local image
  const displayImage = (item.shopifyHandle && shopifyImage(item.shopifyHandle)) || item.image;
  const displayPrice = (item.shopifyHandle && shopifyPrice(item.shopifyHandle)) || item.price;
  const badgeTone = (b) => {
    if (/sold/i.test(b)) return 'olive';
    if (/limited|launch|new/i.test(b)) return accent;
    if (/bestseller|editor/i.test(b)) return 'red';
    if (/commission|set/i.test(b)) return 'sky';
    return accent;
  };
  const handleAdd = (e) => {
    e.stopPropagation();
    if (item.shopifyHandle) {
      quickBuy(item.shopifyHandle);
    } else {
      // No Shopify product — scroll to commissions for originals, or open store for others
      const el = document.getElementById('commissions');
      if (el) el.scrollIntoView({ behavior: 'smooth' });
    }
  };
  return (
    <div className="card" onClick={() => onOpen && onOpen(item)}>
      <div className="card__media">
        <Placeholder palette={item.palette} label={item.id} src={displayImage} alt={typeof item.title === 'object' ? item.title[lang] : item.title} />
        <div className="card__badges">
          {item.badges?.map((b) => (
            <Badge key={b} tone={badgeTone(b)}>{b}</Badge>
          ))}
        </div>
        <div className="card__quick">
          <button onClick={(e) => { e.stopPropagation(); onOpen && onOpen(item); }}>
            {lang === 'es' ? 'Ver' : 'View'}
          </button>
          <button className="alt" onClick={handleAdd}>
            {lang === 'es' ? 'Añadir' : 'Add to cart'}
          </button>
        </div>
      </div>
      <div>
        <div className="card__meta">
          <div className="card__title">
            <em>{t(lang, item.title)}</em>
          </div>
          <div className="card__price">{displayPrice}</div>
        </div>
        {item.caption && (
          <div className="card__caption">{t(lang, item.caption)}</div>
        )}
        {item.sizes && item.sizes.length > 0 && (
          <div className="card__sizes">
            {item.sizes.map((s) => <span key={s}>{s}</span>)}
          </div>
        )}
      </div>
    </div>
  );
}

// ---- Lightbox
function Lightbox({ items, index, lang, cart, onClose, onNav }) {
  const open = index != null;
  const item = open ? items[index] : null;
  const [zoom, setZoom] = useState(false);
  const lbImage = item && ((item.shopifyHandle && shopifyImage(item.shopifyHandle)) || item.image);
  const lbPrice = item && ((item.shopifyHandle && shopifyPrice(item.shopifyHandle)) || item.price);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onNav(-1);
      if (e.key === 'ArrowRight') onNav(1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose, onNav]);

  useEffect(() => { setZoom(false); }, [index]);

  return (
    <div className={`lightbox ${open ? 'is-open' : ''}`} onClick={onClose}>
      <button className="lightbox__close" onClick={onClose}>
        {lang === 'es' ? 'Cerrar' : 'Close'}
      </button>
      {item && (
        <div className="lightbox__inner" onClick={(e) => e.stopPropagation()}>
          <div
            className={`lightbox__media ${zoom ? 'is-zoomed' : ''}`}
            onClick={() => setZoom(z => !z)}
          >
            <Placeholder palette={item.palette} label={item.id} src={lbImage} alt={typeof item.title === 'object' ? item.title[lang] : item.title} />
          </div>
          <div className="lightbox__info">
            <div className="label" style={{ opacity: 0.6 }}>
              {item.badges?.[0] || (lang === 'es' ? 'Pieza' : 'Piece')}
            </div>
            <h3><em>{t(lang, item.title)}</em></h3>
            {item.caption && (
              <p className="serif italic" style={{ fontSize: 18, lineHeight: 1.5 }}>
                {t(lang, item.caption)}
              </p>
            )}
            {item.medium && (
              <p style={{ fontSize: 13, opacity: 0.7, marginTop: 14 }}>
                {t(lang, item.medium)}
              </p>
            )}
            <div className="price">{lbPrice}</div>
            {item.sizes && item.sizes.length > 0 && (
              <div style={{ display: 'flex', gap: 8, margin: '12px 0 20px' }}>
                {item.sizes.map((s) => (
                  <span key={s} style={{
                    fontSize: 11, padding: '6px 12px',
                    border: '1px solid rgba(250,227,177,0.35)',
                    letterSpacing: '0.1em', fontWeight: 600,
                  }}>{s}</span>
                ))}
              </div>
            )}
            <div style={{ display: 'flex', gap: 12, marginTop: 12 }}>
              <button className="btn btn--light" onClick={() => {
                if (item.shopifyHandle) quickBuy(item.shopifyHandle);
                else { const el = document.getElementById('commissions'); if (el) el.scrollIntoView({ behavior: 'smooth' }); onClose(); }
              }}>
                {lang === 'es' ? 'Añadir al carrito' : 'Add to cart'}
              </button>
              <button className="btn" style={{ borderColor: 'rgba(250,227,177,0.5)', color: 'var(--cream)' }}
                onClick={() => { const el = document.getElementById('commissions'); if (el) el.scrollIntoView({ behavior: 'smooth' }); onClose(); }}>
                {lang === 'es' ? 'Encargar' : 'Commission'}
              </button>
            </div>
          </div>
          <div className="lightbox__nav">
            <button onClick={() => onNav(-1)} aria-label="Previous">‹</button>
            <button onClick={() => onNav(1)} aria-label="Next">›</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ---- Section header (rule + eyebrow + headline + sub)
function SectionHead({ eyebrow, head, body, lang, center = false, lightOnDark = false }) {
  return (
    <div className={`sec-head ${center ? 'sec-head--center' : ''}`} style={{ color: lightOnDark ? 'inherit' : undefined }}>
      <div className="sec-head__rule">
        <span className="line" />
        <span className="label">{t(lang, eyebrow)}</span>
      </div>
      <h2 className="h-section">
        {Array.isArray(head?.[lang]) ? (
          <>
            {head[lang][0]}<br />
            <em>{head[lang][1]}</em>
          </>
        ) : Array.isArray(head) ? (
          <>
            {head[0]}<br />
            <em>{head[1]}</em>
          </>
        ) : t(lang, head)}
      </h2>
      {body && <p className="serif italic" style={{ fontSize: 18, lineHeight: 1.55, opacity: 0.78, maxWidth: '52ch', marginTop: 4 }}>{t(lang, body)}</p>}
    </div>
  );
}

// ---- Cart Drawer
function CartDrawer({ lang, cart, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div className="lightbox is-open" onClick={onClose} style={{ zIndex: 10000 }}>
      <div className="cart-drawer" onClick={(e) => e.stopPropagation()} style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(420px, 90vw)',
        background: 'var(--dark, #231F20)', borderLeft: '1px solid rgba(250,227,177,0.15)',
        display: 'flex', flexDirection: 'column', padding: '32px 24px', overflowY: 'auto',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <h3 style={{ margin: 0, fontFamily: 'var(--serif)' }}>
            {lang === 'es' ? 'Tu bolsa' : 'Your bag'} ({cart.count})
          </h3>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--cream, #FAE3B1)', fontSize: 16, cursor: 'pointer' }}>
            {lang === 'es' ? 'Cerrar' : 'Close'}
          </button>
        </div>

        {cart.items.length === 0 ? (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <p className="serif italic" style={{ opacity: 0.6, fontSize: 18 }}>
              {lang === 'es' ? 'Tu bolsa está vacía.' : 'Your bag is empty.'}
            </p>
          </div>
        ) : (
          <>
            <div style={{ flex: 1 }}>
              {cart.items.map((item) => (
                <div key={item.key} style={{
                  display: 'flex', gap: 16, padding: '16px 0',
                  borderBottom: '1px solid rgba(250,227,177,0.1)',
                }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, marginBottom: 4 }}>{item.title}</div>
                    {item.variantTitle && <div style={{ fontSize: 13, opacity: 0.6 }}>{item.variantTitle}</div>}
                    <div style={{ fontSize: 14, marginTop: 8 }}>{item.price}</div>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 8 }}>
                      <button onClick={() => cart.updateQuantity(item.key, item.quantity - 1)}
                        style={{ background: 'none', border: '1px solid rgba(250,227,177,0.3)', color: 'var(--cream)', width: 28, height: 28, cursor: 'pointer' }}>-</button>
                      <span style={{ fontSize: 14, minWidth: 20, textAlign: 'center' }}>{item.quantity}</span>
                      <button onClick={() => cart.updateQuantity(item.key, item.quantity + 1)}
                        style={{ background: 'none', border: '1px solid rgba(250,227,177,0.3)', color: 'var(--cream)', width: 28, height: 28, cursor: 'pointer' }}>+</button>
                      <button onClick={() => cart.removeItem(item.key)}
                        style={{ background: 'none', border: 'none', color: 'var(--accent)', fontSize: 12, cursor: 'pointer', marginLeft: 'auto' }}>
                        {lang === 'es' ? 'Quitar' : 'Remove'}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ paddingTop: 24, borderTop: '1px solid rgba(250,227,177,0.2)' }}>
              <button className="btn btn--solid" onClick={cart.goToCheckout} style={{ width: '100%', padding: '16px 24px', fontSize: 16 }}>
                {lang === 'es' ? 'Ir al checkout' : 'Go to checkout'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  t, Placeholder, Badge, BiText, ProductCard, Lightbox, SectionHead, CartDrawer,
});
