// ============================================================
// COMPONENTS — shared UI bits
// ============================================================
const { useState, useEffect, useRef, useMemo } = React;

function breedSlug(name){
  return name.normalize('NFD').replace(/[̀-ͯ]/g,'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/(^-|-$)/g,'');
}

const Icon = {
  search: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></svg>,
  cart: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 4h2l2.5 12h11l2.5-9H6"/><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/></svg>,
  heart: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 21s-7-4.5-9-9a5 5 0 0 1 9-3 5 5 0 0 1 9 3c-2 4.5-9 9-9 9z"/></svg>,
  user: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>,
  arrow: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14m-6-7 7 7-7 7"/></svg>,
  arrowL: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M19 12H5m6-7-7 7 7 7"/></svg>,
  paw: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="9" r="2"/><circle cx="10" cy="5" r="2"/><circle cx="14" cy="5" r="2"/><circle cx="18" cy="9" r="2"/><path d="M12 11c-3 0-5 3-5 6 0 2 1.5 3 3 3s2-1 2-1 1 1 2 1 3-1 3-3c0-3-2-6-5-6z"/></svg>,
  share: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="6" cy="12" r="3"/><circle cx="18" cy="6" r="3"/><circle cx="18" cy="18" r="3"/><path d="m9 13 6 4M15 7l-6 4"/></svg>,
  filter: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 6h18M6 12h12M10 18h4"/></svg>,
};

function TopBar({ active, onNav, cartCount, onLogin }) {
  return (
    <header className="topbar">
      <div className="container-wide">
        <div className="topbar-row">
          <a href="#home" className="brand" onClick={(e) => { e.preventDefault(); onNav('home'); }}>
            <span className="brand-mark">P</span>
            <span>Pootje</span>
          </a>
          <nav className="nav">
            <a className={active === 'home' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('home'); }}>Home</a>
            <a className={active === 'quiz' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('quiz'); }}>Hondenmatch</a>
            <a className={active === 'breeds' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('breeds'); }}>Rassen</a>
            <a className={active === 'shop' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('shop'); }}>Webshop</a>
            <a className={active === 'guide' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('guide'); }}>Kennisbank</a>
            <a className={active === 'lid' ? 'active' : ''} onClick={(e) => { e.preventDefault(); onNav('lid'); }}>Word lid</a>
          </nav>
          <div className="topbar-actions">
            <button className="icon-btn" title="Zoeken">{Icon.search}</button>
            <button className="icon-btn" title="Favorieten">{Icon.heart}</button>
            <button className="icon-btn" title="Winkelmandje" onClick={() => onNav('shop')}>
              {Icon.cart}
              {cartCount > 0 && <span className="cart-bubble">{cartCount}</span>}
            </button>
            <button className="btn-login" onClick={() => onLogin && onLogin('login')}>{Icon.user} Inloggen</button>
          </div>
        </div>
      </div>
    </header>
  );
}

function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">Pootje</div>
            <p className="footer-brand-desc">Welke hond past bij jou? Wij helpen je een leven lang met match, kennis en alles wat je hond nodig heeft.</p>
          </div>
          <div>
            <h4>Ontdekken</h4>
            <div className="footer-links">
              <a onClick={() => onNav('quiz')}>Hondenmatch quiz</a>
              <a onClick={() => onNav('breeds')}>Alle 200+ rassen</a>
              <a onClick={() => onNav('guide')}>Kennisbank</a>
              <a>Vergelijken</a>
            </div>
          </div>
          <div>
            <h4>Webshop</h4>
            <div className="footer-links">
              <a onClick={() => onNav('shop')}>Voer &amp; snacks</a>
              <a onClick={() => onNav('shop')}>Manden</a>
              <a onClick={() => onNav('shop')}>Tuig &amp; riemen</a>
              <a onClick={() => onNav('shop')}>Starterpakketten</a>
            </div>
          </div>
          <div>
            <h4>Service</h4>
            <div className="footer-links">
              <a>Klantenservice</a>
              <a>Bezorging</a>
              <a>Retourneren</a>
              <a>Contact</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Pootje. Made with care in NL.</span>
          <span>Privacy · Voorwaarden · Cookies</span>
        </div>
      </div>
    </footer>
  );
}

function BreedCard({ breed, onClick }) {
  return (
    <article className="breed-card" onClick={onClick}>
      <div className="breed-photo">
        <span className="ph-label">FOTO · {breed.name.split(' ')[0].toUpperCase()}</span>
        <img src={`assets/breeds/${breedSlug(breed.name)}.jpg`} alt={breed.name} onError={(e) => e.target.remove()} />
      </div>
      <div className="breed-info">
        <h3>{breed.name}</h3>
        <div className="meta">{breed.group} · {breed.size} · {breed.lifespan}</div>
        <p className="desc">{breed.short}</p>
        <div className="breed-tags">
          {breed.tags.slice(0, 3).map((t, i) => <span key={i} className="tag">{t}</span>)}
        </div>
      </div>
    </article>
  );
}

function TraitBars({ traits, max = 5 }) {
  const labels = {
    energie: 'Energie', vriendelijk: 'Vriendelijk', training: 'Trainbaarheid',
    verzorging: 'Verzorging', kindvriendelijk: 'Met kinderen', alleenZijn: 'Alleen kunnen zijn',
    blaffen: 'Blaffen', allergie: 'Hypoallergeen'
  };
  return (
    <div className="traits">
      {Object.entries(labels).map(([k, label]) => {
        const v = traits[k] || 0;
        return (
          <div key={k} className="trait">
            <span className="trait-label">{label}</span>
            <div className="trait-bar">
              <div className="trait-bar-fill" style={{ width: (v / max * 100) + '%' }}></div>
            </div>
            <span className="trait-val">{v}/{max}</span>
          </div>
        );
      })}
    </div>
  );
}

function CostChart({ breed }) {
  const items = [
    { label: 'Voer/mnd', val: parseInt(breed.care.voer.match(/\d+/)?.[0] || 50), max: 120, color: '' },
    { label: 'Verzekering', val: 35, max: 120, color: '' },
    { label: 'Dierenarts', val: 28, max: 120, color: '' },
    { label: 'Trimmer', val: breed.traits.verzorging * 12, max: 120, color: 'alt' },
    { label: 'Speelgoed', val: 12, max: 120, color: 'alt' },
    { label: 'Verzekering+', val: 18, max: 120, color: 'alt' },
  ];
  const total = items.reduce((s, i) => s + i.val, 0);
  return (
    <div>
      <div className="cost-bars">
        {items.map((it, i) => (
          <div key={i} className="cost-bar">
            <div className={`cost-bar-fill ${it.color}`} style={{ height: (it.val / it.max * 100) + '%' }}>
              <div className="cost-bar-amt">€{it.val}</div>
            </div>
            <div className="cost-bar-label">{it.label}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24, alignItems: 'baseline' }}>
        <div>
          <div className="upper muted">Geschat per maand</div>
          <div className="serif" style={{ fontSize: 32 }}>€{total},–</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="upper muted">Per jaar</div>
          <div className="serif" style={{ fontSize: 22 }}>€{total * 12},–</div>
        </div>
      </div>
    </div>
  );
}

function ScheduleChart({ breed }) {
  const days = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
  const energie = breed.traits.energie || 3;
  const buildDay = (i) => {
    const blocks = [];
    blocks.push('b-walk');
    if (energie >= 3) blocks.push('b-train');
    blocks.push('b-rest');
    if (energie >= 4) blocks.push('b-walk');
    blocks.push('b-play');
    blocks.push('b-rest');
    blocks.push('b-walk');
    if (i === 5 || i === 6) blocks.push('b-play');
    return blocks;
  };
  return (
    <div>
      <div className="schedule">
        {days.map((d, i) => (
          <div key={d} className="day">
            <div className="day-name">{d}</div>
            <div className="day-blocks">
              {buildDay(i).map((b, j) => <span key={j} className={`block ${b}`}></span>)}
            </div>
          </div>
        ))}
      </div>
      <div className="legend">
        <span><i className="legend-dot" style={{ background: 'var(--forest)' }}></i> Wandelen</span>
        <span><i className="legend-dot" style={{ background: 'var(--terracotta)' }}></i> Training</span>
        <span><i className="legend-dot" style={{ background: 'var(--gold)' }}></i> Spelen</span>
        <span><i className="legend-dot" style={{ background: 'var(--line)' }}></i> Rust</span>
      </div>
    </div>
  );
}

function ProductCard({ product, inCart, onAdd }) {
  return (
    <article className="product">
      <div className="product-img">
        {product.badge && <span className="product-badge">{product.badge}</span>}
        <button className="product-fav" onClick={(e) => e.stopPropagation()}>♡</button>
        <span className="product-tag">{product.tag}</span>
      </div>
      <div className="product-info">
        <div className="product-brand">{product.brand}</div>
        <div className="product-name">{product.name}</div>
        <div className="product-rating">
          <span className="stars">★★★★★</span>
          <span>{product.rating} · {product.reviews} reviews</span>
        </div>
        <div className="product-row">
          <div className="product-price">
            €{product.price.toFixed(2)}
            {product.old && <span className="old">€{product.old.toFixed(2)}</span>}
          </div>
          <button className={`add-btn ${inCart ? 'added' : ''}`} onClick={(e) => { e.stopPropagation(); onAdd(product); }}>
            {inCart ? '✓' : '+'}
          </button>
        </div>
      </div>
    </article>
  );
}

Object.assign(window, {
  Icon, TopBar, Footer, BreedCard, TraitBars, CostChart, ScheduleChart, ProductCard, breedSlug,
});