// ui.jsx — shared UI atoms: icons, store cards, product cards, scaffolding

// ─── Icons (SVG, 24px stroke) ─────────────────────────────────────────────
const Icon = {
  home:    (c='currentColor',s=2) => <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M3 11l9-8 9 8v9a2 2 0 01-2 2h-4v-7h-6v7H5a2 2 0 01-2-2v-9z" stroke={c} strokeWidth={s} strokeLinejoin="round"/></svg>,
  search:  (c='currentColor',s=2) => <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="7" stroke={c} strokeWidth={s}/><path d="M20 20l-3.5-3.5" stroke={c} strokeWidth={s} strokeLinecap="round"/></svg>,
  drop:    (c='currentColor',s=2) => <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 2.5l1.4 3.5 3.7.5-2.7 2.6.6 3.7L12 11l-3 1.8.6-3.7L7 6.5l3.7-.5L12 2.5z" stroke={c} strokeWidth={s} strokeLinejoin="round"/><path d="M5 18l3-2 4 2 4-2 3 2" stroke={c} strokeWidth={s} strokeLinecap="round" strokeLinejoin="round"/></svg>,
  saved:   (c='currentColor',s=2) => <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M6 3h12v18l-6-4-6 4V3z" stroke={c} strokeWidth={s} strokeLinejoin="round"/></svg>,
  user:    (c='currentColor',s=2) => <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="8" r="4" stroke={c} strokeWidth={s}/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8" stroke={c} strokeWidth={s} strokeLinecap="round"/></svg>,
  heart:   (c='currentColor',s=2,fill='none') => <svg width="24" height="24" viewBox="0 0 24 24" fill={fill}><path d="M12 21s-7-4.5-9.5-9C.8 8.5 3 5 6.5 5 9 5 11 7 12 9c1-2 3-4 5.5-4C21 5 23.2 8.5 21.5 12 19 16.5 12 21 12 21z" stroke={c} strokeWidth={s} strokeLinejoin="round"/></svg>,
  bookmark:(c='currentColor',s=2,fill='none') => <svg width="22" height="22" viewBox="0 0 24 24" fill={fill}><path d="M6 3h12v18l-6-4-6 4V3z" stroke={c} strokeWidth={s} strokeLinejoin="round"/></svg>,
  share:   (c='currentColor',s=2) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M12 3v12M12 3l-4 4M12 3l4 4M5 13v6a2 2 0 002 2h10a2 2 0 002-2v-6" stroke={c} strokeWidth={s} strokeLinecap="round" strokeLinejoin="round"/></svg>,
  back:    (c='currentColor',s=2) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M15 5l-7 7 7 7" stroke={c} strokeWidth={s+0.4} strokeLinecap="round" strokeLinejoin="round"/></svg>,
  more:    (c='currentColor') => <svg width="22" height="22" viewBox="0 0 24 24"><circle cx="5" cy="12" r="2" fill={c}/><circle cx="12" cy="12" r="2" fill={c}/><circle cx="19" cy="12" r="2" fill={c}/></svg>,
  camera:  (c='currentColor',s=2) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 8a2 2 0 012-2h2.5L9 4h6l1.5 2H19a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V8z" stroke={c} strokeWidth={s} strokeLinejoin="round"/><circle cx="12" cy="13" r="3.5" stroke={c} strokeWidth={s}/></svg>,
  sparkle: (c='currentColor') => <svg width="14" height="14" viewBox="0 0 24 24"><path d="M12 2l1.8 6.2L20 10l-6.2 1.8L12 18l-1.8-6.2L4 10l6.2-1.8L12 2z" fill={c}/></svg>,
  close:   (c='currentColor',s=2) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke={c} strokeWidth={s} strokeLinecap="round"/></svg>,
  plus:    (c='currentColor',s=2) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke={c} strokeWidth={s} strokeLinecap="round"/></svg>,
  flame:   (c='currentColor') => <svg width="14" height="14" viewBox="0 0 24 24" fill={c}><path d="M12 2c0 4-4 5-4 9a4 4 0 008 0c0-2-1-3-1-5 2 1 4 3 4 6a7 7 0 11-14 0c0-5 5-6 7-10z"/></svg>,
};

// ─── Tag pill ─────────────────────────────────────────────────────────────
function Tag({ children, active, onClick, dark, size = 'md', shape = 'rounded' }) {
  const radii = { rounded: 999, sharp: 6, blob: 16 };
  const padY = size === 'sm' ? 6 : 9;
  const padX = size === 'sm' ? 12 : 14;
  const fs = size === 'sm' ? 12 : 13;
  return (
    <button onClick={onClick} className="ms-tag" style={{
      border: 'none', cursor: 'pointer',
      padding: `${padY}px ${padX}px`,
      borderRadius: radii[shape] ?? 999,
      fontSize: fs, fontWeight: 500, letterSpacing: -0.1,
      background: active
        ? (dark ? 'var(--ink)' : 'var(--ink)')
        : (dark ? 'rgba(255,255,255,0.08)' : 'var(--surface-2)'),
      color: active ? (dark ? 'var(--bg)' : '#fff') : 'var(--ink)',
      whiteSpace: 'nowrap', flexShrink: 0,
      transition: 'all .15s',
    }}>{children}</button>
  );
}

// ─── Cover image (real photo + gradient veil) ─────────────────────────────
function Cover({ store, height, radius = 24 }) {
  return (
    <div style={{
      position: 'relative', width: '100%', height, borderRadius: radius,
      overflow: 'hidden', background: store.gradient,
    }}>
      {store.cover ? (
        <img src={store.cover} alt={store.title}
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover',
            mixBlendMode: 'multiply', opacity: 0.92,
          }} />
      ) : null}
      {/* gradient overlay for text legibility */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(20,30,18,0) 40%, rgba(20,30,18,0.55) 100%)',
      }} />
    </div>
  );
}

/** Mini-store feed card (TikTok-style); loads clipping previews via /api/share when active. */
function StoreFeedCard({ store, isActive, onOpen, onSave, saved, shape, density, dark }) {
  const radii = { rounded: 28, sharp: 8, blob: 36 };
  const padTop = density === 'compact' ? 60 : 64;
  const padBottom = density === 'compact' ? 96 : 100;
  const [patchTick, bumpPatch] = React.useReducer((x) => x + 1, 0);
  const prefetching = React.useRef(false);

  React.useEffect(() => {
    const h = () => bumpPatch();
    window.addEventListener('deanna:stores-patch', h);
    return () => window.removeEventListener('deanna:stores-patch', h);
  }, []);

  React.useEffect(() => {
    if (!isActive || !store?.shareSlug || store.productsLoaded || prefetching.current) return;
    prefetching.current = true;
    window.hydrateStoreProducts?.(store.shareSlug)
      .then((products) => {
        window.mergeProductsIntoGlobalStore?.(store.bookId, store.shareSlug, products || []);
        prefetching.current = false;
      })
      .catch(() => { prefetching.current = false; });
  }, [isActive, store.shareSlug, store.bookId, store.productsLoaded]);

  const productsPeek = React.useMemo(() => {
    const cur = window.findStore?.(store.id);
    const list = (cur && Array.isArray(cur.products)) ? cur.products : (store.products || []);
    return list;
  }, [store.id, patchTick, isActive]);

  const brandLinePrimary = React.useMemo(() => {
    const first = productsPeek[0];
    if (first && first.img && first.name) return `${first.name.slice(0, 42)}`;
    if (store.creatorName) return store.creatorName;
    const n = typeof store.items === 'number' ? store.items : 0;
    return n ? `${n} clipping${n === 1 ? '' : 's'} en esta tienda` : 'MiniTienda Deanna';
  }, [productsPeek, store.creatorName, store.items]);

  const brandMarcaSuffix = React.useMemo(() => {
    const imgs = productsPeek.filter((p) => p.img);
    const shown = imgs.length || (typeof store.items === 'number' ? store.items : 0);
    return shown <= 1 ? `${shown} pieza` : `${shown} piezas`;
  }, [productsPeek, store.items]);

  return (
    <div className="ms-feed-card" style={{
      position: 'relative', width: '100%', height: '100%',
      padding: `${padTop}px 12px ${padBottom}px`,
      boxSizing: 'border-box',
    }}>
      <div onClick={onOpen} style={{
        position: 'relative', width: '100%', height: '100%',
        borderRadius: radii[shape] ?? 28, overflow: 'hidden',
        background: store.gradient,
        boxShadow: dark
          ? '0 24px 48px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.06) inset'
          : '0 24px 48px rgba(40,55,32,0.18), 0 0 0 1px rgba(0,0,0,0.04) inset',
        cursor: 'pointer',
      }}>
        {store.cover ? (
          <img src={store.cover} alt={store.title}
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', mixBlendMode: 'multiply', opacity: 0.95,
              transform: isActive ? 'scale(1.02)' : 'scale(1)',
              transition: 'transform 1200ms cubic-bezier(.2,.7,.3,1)',
            }} />
        ) : null}
        {/* dark gradient veil */}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(15,25,12,0) 35%, rgba(15,25,12,0.78) 100%)',
        }} />
        {/* mini-store label chip */}
        <div style={{
          position: 'absolute', top: 14, left: 14,
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '6px 10px', borderRadius: 999,
          background: 'rgba(255,255,255,0.18)',
          backdropFilter: 'blur(14px) saturate(160%)',
          WebkitBackdropFilter: 'blur(14px) saturate(160%)',
          border: '0.5px solid rgba(255,255,255,0.35)',
          color: '#fff', fontSize: 11, fontWeight: 600,
          letterSpacing: 0.4, textTransform: 'uppercase',
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: '#C9E5B4' }} />
          MiniTienda
        </div>
        {/* count + saves */}
        <div style={{
          position: 'absolute', top: 14, right: 14,
          padding: '6px 10px', borderRadius: 999,
          background: 'rgba(0,0,0,0.32)',
          backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
          color: '#fff', fontSize: 11, fontWeight: 500,
        }}>{store.items} pzs</div>

        {/* product peek strip */}
        <div style={{
          position: 'absolute', bottom: 122, left: 18, right: 78,
          display: 'flex', gap: 8, overflow: 'hidden',
        }}>
          {productsPeek.slice(0, 4).map((p, i) => (
            <div key={p.id || i} style={{
              flex: '0 0 64px', height: 84, borderRadius: 12,
              overflow: 'hidden',
              background: 'rgba(255,255,255,0.12)',
              boxShadow: '0 6px 18px rgba(0,0,0,0.28)',
              transform: `translateY(${i * 2}px)`,
              display: 'flex',
              alignItems: 'stretch',
              justifyContent: 'center',
            }}>
              {p.img ? (
                <img src={p.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              ) : (
                <span style={{
                  alignSelf: 'center', fontSize: 10, padding: '0 8px',
                  color: 'rgba(255,255,255,0.82)', fontWeight: 600, textAlign: 'center', lineHeight: 1.2,
                }}>
                  {p.clipType === 'video' ? '▶' : '·'}
                </span>
              )}
            </div>
          ))}
        </div>

        {/* title block */}
        <div style={{
          position: 'absolute', left: 22, right: 78, bottom: 22, color: '#fff',
        }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: 1.2,
            textTransform: 'uppercase', opacity: 0.78, marginBottom: 6,
          }}>{brandLinePrimary} · {brandMarcaSuffix}</div>
          <div style={{
            fontSize: 26, lineHeight: '30px', fontWeight: 600,
            letterSpacing: -0.6, marginBottom: 6,
            fontFamily: 'var(--font-display)',
          }}>{store.title}</div>
          <div style={{
            fontSize: 13, lineHeight: '18px', opacity: 0.85, fontWeight: 400,
          }}>{store.vibe}</div>
        </div>

        {/* side actions */}
        <div style={{
          position: 'absolute', right: 14, bottom: 22,
          display: 'flex', flexDirection: 'column', gap: 18,
          alignItems: 'center',
        }}>
          <SideAction label={fmtSaves(store.saves)}
            onClick={(e) => { e.stopPropagation(); onSave(); }}
            active={saved}>
            {Icon.heart('#fff', 2, saved ? '#FF6B6B' : 'none')}
          </SideAction>
          <SideAction label="Guardar"
            onClick={(e) => { e.stopPropagation(); onSave(); }}>
            {Icon.bookmark('#fff', 2)}
          </SideAction>
          <SideAction label="Compartir">
            {Icon.share('#fff', 2)}
          </SideAction>
        </div>
      </div>
    </div>
  );
}

function SideAction({ children, label, onClick, active }) {
  return (
    <button onClick={onClick} style={{
      border: 'none', background: 'transparent', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      padding: 0,
    }}>
      <div style={{
        width: 46, height: 46, borderRadius: 999,
        background: 'rgba(255,255,255,0.16)',
        backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
        border: '0.5px solid rgba(255,255,255,0.28)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: active ? '0 0 0 2px rgba(255,107,107,0.5)' : 'none',
        transition: 'all .15s',
      }}>{children}</div>
      <span style={{ color: '#fff', fontSize: 11, fontWeight: 500, opacity: 0.9 }}>{label}</span>
    </button>
  );
}

// ─── Pinterest masonry tile ───────────────────────────────────────────────
function StorePinTile({ store, onOpen, onSave, saved, shape, h }) {
  const radii = { rounded: 18, sharp: 4, blob: 28 };
  return (
    <div onClick={onOpen} style={{
      position: 'relative', width: '100%', height: h,
      borderRadius: radii[shape] ?? 18, overflow: 'hidden',
      background: store.gradient,
      cursor: 'pointer', marginBottom: 10,
      boxShadow: '0 6px 14px rgba(40,55,32,0.10)',
    }}>
      {store.cover ? (
        <img src={store.cover} alt="" style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover', mixBlendMode: 'multiply', opacity: 0.94,
        }} />
      ) : null}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, transparent 50%, rgba(15,25,12,0.78) 100%)',
      }} />
      <button onClick={(e) => { e.stopPropagation(); onSave(); }} style={{
        position: 'absolute', top: 8, right: 8,
        width: 32, height: 32, borderRadius: 999,
        background: saved ? '#1A1F18' : 'rgba(255,255,255,0.92)',
        border: 'none', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {Icon.bookmark(saved ? '#C9E5B4' : '#1A1F18', 2.2, saved ? '#C9E5B4' : 'none')}
      </button>
      <div style={{
        position: 'absolute', left: 10, right: 10, bottom: 10, color: '#fff',
      }}>
        <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: -0.2,
          fontFamily: 'var(--font-display)' }}>{store.title}</div>
        <div style={{ fontSize: 11, opacity: 0.85, marginTop: 2 }}>
          {store.items} pzs · {fmtSaves(store.saves)}
        </div>
      </div>
    </div>
  );
}

// ─── Hybrid (hero + peek) card ────────────────────────────────────────────
function StoreHybridCard({ store, onOpen, onSave, saved, shape }) {
  const radii = { rounded: 22, sharp: 6, blob: 32 };
  return (
    <div onClick={onOpen} style={{
      position: 'relative', width: '100%',
      borderRadius: radii[shape] ?? 22, overflow: 'hidden',
      background: store.gradient,
      cursor: 'pointer',
      boxShadow: '0 10px 24px rgba(40,55,32,0.12)',
    }}>
      <div style={{ position: 'relative', height: 380 }}>
        {store.cover ? (
          <img src={store.cover} alt="" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', mixBlendMode: 'multiply', opacity: 0.93,
          }} />
        ) : null}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(15,25,12,0) 50%, rgba(15,25,12,0.7) 100%)',
        }} />
        <button onClick={(e) => { e.stopPropagation(); onSave(); }} style={{
          position: 'absolute', top: 14, right: 14,
          width: 40, height: 40, borderRadius: 999,
          background: 'rgba(255,255,255,0.18)',
          backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
          border: '0.5px solid rgba(255,255,255,0.32)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.bookmark('#fff', 2, saved ? '#fff' : 'none')}</button>
      </div>
      <div style={{
        padding: '14px 16px 16px', background: 'var(--surface)',
      }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: 0.6,
          textTransform: 'uppercase', color: 'var(--ink-2)', marginBottom: 6 }}>
          {store.vibe}
        </div>
        <div style={{
          fontSize: 22, lineHeight: '26px', fontWeight: 600, letterSpacing: -0.4,
          color: 'var(--ink)', marginBottom: 12, fontFamily: 'var(--font-display)',
        }}>{store.title}</div>
        <div style={{ display: 'flex', gap: 6, overflow: 'hidden' }}>
          {(store.products || []).slice(0, 5).map((p) => (
            <div key={p.id} style={{
              flex: '0 0 56px', height: 72, borderRadius: 10, overflow: 'hidden',
              background: 'var(--surface-2)',
            }}>
              {p.img ? (
                <img src={p.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              ) : (
                <div style={{
                  width: '100%', height: '100%', display: 'flex', alignItems: 'center',
                  justifyContent: 'center', fontSize: 13, fontWeight: 700, color: 'var(--ink-2)',
                }}>{p.clipType === 'video' ? '▶' : '·'}</div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Product card ─────────────────────────────────────────────────────────
function ProductCard({ product, onOpen, shape }) {
  const radii = { rounded: 14, sharp: 4, blob: 22 };
  return (
    <div onClick={onOpen} style={{ cursor: 'pointer' }}>
      <div style={{
        width: '100%', aspectRatio: '3/4',
        borderRadius: radii[shape] ?? 14, overflow: 'hidden',
        background: 'var(--surface-2)', position: 'relative',
      }}>
        {product.img ? (
          <img src={product.img} alt={product.name} style={{
            width: '100%', height: '100%', objectFit: 'cover',
          }} />
        ) : (
          <div style={{
            width: '100%', height: '100%', display: 'flex', alignItems: 'center',
            justifyContent: 'center', fontSize: 22, fontWeight: 700, color: 'var(--ink-2)',
          }}>
            {product.clipType === 'video' ? '▶ vídeo' : 'Clip'}
          </div>
        )}
      </div>
      <div style={{ padding: '8px 2px 0' }}>
        <div style={{ fontSize: 11, color: 'var(--ink-2)', fontWeight: 500,
          textTransform: 'uppercase', letterSpacing: 0.4 }}>{product.brand}</div>
        <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500,
          letterSpacing: -0.1, marginTop: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{product.name}</div>
        <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600, marginTop: 2 }}>{product.price}</div>
      </div>
    </div>
  );
}

// ─── helpers ──────────────────────────────────────────────────────────────
function fmtSaves(n) {
  if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
  return String(n);
}

Object.assign(window, {
  Icon, Tag, Cover, StoreFeedCard, StorePinTile, StoreHybridCard, ProductCard,
  fmtSaves,
});
