// Atoms: ícones, placeholders de joias, helpers

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// ----- ícones SVG (stroke) -----
function Icon({ name, size = 18, stroke = 1.6 }) {
  const s = size;
  const sw = stroke;
  const props = { width: s, height: s, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'search': return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>;
    case 'user':   return <svg {...props}><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6"/></svg>;
    case 'bag':    return <svg {...props}><path d="M5 8h14l-1 12H6L5 8z"/><path d="M9 8V6a3 3 0 1 1 6 0v2"/></svg>;
    case 'heart':  return <svg {...props}><path d="M12 21s-7-4.5-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 11c0 5.5-7 10-7 10z"/></svg>;
    case 'menu':   return <svg {...props}><path d="M4 7h16M4 12h16M4 17h16"/></svg>;
    case 'close':  return <svg {...props}><path d="M6 6l12 12M18 6 6 18"/></svg>;
    case 'arrow':  return <svg {...props}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'arrow-down': return <svg {...props}><path d="M12 5v14M6 13l6 6 6-6"/></svg>;
    case 'check':  return <svg {...props}><path d="M5 12l5 5L20 7"/></svg>;
    case 'plus':   return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
    case 'minus':  return <svg {...props}><path d="M5 12h14"/></svg>;
    case 'star':   return <svg {...props} fill="currentColor" stroke="none"><path d="M12 2l2.9 6.6 7.1.6-5.4 4.7 1.7 7L12 17.3 5.7 21l1.7-7L2 9.2l7.1-.6L12 2z"/></svg>;
    case 'whatsapp': return <svg {...props} fill="currentColor" stroke="none" viewBox="0 0 24 24"><path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.93.55 3.74 1.5 5.27L2 22l4.94-1.29c1.45.79 3.12 1.24 4.9 1.24h.01c5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.834 9.834 0 0 0 12.04 2zm0 18.17h-.01c-1.6 0-3.16-.43-4.51-1.24l-.32-.19-3.36.88.9-3.28-.21-.34a8.224 8.224 0 0 1-1.26-4.38c0-4.54 3.7-8.24 8.25-8.24 2.2 0 4.27.86 5.83 2.42a8.18 8.18 0 0 1 2.41 5.83c0 4.54-3.7 8.24-8.24 8.24zm4.52-6.16c-.25-.12-1.47-.72-1.7-.81-.23-.08-.39-.12-.56.12-.16.25-.64.81-.79.97-.15.16-.29.18-.54.06-.25-.12-1.05-.39-2-1.23-.74-.66-1.24-1.47-1.38-1.72-.14-.25-.02-.38.11-.5.11-.11.25-.29.37-.43.12-.14.16-.25.25-.41.08-.16.04-.31-.02-.43-.06-.12-.56-1.34-.76-1.84-.2-.48-.41-.42-.56-.43h-.48c-.16 0-.43.06-.66.31-.23.25-.86.84-.86 2.06 0 1.22.89 2.55 1.01 2.71.12.16 1.74 2.66 4.21 3.73.59.26 1.05.41 1.41.52.59.19 1.13.16 1.56.1.48-.07 1.47-.6 1.67-1.18.21-.58.21-1.07.14-1.18-.07-.11-.23-.16-.48-.28z"/></svg>;
    case 'shield': return <svg {...props}><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3z"/><path d="M9 12l2 2 4-4"/></svg>;
    case 'truck':  return <svg {...props}><path d="M3 7h11v9H3zM14 10h4l3 3v3h-7z"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></svg>;
    case 'card':   return <svg {...props}><rect x="2" y="6" width="20" height="13" rx="2"/><path d="M2 10h20"/></svg>;
    case 'sparkle':return <svg {...props}><path d="M12 3v5M12 16v5M3 12h5M16 12h5M6 6l3 3M15 15l3 3M18 6l-3 3M9 15l-3 3"/></svg>;
    case 'moon':   return <svg {...props}><path d="M20 14A8 8 0 1 1 10 4a6 6 0 0 0 10 10z"/></svg>;
    case 'eye':    return <svg {...props}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'eye-off':return <svg {...props}><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/></svg>;
    default: return null;
  }
}

// ----- Logo wordmark -----
function Logo({ light = false, size = 22 }) {
  const color = light ? '#fff' : 'var(--ink)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, color }}>
      <LogoMark size={size + 4} light={light} />
      <span className="serif" style={{ fontSize: size, letterSpacing: '0.04em', fontWeight: 500 }}>
        Lua Azul
      </span>
    </div>
  );
}

function LogoMark({ size = 28, light = false }) {
  // Official watercolor moon logo
  return (
    <img
      src="assets/logo.png"
      alt="Lua Azul"
      width={size}
      height={size}
      style={{
        display: 'block',
        width: size,
        height: size,
        objectFit: 'contain',
        // Subtle glow behind the watercolor moon when over dark backgrounds
        filter: light ? 'drop-shadow(0 1px 6px rgba(165,243,252,0.35))' : 'none',
      }}
    />
  );
}

// ----- Jewelry placeholder visual -----
// SVG illustration of a stylized piece, parameterized by hue + product category.
function JewelArt({ cat = 'Brincos', hue = 200, size = '100%', tone = 'soft' }) {
  // tone: 'soft' (light bg), 'deep' (gradient bg)
  const id = useMemo(() => 'ja-' + Math.random().toString(36).slice(2), []);
  const bgA = tone === 'deep' ? `oklch(0.55 0.13 ${hue})` : `oklch(0.94 0.04 ${hue})`;
  const bgB = tone === 'deep' ? `oklch(0.42 0.15 ${hue - 6})` : `oklch(0.88 0.06 ${hue + 6})`;
  const metal = tone === 'deep' ? '#cffafe' : `oklch(0.42 0.13 ${hue + 2})`;
  const stoneA = `oklch(0.72 0.15 ${hue})`;
  const stoneB = `oklch(0.55 0.17 ${hue + 4})`;
  const shine = '#ffffff';

  return (
    <svg viewBox="0 0 300 300" width={size} height={size} preserveAspectRatio="xMidYMid slice"
         style={{ display: 'block', width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id={`${id}-bg`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={bgA}/><stop offset="100%" stopColor={bgB}/>
        </linearGradient>
        <radialGradient id={`${id}-stone`} cx="0.35" cy="0.3">
          <stop offset="0%" stopColor={shine} stopOpacity="0.85"/>
          <stop offset="40%" stopColor={stoneA}/>
          <stop offset="100%" stopColor={stoneB}/>
        </radialGradient>
        <radialGradient id={`${id}-vign`} cx="0.5" cy="1.1" r="0.9">
          <stop offset="0%" stopColor="#000" stopOpacity="0.18"/>
          <stop offset="100%" stopColor="#000" stopOpacity="0"/>
        </radialGradient>
      </defs>
      <rect width="300" height="300" fill={`url(#${id}-bg)`} />
      {/* subtle sparkle dots */}
      <g opacity="0.5">
        {[[40,60],[260,80],[230,220],[60,230],[150,40],[270,150]].map(([x,y],i)=>(
          <circle key={i} cx={x} cy={y} r={1.5} fill={shine}/>
        ))}
      </g>
      <rect width="300" height="300" fill={`url(#${id}-vign)`}/>

      {cat === 'Brincos' && <Earring id={id} metal={metal} stone={`url(#${id}-stone)`} shine={shine}/>}
      {cat === 'Colares' && <Necklace id={id} metal={metal} stone={`url(#${id}-stone)`} shine={shine}/>}
      {cat === 'Pulseiras' && <Bracelet id={id} metal={metal} stone={`url(#${id}-stone)`} shine={shine}/>}
      {cat === 'Chokers' && <Choker id={id} metal={metal} stone={`url(#${id}-stone)`} shine={shine}/>}
      {cat === 'Conjuntos' && <SetCombo id={id} metal={metal} stone={`url(#${id}-stone)`} shine={shine}/>}
    </svg>
  );
}

function Earring({ metal, stone, shine }) {
  return (
    <g>
      {/* Hook */}
      <path d="M150 70 q-12 -4 -12 12" stroke={metal} strokeWidth="2" fill="none" strokeLinecap="round"/>
      {/* Chain */}
      <path d="M150 82 v40" stroke={metal} strokeWidth="1.5" fill="none"/>
      {/* Stone */}
      <ellipse cx="150" cy="160" rx="42" ry="56" fill={stone}/>
      <ellipse cx="138" cy="142" rx="10" ry="14" fill={shine} opacity="0.45"/>
      <ellipse cx="150" cy="160" rx="42" ry="56" fill="none" stroke={metal} strokeWidth="2"/>
      {/* facet lines */}
      <path d="M150 104 L120 160 L150 216 L180 160 Z" fill="none" stroke={shine} strokeWidth="0.6" opacity="0.4"/>
    </g>
  );
}
function Necklace({ metal, stone, shine }) {
  return (
    <g>
      {/* Chain arc */}
      <path d="M40 110 Q150 230 260 110" fill="none" stroke={metal} strokeWidth="2"/>
      <path d="M40 110 Q150 235 260 110" fill="none" stroke={shine} strokeWidth="0.6" opacity="0.45"/>
      {/* Pendant */}
      <circle cx="150" cy="200" r="28" fill={stone}/>
      <circle cx="150" cy="200" r="28" fill="none" stroke={metal} strokeWidth="2"/>
      <circle cx="142" cy="193" r="7" fill={shine} opacity="0.55"/>
      {/* bail */}
      <rect x="146" y="168" width="8" height="10" rx="3" fill={metal}/>
    </g>
  );
}
function Bracelet({ metal, stone, shine }) {
  const beads = Array.from({length: 9}, (_,i)=> 60 + i*22);
  return (
    <g>
      <path d="M48 150 Q150 220 252 150" fill="none" stroke={metal} strokeWidth="1.5"/>
      {beads.map((x,i)=>(
        <g key={i}>
          <circle cx={x} cy={150 + Math.sin(i*0.45)*22} r={i===4?14:10} fill={i%2===0?stone:metal}/>
          {i%2===0 && <circle cx={x-3} cy={147 + Math.sin(i*0.45)*22} r={3} fill={shine} opacity="0.6"/>}
        </g>
      ))}
    </g>
  );
}
function Choker({ metal, stone, shine }) {
  return (
    <g>
      <path d="M50 130 Q150 200 250 130" fill="none" stroke={metal} strokeWidth="3"/>
      <path d="M50 130 Q150 200 250 130" fill="none" stroke={shine} strokeWidth="0.6" opacity="0.45"/>
      {/* center stone */}
      <path d="M150 175 l 22 -22 l -22 -22 l -22 22 z" fill={stone} stroke={metal} strokeWidth="1.5"/>
      <path d="M150 153 l 0 44" stroke={shine} strokeWidth="0.6" opacity="0.5"/>
      <path d="M128 153 q 22 22 44 0" fill="none" stroke={shine} strokeWidth="0.6" opacity="0.4"/>
    </g>
  );
}
function SetCombo({ metal, stone, shine }) {
  return (
    <g>
      {/* mini earring left */}
      <circle cx="80" cy="100" r="14" fill={stone} stroke={metal} strokeWidth="1.5"/>
      <circle cx="76" cy="96" r="3.5" fill={shine} opacity="0.6"/>
      {/* mini earring right */}
      <circle cx="220" cy="100" r="14" fill={stone} stroke={metal} strokeWidth="1.5"/>
      <circle cx="216" cy="96" r="3.5" fill={shine} opacity="0.6"/>
      {/* necklace arc */}
      <path d="M70 130 Q150 215 230 130" fill="none" stroke={metal} strokeWidth="1.5"/>
      <circle cx="150" cy="190" r="22" fill={stone} stroke={metal} strokeWidth="1.5"/>
      <circle cx="143" cy="183" r="6" fill={shine} opacity="0.6"/>
    </g>
  );
}

// ----- Cart context -----
const CartContext = createContext(null);
const CART_KEY = 'lua_cart_state';

function itemToStored(i){ return { id: i.id, qty: i.qty, ref: i.ref }; }

function loadLocalCart(){
  try {
    const raw = localStorage.getItem(CART_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? arr.filter(it => it.id && it.ref) : [];
  } catch { return []; }
}

function CartProvider({ children }) {
  const [items, setItems] = useState(() => loadLocalCart());
  const [open, setOpen] = useState(false);
  const [flash, setFlash] = useState(null);
  const [hydrated, setHydrated] = useState(false);

  // Persiste no localStorage sempre (sobrevive refresh)
  useEffect(() => {
    try { localStorage.setItem(CART_KEY, JSON.stringify(items.map(itemToStored))); } catch {}
    // Se logado, sincroniza com backend (debounce)
    const token = localStorage.getItem('lua_token');
    if (!token || !hydrated) return;
    const t = setTimeout(() => {
      fetch('/api/cart', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
        body: JSON.stringify({ items: items.map(i => ({
          id: i.id, name: i.ref?.name, price: i.ref?.price, qty: i.qty,
          image: i.ref?.image, variant: i.ref?.variant, cat: i.ref?.cat, hue: i.ref?.hue, slug: i.ref?.slug,
        })) }),
      }).catch(()=>{});
    }, 800);
    return () => clearTimeout(t);
  }, [items, hydrated]);

  // Mount: se logado, busca carrinho do servidor e mescla com local
  useEffect(() => {
    const token = localStorage.getItem('lua_token');
    if (!token){ setHydrated(true); return; }
    fetch('/api/cart', { headers: { 'Authorization': 'Bearer ' + token } })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (!data || !Array.isArray(data.cart)) return;
        const serverItems = data.cart.map(it => ({ id: it.id, qty: it.qty || 1, ref: { ...it } }));
        // Mescla: server prioridade, mas mantém locais que não estão no server
        setItems(local => {
          const merged = [...serverItems];
          for (const l of local){
            if (!merged.find(m => m.id === l.id)) merged.push(l);
          }
          return merged;
        });
      })
      .catch(()=>{})
      .finally(() => setHydrated(true));
  }, []);

  function add(product, qty = 1) {
    setItems((cur) => {
      const existing = cur.find(i => i.id === product.id);
      if (existing) return cur.map(i => i.id === product.id ? { ...i, qty: i.qty + qty } : i);
      return [...cur, { id: product.id, qty, ref: product }];
    });
    setFlash(product.name);
    setTimeout(()=> setFlash(null), 1800);
  }
  function remove(id) { setItems(cur => cur.filter(i => i.id !== id)); }
  function setQty(id, qty) {
    if (qty <= 0) return remove(id);
    setItems(cur => cur.map(i => i.id === id ? { ...i, qty } : i));
  }
  function buyNow(product) {
    add(product, 1);
    setTimeout(()=> setOpen(true), 200);
  }
  function clear() { setItems([]); }

  const count = items.reduce((s,i)=> s + (i.qty || 0), 0);
  const total = items.reduce((s,i)=> s + (i.qty || 0) * (i.ref?.price || 0), 0);

  return (
    <CartContext.Provider value={{ items, count, total, open, setOpen, add, buyNow, remove, setQty, clear, flash }}>
      {children}
    </CartContext.Provider>
  );
}
const useCart = () => useContext(CartContext);

// ----- Reveal on scroll -----
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }});
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

// ----- format money -----
const brl = (v) => 'R$ ' + v.toFixed(2).replace('.', ',');

Object.assign(window, { Icon, Logo, LogoMark, JewelArt, CartProvider, useCart, useReveal, brl });
