/* Escala — shared UI atoms */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ============ Icons (hand-tuned line set, matches Apple/Mango feel) ============
const Icon = {
  Search: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  User:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>,
  Bag:    (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 8h14l-1 12H6L5 8Z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>,
  Menu:   (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" {...p}><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  Close:  (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" {...p}><path d="m6 6 12 12M18 6 6 18"/></svg>,
  Arrow:  (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  ArrowLeft: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>,
  Heart:  (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20.8 5.2a5.4 5.4 0 0 0-7.6 0L12 6.5l-1.2-1.3a5.4 5.4 0 1 0-7.6 7.6L12 21l8.8-8.2a5.4 5.4 0 0 0 0-7.6Z"/></svg>,
  Check:  (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m5 12 5 5L20 7"/></svg>,
  Plus:   (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  Minus:  (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" {...p}><path d="M5 12h14"/></svg>,
  Truck:  (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 7h11v9H3zM14 10h4l3 3v3h-7"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></svg>,
  Globe:  (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>,
  Stripe: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" {...p}><path d="M13.5 8.4c0-.7.6-.95 1.4-.95 1.2 0 2.7.4 3.85 1.05V4.85c-1.3-.5-2.55-.7-3.85-.7C11.7 4.15 9.55 5.7 9.55 8.5c0 4.45 5.95 3.7 5.95 5.6 0 .85-.7 1.1-1.6 1.1-1.3 0-3.05-.55-4.35-1.3v3.7c1.45.6 2.95.85 4.35.85 3.4 0 5.6-1.5 5.6-4.4 0-4.7-6-3.85-6-5.65Z"/></svg>,
  Google: (p) => <svg viewBox="0 0 24 24" width="16" height="16" {...p}><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.07 5.07 0 0 1-2.2 3.32v2.76h3.55c2.08-1.92 3.29-4.74 3.29-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.55-2.76c-.98.66-2.24 1.06-3.73 1.06-2.87 0-5.3-1.94-6.16-4.55H2.18v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.84 14.09a6.6 6.6 0 0 1 0-4.18V7.07H2.18a11 11 0 0 0 0 9.86l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.07.56 4.21 1.64l3.15-3.15A11 11 0 0 0 12 1 11 11 0 0 0 2.18 7.07l3.66 2.84C6.7 7.32 9.13 5.38 12 5.38z"/></svg>,
};

// ============ Site Header ============
function SiteHeader({ route, navigate, onCart, onSearch, cartCount, user }) {
  const T = window.t || (k => k);
  const accountLabel = user ? T('nav.account.in') : T('nav.account.out');
  const accountTarget = user ? '/account' : '/login';
  React.useEffect(() => {
    const h = () => { /* re-render via parent on i18n change handled by switcher */ };
    window.addEventListener('escala:i18n', h);
    return () => window.removeEventListener('escala:i18n', h);
  }, []);
  return (
    <header className="site-header">
      <div className="site-header__inner">
        <a href="#/" onClick={(e) => { e.preventDefault(); navigate('/'); }} className="brand">
          ESCALA<sup>®</sup>
        </a>
        <nav className="nav nav--desktop">
          <a href="#/" className={route === '/' ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); navigate('/'); }}>{(window.t||(k=>k))('nav.home')}</a>
          <a href="#/shop" className={route.startsWith('/shop') || route.startsWith('/product') ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); navigate('/shop'); }}>{(window.t||(k=>k))('nav.shop')}</a>
          <a href="#/about" className={route === '/about' ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); navigate('/about'); }}>{(window.t||(k=>k))('nav.about')}</a>
          <a href={'#' + accountTarget} className={route.startsWith('/account') || route === '/login' ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); navigate(accountTarget); }}>{accountLabel}</a>
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <LangCurrencySwitcher/>
          <button className="icon-btn" onClick={onSearch} aria-label="Buscar"><Icon.Search/></button>
          <button className="icon-btn" onClick={() => navigate(accountTarget)} aria-label={user ? 'Mi cuenta' : 'Entrar'}><Icon.User/></button>
          <button className="icon-btn" onClick={onCart} aria-label="Bolsa">
            <Icon.Bag/>
            {cartCount > 0 && <span className="badge">{cartCount}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

// ============ Footer ============
function SiteFooter({ navigate }) {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="site-footer__grid">
          <div>
            <div className="brand" style={{ marginBottom: 16 }}>ESCALA<sup>®</sup></div>
            <p style={{ fontSize: 13, color: 'var(--ink-3)', maxWidth: 280, lineHeight: 1.55 }}>
              Tu segunda muda de piel para escalar. Hecho en Portugal.
            </p>
            <form
              onSubmit={(e) => { e.preventDefault(); alert('Gracias — te avisaremos.'); }}
              style={{ display: 'flex', gap: 8, marginTop: 24, maxWidth: 320 }}>
              <input type="email" required placeholder="tu@email.com" className="input" style={{ padding: '10px 14px' }}/>
              <button className="btn btn--sm" type="submit">Avísame</button>
            </form>
          </div>
          <div>
            <h4>Tienda</h4>
            <ul>
              <li><a href="#/shop" onClick={(e)=>{e.preventDefault(); navigate('/shop');}}>Todo</a></li>
              <li><a href="#/shop?color=white" onClick={(e)=>{e.preventDefault(); navigate('/shop?color=white');}}>Blanco</a></li>
              <li><a href="#/shop?color=black" onClick={(e)=>{e.preventDefault(); navigate('/shop?color=black');}}>Negro</a></li>
              <li><a href="#/shop?sort=new" onClick={(e)=>{e.preventDefault(); navigate('/shop?sort=new');}}>Novedades</a></li>
            </ul>
          </div>
          <div>
            <h4>Compañía</h4>
            <ul>
              <li><a href="#/about" onClick={(e)=>{e.preventDefault(); navigate('/about');}}>Sobre Escala</a></li>
              <li><a href="#/legal" onClick={(e)=>{e.preventDefault(); navigate('/legal');}}>Términos</a></li>
              <li><a href="#/legal" onClick={(e)=>{e.preventDefault(); navigate('/legal');}}>Privacidad</a></li>
              <li><a href="#" onClick={(e)=>e.preventDefault()}>Contacto</a></li>
            </ul>
          </div>
          <div>
            <h4>Cuenta</h4>
            <ul>
              <li><a href="#/account/orders" onClick={(e)=>{e.preventDefault(); navigate('/account/orders');}}>Mis pedidos</a></li>
              <li><a href="#/account" onClick={(e)=>{e.preventDefault(); navigate('/account');}}>Mi perfil</a></li>
              <li><a href="#/login" onClick={(e)=>{e.preventDefault(); navigate('/login');}}>Iniciar sesión</a></li>
            </ul>
          </div>
        </div>
        <div className="site-footer__bottom">
          <span>© 2026 Escala Apparel S.L. — Todos los derechos reservados.</span>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <span><Icon.Globe style={{ verticalAlign: 'middle', marginRight: 4 }}/> ES · EUR</span>
            <span style={{ opacity: 0.6 }}>·</span>
            <span>Pagos seguros con Stripe</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ============ Product card ============
function ProductCard({ product, onClick }) {
  const img = product.images[0];
  return (
    <article className="product-card" onClick={onClick}>
      <div className="product-card__media">
        {product.newIn && <span className="product-card__badge">Nuevo</span>}
        {img ? <img src={img} alt={product.name}/> : <div className="skeleton-img">{product.name}</div>}
      </div>
      <div className="product-card__title">
        <h3>{product.name}</h3>
        <span>{window.ESCALA_FORMAT(product.price)}</span>
      </div>
      <div className="product-card__sub">{product.type}</div>
      <div className="product-card__swatches">
        {product.colors.includes('white') && <span className="swatch swatch--white" title="Blanco"/>}
        {product.colors.includes('black') && <span className="swatch swatch--black" title="Negro"/>}
        <span style={{ fontSize: 11, color: 'var(--ink-4)', marginLeft: 6 }}>
          {product.embroideryColors.length} bordados
        </span>
      </div>
    </article>
  );
}

// ============ Cart Drawer ============
function CartDrawer({ open, onClose, navigate }) {
  const [, force] = useState(0);
  useEffect(() => window.ESCALA_CART.subscribe(() => force(v => v+1)), []);
  const lines = window.ESCALA_CART.get();
  const subtotal = window.ESCALA_CART.subtotal();

  return (
    <>
      <div className={'drawer-mask' + (open ? ' open' : '')} onClick={onClose}/>
      <aside className={'drawer' + (open ? ' open' : '')} aria-hidden={!open}>
        <div className="drawer__head">
          <h3>Tu bolsa <span style={{ color: 'var(--ink-4)', fontWeight: 400, marginLeft: 6 }}>· {window.ESCALA_CART.count()}</span></h3>
          <button className="icon-btn" onClick={onClose} aria-label="Cerrar"><Icon.Close/></button>
        </div>
        <div className="drawer__body">
          {lines.length === 0 && (
            <div style={{ padding: '80px 0', textAlign: 'center', color: 'var(--ink-4)' }}>
              <p style={{ fontSize: 14 }}>Tu bolsa está vacía</p>
              <button className="btn btn--ghost btn--sm" onClick={() => { onClose(); navigate('/shop'); }} style={{ marginTop: 16 }}>
                Explorar tienda
              </button>
            </div>
          )}
          {lines.map((l, idx) => (
            <div className="cart-line" key={idx}>
              <div className="cart-line__media">
                {l.image ? <img src={l.image} alt=""/> : <div className="skeleton-img"></div>}
              </div>
              <div className="cart-line__info">
                <h4>{l.productName}</h4>
                <span>Color: {l.color === 'white' ? 'Blanco' : 'Negro'}</span>
                <span>Línea: {l.lineLabel} · Talla {l.size}</span>
                <div className="qty-stepper">
                  <button onClick={() => window.ESCALA_CART.setQty(idx, l.qty - 1)}><Icon.Minus/></button>
                  <span>{l.qty}</span>
                  <button onClick={() => window.ESCALA_CART.setQty(idx, l.qty + 1)}><Icon.Plus/></button>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between' }}>
                <span className="cart-line__price">{window.ESCALA_FORMAT(l.price * l.qty)}</span>
                <button onClick={() => window.ESCALA_CART.remove(idx)}
                        style={{ background: 'none', border: 'none', fontSize: 11, color: 'var(--ink-4)', textDecoration: 'underline', cursor: 'pointer', padding: 0 }}>
                  Eliminar
                </button>
              </div>
            </div>
          ))}
        </div>
        {lines.length > 0 && (
          <div className="drawer__foot">
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 13, color: 'var(--ink-3)' }}>
              <span>Subtotal</span><span>{window.ESCALA_FORMAT(subtotal)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontSize: 13, color: 'var(--ink-3)' }}>
              <span>Envío</span><span>Calculado en checkout</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontSize: 16, fontWeight: 500 }}>
              <span>Total</span><span>{window.ESCALA_FORMAT(subtotal)}</span>
            </div>
            <button className="btn btn--full btn--lg" onClick={() => { onClose(); navigate('/checkout'); }}>
              Finalizar compra <Icon.Arrow/>
            </button>
            <p style={{ fontSize: 11, color: 'var(--ink-4)', textAlign: 'center', marginTop: 12 }}>
              Pagos seguros con Stripe · Devolución gratuita 30 días
            </p>
          </div>
        )}
      </aside>
    </>
  );
}

// ============ Search overlay ============
function SearchOverlay({ open, onClose, navigate }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 100); }, [open]);
  const products = window.ESCALA_DATA.products;
  const results = q ? products.filter(p =>
    p.name.toLowerCase().includes(q.toLowerCase()) ||
    p.type.toLowerCase().includes(q.toLowerCase())
  ) : products.slice(0, 4);

  if (!open) return null;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(255,255,255,0.92)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ borderBottom: '1px solid var(--line-soft)' }}>
        <div className="container" style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '24px 32px' }}>
          <Icon.Search/>
          <input
            ref={inputRef}
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Buscar camisetas, tipos, bordados…"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent',
                     fontSize: 22, fontFamily: 'var(--font-display)', letterSpacing: '-0.02em', color: 'var(--ink)' }}
          />
          <button className="icon-btn" onClick={onClose}><Icon.Close/></button>
        </div>
      </div>
      <div className="container" style={{ padding: '32px', flex: 1, overflowY: 'auto' }}>
        <p className="t-eyebrow" style={{ marginBottom: 24 }}>{q ? `${results.length} resultados` : 'Populares'}</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 24 }}>
          {results.map(p => (
            <ProductCard key={p.id} product={p} onClick={() => { onClose(); navigate('/product/' + p.slug); }}/>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Icon, SiteHeader, SiteFooter, ProductCard, CartDrawer, SearchOverlay,
});
