// Reusable building blocks: Header, Footer, ColoringCard, CategoryCard, Buttons, etc.

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

// === Buttons ===
const Btn = ({ variant = 'primary', size = 'md', children, className = '', leading, trailing, ...props }) => {
  const sizes = {
    sm: 'px-3.5 py-2 text-sm gap-1.5',
    md: 'px-5 py-3 text-[15px] gap-2',
    lg: 'px-6 py-4 text-base gap-2',
  };
  const variants = {
    primary:  'bg-coral text-white hover:bg-coralDeep btn-candy',
    secondary:'bg-ink text-white hover:bg-inkSoft btn-candy',
    ghost:    'bg-transparent text-ink hover:bg-ink/5',
    soft:     'bg-paper text-ink ring-2 ring-line hover:ring-ink/30',
    sun:      'bg-sun text-ink hover:bg-sunDeep btn-candy',
  };
  return (
    <button {...props}
      className={cls('inline-flex items-center justify-center rounded-full font-extrabold transition',
        sizes[size], variants[variant], className)}>
      {leading}{children}{trailing}
    </button>
  );
};

// === Default-Mappe switcher (header chip) ===
const DefaultMappeSwitcher = ({ mappen, activeMappeId, setActiveMappeId, user }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  if (!user) return null;
  if (!mappen || mappen.length <= 1) return null;
  const active = mappen.find(m => m.id === activeMappeId) || mappen[0];
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(!open)}
        title="Standard-Sammelmappe ändern"
        className="hidden md:inline-flex items-center gap-2 pl-1 pr-3 py-1 rounded-full bg-paper ring-2 ring-line hover:ring-ink/30 transition btn-press">
        <span className="inline-flex w-7 h-7 rounded-full bg-cream items-center justify-center text-base">{active.emoji}</span>
        <span className="flex flex-col items-start leading-none">
          <span className="text-[9px] font-bold uppercase tracking-wider text-inkSoft">Standard</span>
          <span className="text-[12px] font-extrabold max-w-[100px] truncate">{active.name}</span>
        </span>
        <IconChevronR size={13} className="text-inkSoft rotate-90"/>
      </button>
      {open && (
        <div className="absolute right-0 top-[calc(100%+8px)] w-72 bg-paper rounded-2xl ring-2 ring-line shadow-card overflow-hidden z-50 pop-in">
          <div className="px-4 py-3 bg-cream border-b-2 border-line">
            <div className="text-[11px] font-bold uppercase tracking-wider text-inkSoft">Neue Bilder landen in</div>
            <div className="text-[13px] text-inkSoft mt-0.5">Wähle deine Standard-Mappe</div>
          </div>
          <div className="p-1.5 max-h-[60vh] overflow-y-auto scroll-soft">
            {mappen.map(m => (
              <button key={m.id} onClick={() => { setActiveMappeId(m.id); setOpen(false); }}
                className={cls("w-full text-left flex items-center gap-3 px-3 py-2.5 rounded-xl transition",
                  m.id === active.id ? 'bg-coral/10 ring-2 ring-coral' : 'hover:bg-cream')}>
                <span className="inline-flex w-9 h-9 rounded-lg bg-cream items-center justify-center text-lg shrink-0">{m.emoji}</span>
                <div className="flex-1 min-w-0">
                  <div className="font-bold text-sm leading-tight truncate">{m.name}</div>
                  <div className="text-[11px] text-inkSoft">{m.items.length} Bild{m.items.length === 1 ? '' : 'er'}</div>
                </div>
                {m.id === active.id && (
                  <span className="inline-flex items-center gap-1 text-[11px] font-extrabold text-coralDeep">
                    <IconStar size={12} className="text-coralDeep"/> aktiv
                  </span>
                )}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// === Header (public) ===
const Header = ({ current, navigate, openMobile, setOpenMobile, collectionCount = 0, openMappe, isAdmin, user, openAuth, signOut, mappen, activeMappeId, setActiveMappeId }) => {
  const [hdrSettings] = useSettings();
  const headerLogo = hdrSettings && hdrSettings.logo;
  const NavLink = ({ id, label, target, emoji }) => (
    <button onClick={() => navigate(target)}
      className={cls(
        "px-4 py-2.5 rounded-full text-[15px] font-bold transition inline-flex items-center gap-1.5",
        current === id ? 'bg-ink text-white' : 'text-ink hover:bg-ink/5'
      )}>
      {emoji && <span aria-hidden="true">{emoji}</span>}{label}
    </button>
  );
  if (isAdmin) {
    return (
      <header className="sticky top-0 z-30 bg-ink text-white">
        <div className="max-w-7xl mx-auto px-5 sm:px-8 py-3 flex items-center gap-4">
          <button onClick={() => navigate({ view: 'adminDashboard' })}
                  className="flex items-center gap-2.5">
            <span className="inline-flex w-9 h-9 rounded-xl bg-white/10 items-center justify-center">
              <IconShield size={18}/>
            </span>
            <span className="font-display text-[20px] leading-none font-bold">
              Admin · Malfino.de
            </span>
          </button>
          <div className="ml-auto flex items-center gap-2">
            <Btn variant="ghost" size="sm" className="!text-white hover:!bg-white/10"
                 onClick={() => navigate({ view: 'home' })}
                 leading={<IconHome size={16}/>}>Zur Webseite</Btn>
          </div>
        </div>
      </header>
    );
  }
  return (
    <header className="sticky top-0 z-30 bg-cream/90 backdrop-blur border-b border-line">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-2.5 flex items-center gap-4 relative min-h-[60px]">
        <button onClick={() => navigate({ view: 'home' })} className="shrink-0">
          {headerLogo ? (
            <img src={headerLogo} alt="Logo" className="max-w-[320px] object-contain block hover:opacity-80 transition"
                 style={{ filter: 'none', height: ((hdrSettings && hdrSettings.logoSizeHeader) || 48) + 'px' }}/>
          ) : (
            <span className="flex items-center gap-2.5">
              <span className="relative inline-flex w-11 h-11 rounded-2xl bg-coral text-white items-center justify-center shadow-pop">
                <TinyBrush size={22} />
                <TinyStar className="absolute -top-1.5 -right-1.5 text-sun" size={14} />
              </span>
              <span className="font-display text-[22px] sm:text-[24px] leading-none font-extrabold tracking-tight">
                Malfino<span className="text-coralDeep">.de</span>
              </span>
            </span>
          )}
        </button>

        <nav className="ml-auto hidden md:flex items-center gap-1">
          <NavLink id="home"     label="Start"      emoji="🏠" target={{ view: 'home' }}/>
          <NavLink id="category" label="Kategorien" emoji="🎨" target={{ view: 'categoryIndex' }}/>
          <NavLink id="ranking"  label="Beliebt"    emoji="⭐" target={{ view: 'ranking' }}/>
        </nav>
        <div className="ml-auto md:ml-2 flex items-center gap-2">
          <button onClick={openMappe}
            className="relative inline-flex items-center gap-2 px-3.5 sm:px-4 py-2.5 rounded-full bg-coral text-white font-bold text-sm shadow-pop hover:bg-coralDeep transition btn-press">
            <span aria-hidden="true" className="bag-bounce">🎒</span>
            <span className="hidden sm:inline">Sammelmappe</span>
            {collectionCount > 0 && (
              <span className="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-white text-coralDeep text-[12px] font-extrabold pop-in">
                {collectionCount}
              </span>
            )}
          </button>
          <DefaultMappeSwitcher mappen={mappen} activeMappeId={activeMappeId} setActiveMappeId={setActiveMappeId} user={user}/>
          <ProfilePill user={user} navigate={navigate} openAuth={openAuth} onSignOut={signOut}/>
          <button onClick={() => setOpenMobile(!openMobile)}
                  className="md:hidden p-2 rounded-full hover:bg-ink/5">
            {openMobile ? <IconClose/> : <IconMenu/>}
          </button>
        </div>
      </div>
      {openMobile && (
        <div className="md:hidden border-t border-line bg-cream">
          <div className="px-5 py-3 grid gap-1">
            {[
              { id:'home', label:'Start', emoji:'🏠', target:{view:'home'}},
              { id:'category', label:'Kategorien', emoji:'🎨', target:{view:'categoryIndex'}},
              { id:'ranking', label:'Beliebt', emoji:'⭐', target:{view:'ranking'}},
            ].map(n => (
              <button key={n.id}
                onClick={() => { navigate(n.target); setOpenMobile(false); }}
                className={cls("text-left px-4 py-3 rounded-xl font-bold inline-flex items-center gap-2",
                  current === n.id ? 'bg-ink text-white' : 'hover:bg-ink/5')}>
                <span>{n.emoji}</span>{n.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </header>
  );
};

// === Footer ===
const Footer = ({ navigate }) => {
  // Top categories by popularity (excludes deleted + empty categories).
  const topCats = React.useMemo(() => getPublicCategories().slice(0, 6), []);
  const [footSettings] = useSettings();
  const footLogo = footSettings && footSettings.logo;
  return (
  <footer className="mt-24 border-t border-line bg-cream">
    <div className="max-w-7xl mx-auto px-5 sm:px-8 py-12 grid md:grid-cols-4 gap-8">
      <div>
        {footLogo ? (
          <img src={footLogo} alt="Logo" className="max-w-[360px] object-contain mb-4 block"
               style={{ height: ((footSettings && footSettings.logoSizeFooter) || 64) + 'px' }}/>
        ) : (
          <div className="flex items-center gap-2.5 mb-4">
            <span className="inline-flex w-9 h-9 rounded-2xl bg-coral text-white items-center justify-center">
              <TinyBrush size={18} />
            </span>
            <span className="font-display text-xl font-bold">Malfino.de</span>
          </div>
        )}
        <p className="text-sm text-inkSoft leading-relaxed max-w-xs">
          Liebevoll gestaltete Malvorlagen für Kinder, Kita, Schule und kreative Pausen, kostenlos zum Ausdrucken.
        </p>
      </div>
      <FooterCol title="Entdecken" items={[
        { l: 'Alle Kategorien', t: { view: 'categoryIndex' }},
        { l: 'Beliebt diesen Monat', t: { view: 'ranking' }},
        { l: 'Sammelmappe', t: { view: 'home', openMappe: true }},
        { l: 'Freunde einladen', t: { view: 'profile', tab: 'referral' }},
      ]} navigate={navigate} />
      <FooterCol title="Beliebteste Kategorien" items={topCats.map(c => ({
        l: c.name, t: { view: 'category', slug: c.slug }
      }))} navigate={navigate} />
      <div>
        <div className="text-sm font-bold mb-3">Über uns</div>
        <ul className="grid gap-2 text-sm text-inkSoft">
          <li><button onClick={() => navigate({view:'about'})} className="hover:text-coralDeep">Über Malfino.de</button></li>
          <li><button onClick={() => navigate({view:'lizenz'})} className="hover:text-coralDeep">Lizenz &amp; Nutzung</button></li>
          <li><button onClick={() => navigate({view:'datenschutz'})} className="hover:text-coralDeep">Datenschutz</button></li>
          <li><button onClick={() => navigate({view:'impressum'})} className="hover:text-coralDeep">Impressum</button></li>
          <li><button onClick={() => window.dispatchEvent(new CustomEvent('aw:cookie-open-settings'))} className="hover:text-coralDeep">🍪 Cookie‑Einstellungen</button></li>
          <li><button onClick={() => navigate({view:'adminDashboard'})} className="text-inkSoft/70 hover:text-coralDeep text-[12px]">Admin‑Login</button></li>
        </ul>
      </div>
    </div>
    <div className="border-t border-line">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-5 text-xs text-inkSoft flex flex-wrap items-center justify-between gap-2">
        <span>© {new Date().getFullYear()} Malfino.de, Alle Bilder kostenlos für private Nutzung.</span>
        <span className="inline-flex items-center gap-1.5"><IconShield size={14}/> Familienfreundlich · Kostenlos</span>
      </div>
    </div>
  </footer>
  );
};
const FooterCol = ({ title, items, navigate }) => (
  <div>
    <div className="text-sm font-bold mb-3">{title}</div>
    <ul className="grid gap-2 text-sm">
      {items.map((it, i) => (
        <li key={i}>
          <button onClick={() => navigate(it.t)} className="text-inkSoft hover:text-coralDeep">
            {it.l}
          </button>
        </li>
      ))}
    </ul>
  </div>
);

// === Search bar ===
const SearchBar = ({ value, onChange, onSubmit, size = 'lg', placeholder = 'Suche nach Einhorn, Dino, Mandala…' }) => (
  <form onSubmit={(e) => { e.preventDefault(); onSubmit && onSubmit(value); }}
        className={cls("flex items-center gap-2 bg-paper ring-2 ring-line rounded-full pl-5 pr-2 shadow-card",
          size === 'lg' ? 'py-2' : 'py-1.5',
          'focus-within:ring-coral')}>
    <IconSearch size={size === 'lg' ? 22 : 18} className="text-inkSoft shrink-0"/>
    <input value={value} onChange={(e) => onChange(e.target.value)}
           placeholder={placeholder}
           className={cls("bg-transparent outline-none flex-1",
             size === 'lg' ? 'py-3 text-[16px]' : 'py-2 text-sm')} />
    <Btn type="submit" size={size === 'lg' ? 'md' : 'sm'}>Suchen</Btn>
  </form>
);

// === ColoringCard ===
const ColoringCard = ({ item, navigate, badge, size = 'md', collection, toggleCollect }) => {
  const cat = findCategory(item.category);
  const tone = TONE_CLASSES[cat?.tone || 'mint'];
  const inMappe = collection && collection.some(x => x.id === item.id);
  return (
    <div className="group relative bg-paper rounded-3xl ring-2 ring-line hover:ring-ink/20 hover:shadow-card transition overflow-hidden card-lift stagger-fade">
      <button onClick={() => navigate({ view: 'detail', slug: item.slug })}
        className="block text-left w-full btn-press">
        <div className={cls("relative paper-bg p-4 aspect-[4/3] flex items-center justify-center")}>
          <div className={cls("absolute inset-3 rounded-2xl border-2 border-dashed border-line/80")}></div>
          {item.previewUrl
            ? <img src={item.previewUrl} alt={item.title}
                className={cls("relative w-[88%] h-[88%] object-contain tilt-img")}/>
            : <ColoringArt artKey={item.art}
                className={cls("relative w-[78%] h-[78%] tilt-img")} />}
          {item.isNew && (
            <span className="absolute top-3 left-3 inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-coral text-white text-[11px] font-extrabold tracking-wide shadow-pop pop-in">
              <span className="twinkle">✨</span> NEU
            </span>
          )}
          {badge && (
            <span className="absolute top-3 right-3 inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-ink text-white text-[11px] font-bold tracking-wide">
              {badge}
            </span>
          )}
        </div>
        <div className="p-4 pb-3">
          <div className="flex items-center gap-2 mb-1.5">
            <span className={cls("inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold", tone.soft, tone.text)}>
              {cat?.name}
            </span>
            <span className="text-[11px] text-inkSoft font-semibold">· {item.difficulty}</span>
          </div>
          <div className="font-display text-[18px] font-extrabold leading-snug truncate">{item.title}</div>
          <div className="mt-2 flex items-center justify-between text-[12px] text-inkSoft">
            <span className="inline-flex items-center gap-1 font-semibold"><IconStar size={14} className="text-sunDeep"/> {item.points.toLocaleString('de-DE')}</span>
            <span className="inline-flex items-center gap-1"><IconDownload size={14}/> {item.downloads.toLocaleString('de-DE')}</span>
          </div>
        </div>
      </button>
      {toggleCollect && (
        <button onClick={(e) => { e.stopPropagation(); toggleCollect(item); }}
          className={cls(
            "absolute bottom-3 right-3 inline-flex items-center gap-1 px-3 py-1.5 rounded-full font-bold text-[12px] transition shadow-pop btn-press",
            inMappe ? 'bg-mint text-emerald-900 ring-2 ring-emerald-700/30' : 'bg-coral text-white hover:bg-coralDeep'
          )}>
          {inMappe ? <><IconCheck size={14}/>In Mappe</> : <><IconPlus size={14}/>Sammeln</>}
        </button>
      )}
    </div>
  );
};

// === CategoryCard ===
const CategoryCard = ({ cat, navigate, variant = 'card' }) => {
  const tone = TONE_CLASSES[cat.tone];
  const hasCover = !!cat.coverImage;
  if (variant === 'chip') {
    return (
      <button onClick={() => navigate({ view: 'category', slug: cat.slug })}
        className={cls("inline-flex items-center gap-2.5 pl-2 pr-5 py-2 rounded-full ring-2 ring-line bg-paper hover:ring-ink/30 hover:-translate-y-0.5 transition",
          "font-bold text-[15px] wiggle")}>
        <span className={cls("inline-flex w-9 h-9 rounded-full items-center justify-center overflow-hidden", hasCover ? 'bg-cream' : tone.bg)}>
          {hasCover
            ? <img src={cat.coverImage} alt="" className="w-full h-full object-cover"/>
            : <ColoringArt artKey={cat.art} className="w-6 h-6"/>}
        </span>
        {cat.name}
        <span className="text-[11px] text-inkSoft font-bold bg-cream px-2 py-0.5 rounded-full">{cat.count}</span>
      </button>
    );
  }
  return (
    <button onClick={() => navigate({ view: 'category', slug: cat.slug })}
      className="group text-left bg-paper rounded-3xl ring-2 ring-line hover:ring-ink/20 hover:shadow-card hover:-translate-y-1 transition overflow-hidden">
      <div className={cls("relative aspect-[5/3] flex items-center justify-center overflow-hidden", hasCover ? 'bg-cream' : `p-6 ${tone.bg}`)}>
        {hasCover ? (
          <img src={cat.coverImage} alt={cat.name}
            className="absolute inset-0 w-full h-full object-cover transition-transform group-hover:scale-105"/>
        ) : (
          <ColoringArt artKey={cat.art} className="w-28 h-28 group-hover:scale-110 group-hover:rotate-[-3deg] transition-transform"/>
        )}
        <span className="absolute top-3 right-3 text-2xl drop-shadow">✨</span>
      </div>
      <div className="px-5 py-4 flex items-center justify-between">
        <div>
          <div className="font-display text-[19px] font-extrabold leading-tight">{cat.name}</div>
          <div className="text-[12px] text-inkSoft font-semibold">{cat.count} Bilder</div>
        </div>
        <span className="inline-flex w-9 h-9 rounded-full bg-cream items-center justify-center group-hover:bg-coral group-hover:text-white transition">
          <IconArrowR size={18}/>
        </span>
      </div>
    </button>
  );
};

// === Section heading ===
const SectionHeading = ({ kicker, title, action }) => (
  <div className="flex items-end justify-between gap-4 mb-6">
    <div>
      {kicker && <div className="inline-flex items-center gap-1.5 text-[12px] font-extrabold uppercase tracking-[0.1em] text-coralDeep mb-2 bg-coral/10 ring-2 ring-coral/20 rounded-full pl-2 pr-3 py-1 sticker">
        <TinyStar size={14} className="text-sunDeep twinkle"/>{kicker}
      </div>}
      <h2 className="font-display text-3xl sm:text-4xl font-extrabold tracking-tight" style={{textWrap:'balance'}}>{title}</h2>
    </div>
    {action}
  </div>
);

// Wavy divider, playful section separator
const WaveDivider = ({ color = '#FFFDF7', flip = false }) => (
  <div className="wave-divider -mt-1" aria-hidden="true" style={flip ? { transform: 'scaleY(-1)' } : undefined}>
    <svg viewBox="0 0 1200 32" preserveAspectRatio="none" className="w-full h-8">
      <path d="M0,16 C150,32 300,0 450,16 C600,32 750,0 900,16 C1050,32 1150,8 1200,16 L1200,32 L0,32 Z" fill={color}/>
    </svg>
  </div>
);

// === Stat card (admin / detail page) ===
const StatCard = ({ label, value, sub, icon, tone = 'sky' }) => {
  const t = TONE_CLASSES[tone];
  return (
    <div className="bg-paper rounded-xl2 ring-1 ring-line p-5 min-w-0 overflow-hidden">
      <div className="flex items-center justify-between mb-2 gap-2">
        <span className="text-[12px] font-bold uppercase tracking-wider text-inkSoft truncate">{label}</span>
        <span className={cls("inline-flex w-8 h-8 rounded-full items-center justify-center shrink-0", t.soft, t.text)}>
          {icon}
        </span>
      </div>
      <div className="font-display text-3xl font-bold leading-none truncate">{value}</div>
      {sub && <div className="text-[12px] text-inkSoft mt-1.5 truncate">{sub}</div>}
    </div>
  );
};

// === Tabs (segmented) ===
const Tabs = ({ tabs, value, onChange }) => (
  <div className="inline-flex items-center bg-paper ring-2 ring-line rounded-full p-1 overflow-x-auto scroll-soft max-w-full">
    {tabs.map(t => (
      <button key={t.value} onClick={() => onChange(t.value)}
        className={cls("px-4 py-2 rounded-full text-sm font-bold whitespace-nowrap transition",
          value === t.value ? 'bg-ink text-white' : 'text-ink hover:bg-ink/5')}>
        {t.label}
      </button>
    ))}
  </div>
);

// === Ranking badge ===
const RankBadge = ({ rank, size = 'md' }) => {
  const colors = rank === 1 ? 'bg-sun text-ink ring-2 ring-sunDeep' : rank === 2 ? 'bg-sky text-ink ring-2 ring-skyDeep' : rank === 3 ? 'bg-coral text-white ring-2 ring-coralDeep' : 'bg-paper ring-2 ring-line text-ink';
  const sizes = size === 'lg' ? 'w-12 h-12 text-base' : 'w-9 h-9 text-sm';
  return (
    <span className={cls("inline-flex items-center justify-center rounded-full font-display font-extrabold shrink-0", colors, sizes)}>
      #{rank}
    </span>
  );
};

Object.assign(window, {
  cls, Btn, Header, Footer, SearchBar, ColoringCard, CategoryCard,
  SectionHeading, WaveDivider, StatCard, Tabs, RankBadge, DefaultMappeSwitcher,
});
