// site.jsx — Kids of Jupiter main site component
const { useState, useEffect, useMemo, useRef } = React;

const T = (lang) => window.KOJ_I18N[lang] || window.KOJ_I18N.tr;
const productName = window.KOJ_getName;

// ─── Helpers ─────────────────────────────────────────────────────────────────
const cls = (...xs) => xs.filter(Boolean).join(' ');

function useHashRoute() {
  const [hash, setHash] = useState(window.location.hash || '#/');
  useEffect(() => {
    const fn = () => { setHash(window.location.hash || '#/'); window.scrollTo({top:0, behavior:'instant'}); };
    window.addEventListener('hashchange', fn);
    return () => window.removeEventListener('hashchange', fn);
  }, []);
  const go = (h) => { window.location.hash = h; };
  return [hash, go];
}

function useProducts() {
  const [products, setProducts] = useState(window.KOJ_PRODUCTS || []);
  useEffect(() => {
    return window.KOJ_subscribeProducts(setProducts);
  }, []);
  return products;
}

function useConfig() {
  const [config, setConfig] = useState(window.KOJ_CONFIG || {});
  useEffect(() => {
    return window.KOJ_subscribeConfig(setConfig);
  }, []);
  return config;
}

function useCollections() {
  const [collections, setCollections] = useState(window.KOJ_COLLECTIONS || []);
  useEffect(() => {
    return window.KOJ_subscribeCollections(setCollections);
  }, []);
  return collections;
}

function useCart() {
  const [cart, setCart] = useState(() => {
    try { return JSON.parse(localStorage.getItem('koj_cart') || '[]'); } catch { return []; }
  });
  useEffect(() => { localStorage.setItem('koj_cart', JSON.stringify(cart)); }, [cart]);

  const add = (item) => setCart(c => {
    const k = `${item.id}|${item.size}|${item.color}`;
    const idx = c.findIndex(x => `${x.id}|${x.size}|${x.color}` === k);
    if (idx >= 0) { const copy = [...c]; copy[idx] = {...copy[idx], qty: copy[idx].qty + (item.qty||1)}; return copy; }
    return [...c, {...item, qty: item.qty || 1}];
  });
  const remove = (k) => setCart(c => c.filter(x => `${x.id}|${x.size}|${x.color}` !== k));
  const setQty = (k, q) => setCart(c => c.map(x => `${x.id}|${x.size}|${x.color}` === k ? {...x, qty: Math.max(1, q)} : x));
  const clear = () => setCart([]);
  const count = cart.reduce((s,x) => s + x.qty, 0);
  return { cart, add, remove, setQty, clear, count };
}

const WHATSAPP = '905433248422';
function buildWaSingle(p, lang, size, color) {
  const t = T(lang);
  const name = productName(p, lang);
  return [t.wa.greet, '', t.wa.single, '', `• ${name}`, `  ${t.product.code}: ${p.id}`, size && `  ${t.product.size}: ${size}`, color && `  ${t.product.color}: ${window.KOJ_translateColor(color, lang)}`, '', t.wa.thanks].filter(Boolean).join('\n');
}
function buildWaCart(cart, lang) {
  const t = T(lang);
  const products = window.KOJ_PRODUCTS;
  const lines = [t.wa.greet, '', t.wa.multi, ''];
  cart.forEach((it, i) => {
    const p = products.find(x => x.id === it.id);
    if (!p) return;
    lines.push(`${i+1}. ${productName(p, lang)}`);
    lines.push(`   ${t.product.code}: ${p.id}  ·  ${t.product.size}: ${it.size}  ·  ${t.product.color}: ${window.KOJ_translateColor(it.color, lang)}  ·  ${t.cart.qty}: ${it.qty}`);
  });
  const total = cart.reduce((s,x) => s + x.qty, 0);
  lines.push('', `${t.wa.total}: ${total}`, '', t.wa.thanks);
  return lines.join('\n');
}
function openWa(text) {
  const url = `https://wa.me/${WHATSAPP}?text=${encodeURIComponent(text)}`;
  const win = window.open(url, '_blank', 'noopener,noreferrer');
  if (!win) {
    try { window.top.location.href = url; } catch { window.location.href = url; }
  }
}

// ─── Reusable bits ───────────────────────────────────────────────────────────
function PlanetMark({ size = 28, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" fill="none" stroke={color} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="34" cy="28" r="13.5" />
      <ellipse cx="34" cy="32" rx="22" ry="6" transform="rotate(-12 34 32)" />
      <path d="M12 14l1.6 3 3-1.4-3 1.4 1.6 3-1.6-3-3 1.4 3-1.4z" fill={color} stroke="none"/>
      <path d="M50 50l1.4 2.6 2.6-1.2-2.6 1.2 1.4 2.6-1.4-2.6-2.6 1.2 2.6-1.2z" fill={color} stroke="none"/>
    </svg>
  );
}

function Logo({ height = 28, config = {}, variant = 'default' }) {
  const h = height * 0.95;
  const k = config.navLogoKids || 'KIDS';
  const o = config.navLogoOf   || 'OF';
  const j = config.navLogoJupiter || 'JUPITER';

  // Eğer config'den herhangi biri değişmişse metin olarak bas, yoksa logoyu resim olarak göster
  const isChanged = config.navLogoKids || config.navLogoOf || config.navLogoJupiter;

  if (isChanged) {
    return (
      <a href="#/" className="koj-logo-text-wrap" style={{ fontSize: height*0.7, fontWeight: 700, letterSpacing: '0.1em', display:'inline-flex', gap: '0.4em', alignItems:'center', textDecoration:'none', color:'inherit' }}>
        <span>{k}</span>
        <span style={{ fontWeight: 300, opacity: 0.6 }}>{o}</span>
        <span>{j}</span>
      </a>
    );
  }

  if (variant === 'white') {
    return (
      <a href="#/" className="koj-logo" aria-label="Kids of Jupiter" style={{display:'inline-flex', alignItems:'center', textDecoration:'none'}}>
        <img src="assets/logo-full-white.png" alt="Kids of Jupiter" className="koj-logo-img" style={{height: h, width:'auto', display:'block', filter:'brightness(0) invert(1)'}} />
      </a>
    );
  }

  return (
    <a href="#/" className="koj-logo" aria-label="Kids of Jupiter" style={{display:'inline-flex', alignItems:'center', textDecoration:'none'}}>
      <img src="assets/logo-full.png" alt="Kids of Jupiter" className="koj-logo-img koj-logo-dark" style={{height: h, width:'auto', display:'block'}} />
      <img src="assets/logo-full-cream.png" alt="Kids of Jupiter" className="koj-logo-img koj-logo-light" style={{height: h, width:'auto', display:'block'}} />
    </a>
  );
}

function Button({ children, variant='primary', as:Tag='button', ...rest }) {
  return <Tag className={`koj-btn koj-btn-${variant}`} {...rest}>{children}</Tag>;
}

window.KOJ_Site_Helpers = { T, cls, useHashRoute, useProducts, useConfig, useCollections, useCart, buildWaSingle, buildWaCart, openWa, Logo, PlanetMark, Button, productName, WHATSAPP };
