// Public pages: Home, CategoryIndex, Category, Detail, Ranking

// === HOME ===
const HomePage = ({ navigate, search, setSearch, points, bumpPoints, collection, toggleCollect, user }) => {
  const fresh = [...COLORINGS].filter(c => c.isNew).slice(0, 4);
  const popular = [...COLORINGS].sort((a,b) => b.points - a.points).slice(0, 8);
  const categories = getPublicCategories();
  const topCats = categories.slice(0, 6);

  return (
    <main>
      {/* Hero */}
      <section className="relative overflow-hidden">
        <div className="absolute inset-0 -z-10">
          <div className="absolute -top-20 -left-20 w-[420px] h-[420px] rounded-full bg-sky/40 blur-3xl"/>
          <div className="absolute top-10 right-0 w-[380px] h-[380px] rounded-full bg-sun/40 blur-3xl"/>
          <div className="absolute bottom-0 left-1/3 w-[360px] h-[360px] rounded-full bg-coral/20 blur-3xl"/>
        </div>
        {/* Floating decorations */}
        <div aria-hidden="true" className="absolute inset-0 -z-0 pointer-events-none">
          <span className="absolute top-[12%] left-[6%] text-3xl float-a">⭐</span>
          <span className="absolute top-[22%] right-[10%] text-4xl float-b drift-l">☁️</span>
          <span className="absolute top-[55%] left-[3%] text-2xl float-c">🎨</span>
          <span className="absolute top-[8%] right-[42%] text-2xl twinkle">✨</span>
          <span className="absolute bottom-[14%] right-[6%] text-3xl float-a">🖍️</span>
          <span className="absolute top-[45%] right-[3%] text-xl twinkle" style={{animationDelay:'0.6s'}}>✨</span>
        </div>
        <div className="max-w-7xl mx-auto px-5 sm:px-8 pt-24 pb-12 grid lg:grid-cols-12 gap-10 items-center">
          <div className="lg:col-span-7">
            <div className="inline-flex items-center gap-2 bg-paper ring-1 ring-line rounded-full pl-1.5 pr-4 py-1.5 mb-5">
              <span className="inline-flex w-7 h-7 rounded-full bg-sun items-center justify-center"><TinyStar size={14}/></span>
              <span className="text-[12px] font-bold tracking-wide">Über 1.500 kostenlose Malvorlagen</span>
            </div>
            <h1 className="font-display text-[44px] sm:text-6xl lg:text-[76px] font-extrabold leading-[1.0] tracking-tight" style={{textWrap:'balance'}}>
              <span className="block">Mal los! ✏️</span>
              <span className="block mt-1">Ganz viele{" "}
                <span className="relative inline-block">
                  <span className="relative z-10">bunte</span>
                  <span className="absolute left-0 right-0 bottom-1.5 h-3.5 bg-sun -z-0 rounded-full"></span>
                </span>{" "}
                Bilder
              </span>
              <span className="block mt-1 text-coralDeep">zum Ausdrucken.</span>
            </h1>
            <p className="mt-5 text-lg text-inkSoft max-w-xl leading-relaxed">
              Entdecke liebevoll gestaltete Malvorlagen für Kinder, Kita, Schule und kreative Pausen. Einfach klicken, drucken, los malen.
            </p>
            <div className="mt-7 max-w-xl">
              <SearchBar value={search} onChange={setSearch}
                onSubmit={() => navigate({ view: 'categoryIndex' })}/>
            </div>
            <div className="mt-5 flex flex-wrap items-center gap-2">
              <span className="text-[12px] font-bold text-inkSoft">Beliebt:</span>
              {['Einhorn','Dinosaurier','Mandala','Weihnachten','Bauernhof'].map(t => (
                <button key={t} onClick={() => { setSearch(t); navigate({view:'categoryIndex'}); }}
                  className="px-3 py-1.5 rounded-full bg-paper ring-1 ring-line text-sm hover:ring-ink/30">
                  {t}
                </button>
              ))}
            </div>
          </div>
          <div className="lg:col-span-5 relative">
            <HeroCollage navigate={navigate}/>
          </div>
        </div>
      </section>

      {/* CTA-Banner: Sammelmappe (jetzt direkt unter dem Hero) */}
      <section className="max-w-7xl mx-auto px-5 sm:px-8 mt-12">
        <div className="relative overflow-hidden rounded-[36px] bg-ink text-white p-8 sm:p-12 grid sm:grid-cols-5 gap-8 items-center">
          <div className="sm:col-span-3">
            <div className="inline-flex items-center gap-2 bg-white/10 rounded-full px-3 py-1.5 mb-4">
              <span aria-hidden="true" className="bag-bounce">🎒</span>
              <span className="text-[12px] font-bold tracking-wide">Sammelmappe</span>
            </div>
            <h3 className="font-display text-3xl sm:text-4xl font-extrabold leading-tight" style={{textWrap:'balance'}}>
              Mehrere Bilder auf einmal drucken? Klar!
            </h3>
            <p className="mt-3 text-white/70 max-w-lg">
              Sammle deine Lieblingsbilder in der Sammelmappe und drucke sie alle gemeinsam, perfekt für Kita, Klasse oder den Kindergeburtstag.
            </p>
            <div className="mt-6 flex flex-wrap gap-3">
              <Btn variant="primary" size="lg" leading={<span aria-hidden="true" className="text-lg">🎒</span>}
                onClick={() => navigate({ view: 'home', openMappe: true })}>Sammelmappe öffnen</Btn>
              <Btn variant="ghost" size="lg" className="!text-white hover:!bg-white/10"
                onClick={() => navigate({ view: 'categoryIndex' })}
                trailing={<IconArrowR size={18}/>}>Bilder entdecken</Btn>
            </div>
          </div>
          <div className="sm:col-span-2">
            <div className="relative mx-auto w-full max-w-[300px] h-60 select-none">
              {/* Hinteres Blatt (links) */}
              <div className="absolute top-1/2 left-1 -translate-y-1/2 -rotate-[9deg] z-10 w-[124px] bg-paper rounded-2xl shadow-pop p-2.5">
                <div className="rounded-xl border-2 border-dashed border-line/80 paper-bg aspect-[3/4] flex items-center justify-center">
                  <ColoringArt artKey="rocket" className="w-[74%] h-[74%]"/>
                </div>
                <div className="text-center text-[11px] font-bold text-inkSoft pt-1.5">Rakete</div>
              </div>
              {/* Hinteres Blatt (rechts) */}
              <div className="absolute top-1/2 right-1 -translate-y-1/2 rotate-[9deg] z-20 w-[124px] bg-paper rounded-2xl shadow-pop p-2.5">
                <div className="rounded-xl border-2 border-dashed border-line/80 paper-bg aspect-[3/4] flex items-center justify-center">
                  <ColoringArt artKey="bunny" className="w-[74%] h-[74%]"/>
                </div>
                <div className="text-center text-[11px] font-bold text-inkSoft pt-1.5">Osterhase</div>
              </div>
              {/* Vorderes Blatt (Mitte) */}
              <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-30 w-[140px]">
                <div className="bg-paper rounded-2xl shadow-2xl p-3 float-a">
                  <div className="rounded-xl border-2 border-dashed border-line/80 paper-bg aspect-[3/4] flex items-center justify-center">
                    <ColoringArt artKey="mandala" className="w-[78%] h-[78%]"/>
                  </div>
                  <div className="text-center text-[12px] font-bold text-inkSoft pt-1.5">Mandala</div>
                </div>
              </div>
              {/* Badge: mehrere Seiten, ein Druck */}
              <div className="absolute -bottom-1 left-1/2 -translate-x-1/2 z-40 inline-flex items-center gap-1.5 bg-coral text-white text-[12px] font-extrabold rounded-full pl-2.5 pr-3 py-1.5 shadow-pop whitespace-nowrap">
                <span aria-hidden="true">🖨️</span> 3 Seiten, 1 Druck
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Beliebte Kategorien (chips) */}
      <section className="max-w-7xl mx-auto px-5 sm:px-8 mt-16">
        <SectionHeading kicker="Beliebte Themen" title="Worauf hast du heute Lust?"
          action={<Btn variant="ghost" size="sm" trailing={<IconArrowR size={16}/>}
            onClick={() => navigate({ view: 'categoryIndex' })}>Alle Kategorien</Btn>}/>
        <div className="flex flex-wrap gap-2.5">
          {categories.map(c => <CategoryCard key={c.slug} cat={c} navigate={navigate} variant="chip"/>)}
        </div>
      </section>

      {/* Neue Ausmalbilder */}
      <section className="max-w-7xl mx-auto px-5 sm:px-8 mt-20">
        <SectionHeading kicker="Frisch im Atelier" title="Neue Ausmalbilder"
          action={<Btn variant="ghost" size="sm" trailing={<IconArrowR size={16}/>}
            onClick={() => navigate({ view: 'categoryIndex' })}>Alle ansehen</Btn>}/>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {fresh.map(c => <ColoringCard key={c.id} item={c} navigate={navigate} collection={collection} toggleCollect={toggleCollect}/>)}
        </div>
      </section>

      {/* Beliebteste diesen Monat */}
      <section className="max-w-7xl mx-auto px-5 sm:px-8 mt-20">
        <SectionHeading kicker="Charts" title="Beliebteste Ausmalbilder diesen Monat"
          action={<Btn variant="ghost" size="sm" trailing={<IconArrowR size={16}/>}
            onClick={() => navigate({ view: 'ranking' })}>Zur Top-Liste</Btn>}/>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {popular.slice(0,4).map((c, i) => (
            <ColoringCard key={c.id} item={c} navigate={navigate} collection={collection} toggleCollect={toggleCollect}
              badge={<><IconTrophy size={12}/>Top {i+1}</>} />
          ))}
        </div>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5 mt-5">
          {popular.slice(4,8).map(c => <ColoringCard key={c.id} item={c} navigate={navigate} collection={collection} toggleCollect={toggleCollect}/>)}
        </div>
      </section>

      {/* Top Kategorien */}
      <section className="max-w-7xl mx-auto px-5 sm:px-8 mt-20">
        <SectionHeading kicker="Lieblingsthemen" title="Top Kategorien"/>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {topCats.map(c => <CategoryCard key={c.slug} cat={c} navigate={navigate}/>)}
        </div>
      </section>

      {/* AdSense slot, inline */}
      <section className="max-w-5xl mx-auto px-5 sm:px-8 mt-12">
        <AdBanner slot="inline" size="leaderboard" user={user}/>
      </section>

      {/* CTA banner removed, moved above (under hero) */}

      {/* SEO text */}
      <section className="max-w-3xl mx-auto px-5 sm:px-8 mt-24 text-center">
        <h3 className="font-display text-2xl sm:text-3xl font-bold mb-3">Kostenlose Ausmalbilder zum Ausdrucken</h3>
        <p className="text-inkSoft leading-relaxed">
          Auf <strong>Malfino.de</strong> findest du eine wachsende Sammlung kostenloser Malvorlagen für Kinder, Eltern, Erzieherinnen und Lehrer. Alle Ausmalbilder sind frei zur privaten Nutzung, einfach das gewünschte Motiv auswählen, als PDF herunterladen oder direkt drucken. Ob niedliche Tiere, magische Einhörner, spannende Dinosaurier oder beruhigende Mandalas: Hier ist für jede kreative Pause das passende Bild dabei. Jedes heruntergeladene oder ausgedruckte Motiv sammelt Punkte, so siehst du sofort, welche Ausmalbilder gerade besonders beliebt sind.
        </p>
      </section>
    </main>
  );
};

const HeroCollage = ({ navigate }) => {
  const today = useTodayStats();
  const todayCount = (today.downloads || 0) + (today.prints || 0);
  return (
  <div className="relative h-[420px] sm:h-[480px]">
    <div className="absolute top-0 right-4 w-56 h-56 bg-paper rounded-3xl ring-2 ring-line shadow-card p-3 rotate-[-4deg] float-a sticker">
      <HeroArt name="rainbow" className="w-full h-full rounded-2xl"/>
    </div>
    <div className="absolute top-32 left-2 w-48 h-48 bg-paper rounded-3xl ring-2 ring-line shadow-card p-3 rotate-[5deg] float-b sticker">
      <HeroArt name="rocket" className="w-full h-full rounded-2xl"/>
    </div>
    <div className="absolute bottom-0 right-12 w-52 h-52 bg-paper rounded-3xl ring-2 ring-line shadow-card p-3 rotate-[3deg] float-c sticker">
      <HeroArt name="bunny" className="w-full h-full rounded-2xl"/>
    </div>
    <div className="absolute top-6 left-12 inline-flex items-center gap-2 bg-coral text-white rounded-full px-3 py-1.5 text-[12px] font-bold rotate-[-6deg] shadow-pop pop-in">
      <IconHeart size={14} className="heart-beat"/>
      {todayCount === 0 ? 'Heute schon los?' : `${todayCount.toLocaleString('de-DE')} Download${todayCount === 1 ? '' : 's'} heute`}
    </div>
    <div className="absolute bottom-12 left-0 inline-flex items-center gap-2 bg-paper ring-2 ring-line rounded-full px-3 py-1.5 text-[12px] font-bold rotate-[4deg] pop-in">
      <IconStar size={14} className="text-sunDeep"/> Top diesen Monat
    </div>
  </div>
  );
};

// === CATEGORY INDEX ===
const CategoryIndexPage = ({ navigate, search, setSearch }) => {
  const filtered = getPublicCategories().filter(c => c.name.toLowerCase().includes(search.toLowerCase()));
  return (
    <main className="max-w-7xl mx-auto px-5 sm:px-8 pt-10 pb-16">
      <Crumbs items={[{label:'Start', target:{view:'home'}},{label:'Alle Kategorien'}]} navigate={navigate}/>
      <div className="mt-4 mb-8">
        <h1 className="font-display text-4xl sm:text-5xl font-bold tracking-tight">Alle Kategorien</h1>
        <p className="text-inkSoft mt-3 max-w-2xl">Wähle ein Lieblingsthema und entdecke unsere Sammlung kostenloser Ausmalbilder zum Ausdrucken.</p>
        <div className="mt-6 max-w-xl">
          <SearchBar value={search} onChange={setSearch} placeholder="Kategorie suchen…" size="md"/>
        </div>
      </div>
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
        {filtered.map(c => <CategoryCard key={c.slug} cat={c} navigate={navigate}/>)}
      </div>
    </main>
  );
};

// === CATEGORY ===
const CategoryPage = ({ slug, navigate, collection, toggleCollect, user }) => {
  const cat = findCategory(slug) || { name: 'Kategorie', slug: slug || '', tone: 'mint', art: 'mandala', count: 0 };
  const tone = TONE_CLASSES[cat.tone] || TONE_CLASSES.mint;
  // Only the images that actually belong to this category.
  const items = coloringsByCategory(cat.slug);
  const [filter, setFilter] = React.useState('beliebt');
  const [shown, setShown] = React.useState(8);
  const sorted = React.useMemo(() => {
    const arr = [...items];
    if (filter === 'beliebt') arr.sort((a,b) => b.points - a.points);
    if (filter === 'neu') arr.sort((a,b) => (b.isNew?1:0) - (a.isNew?1:0));
    if (filter === 'einfach') return arr.filter(x => x.difficulty === 'Einfach');
    if (filter === 'detail') return arr.filter(x => x.difficulty === 'Detailreich');
    return arr;
  }, [filter, slug]);

  return (
    <main>
      <section className={cls("border-b border-line", tone.soft)}>
        <div className="max-w-7xl mx-auto px-5 sm:px-8 py-12">
          <Crumbs items={[
            {label:'Start', target:{view:'home'}},
            {label:'Kategorien', target:{view:'categoryIndex'}},
            {label:cat.name}
          ]} navigate={navigate}/>
          <div className="mt-5 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-6">
            <div className="max-w-2xl">
              <div className="inline-flex items-center gap-1.5 text-[12px] font-bold uppercase tracking-[0.12em] text-inkSoft mb-2">
                <IconTag size={14}/>{cat.count} Ausmalbilder
              </div>
              <h1 className="font-display text-5xl font-bold tracking-tight">Ausmalbilder {cat.name}</h1>
              <p className="text-inkSoft mt-3 leading-relaxed">
                Ob für die Kita, die Schule oder den Regennachmittag zuhause, entdecke unsere liebevoll gestalteten {cat.name}-Malvorlagen. Alle Bilder kannst du kostenlos herunterladen oder direkt ausdrucken.
              </p>
            </div>
            <div className="bg-paper rounded-2xl p-3 ring-1 ring-line w-32 h-32 flex items-center justify-center shrink-0">
              <ColoringArt artKey={cat.art} className="w-24 h-24"/>
            </div>
          </div>
        </div>
      </section>

      <section className="max-w-7xl mx-auto px-5 sm:px-8 py-10">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-7">
          <Tabs tabs={[
            {label:'Beliebt', value:'beliebt'},
            {label:'Neu', value:'neu'},
            {label:'Einfach', value:'einfach'},
            {label:'Detailreich', value:'detail'},
          ]} value={filter} onChange={setFilter}/>
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-sun/40 text-amber-900">
            <IconTrophy size={16}/>
            <span className="text-sm font-semibold">Beliebt diesen Monat</span>
          </div>
        </div>

        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {sorted.slice(0, shown).map(c => <ColoringCard key={c.id} item={c} navigate={navigate} collection={collection} toggleCollect={toggleCollect}/>)}
        </div>

        {/* AdSense, inline between grid and pagination */}
        <div className="mt-10 max-w-4xl mx-auto">
          <AdBanner slot="inline" size="leaderboard" user={user}/>
        </div>

        {shown < sorted.length && (
          <div className="mt-10 text-center">
            <Btn variant="soft" size="lg" onClick={() => setShown(s => s + 8)}
              trailing={<IconChevronR size={18}/>}>
              Mehr laden
            </Btn>
            <div className="mt-3 text-[12px] text-inkSoft">{shown} von {sorted.length} angezeigt</div>
          </div>
        )}
      </section>
    </main>
  );
};

// === DETAIL ===
const DetailPage = ({ slug, navigate, points, bumpPoints, collection, toggleCollect, user }) => {
  const realItem = findColoring(slug);
  const item = realItem || { id: 0, category: '', title: 'Nicht gefunden', tags: [], downloads: 0, prints: 0, points: 0, art: 'mandala', previewUrl: '', difficulty: 'Einfach' };
  const cat = findCategory(item.category) || { name: '', slug: '', tone: 'mint' };
  const tone = TONE_CLASSES[cat.tone] || TONE_CLASSES.mint;
  const [bursts, setBursts] = React.useState([]);
  const [stats, setStats] = React.useState({
    downloads: item.downloads, prints: item.prints, points: item.points
  });

  const bump = (kind) => {
    const inc = kind === 'download' ? 2 : 3;
    // Persist to the shared data object so lists/ranking reflect the new count.
    if (kind === 'download') item.downloads += 1;
    if (kind === 'print')    item.prints += 1;
    item.points += inc;
    setStats({ downloads: item.downloads, prints: item.prints, points: item.points });
    const id = Math.random();
    setBursts(b => [...b, { id, value: `+${inc}`, kind }]);
    setTimeout(() => setBursts(b => b.filter(x => x.id !== id)), 1100);
    bumpPoints && bumpPoints(inc);
    // Actually trigger the action
    if (kind === 'download') downloadColoring(item);
    if (kind === 'print') printColoring(item);
  };

  const similar = COLORINGS.filter(c => c.category === item.category && c.id !== item.id).slice(0,4);
  const fillers = COLORINGS.filter(c => c.id !== item.id).slice(0, 4 - similar.length);
  const related = [...similar, ...fillers].slice(0,4);

  if (!realItem) {
    return (
      <main className="max-w-3xl mx-auto px-5 sm:px-8 pt-16 pb-24 text-center">
        <div className="text-6xl mb-4">🔍</div>
        <h1 className="font-display text-3xl font-extrabold">Ausmalbild nicht gefunden</h1>
        <p className="text-inkSoft mt-3">Dieses Bild gibt es (noch) nicht.</p>
        <div className="mt-7"><Btn size="lg" onClick={() => navigate({ view: 'home' })}>Zur Startseite</Btn></div>
      </main>
    );
  }
  return (
    <main className="max-w-7xl mx-auto px-5 sm:px-8 pt-8 pb-16">
      <Crumbs items={[
        {label:'Start', target:{view:'home'}},
        {label:cat.name, target:{view:'category', slug:cat.slug}},
        {label:item.title}
      ]} navigate={navigate}/>

      <div className="mt-6 grid lg:grid-cols-12 gap-10">
        {/* Preview */}
        <div className="lg:col-span-7">
          <div className="bg-paper rounded-xl3 ring-1 ring-line p-6 sm:p-8">
            <div className="paper-bg rounded-2xl aspect-[4/3] flex items-center justify-center relative">
              <div className="absolute inset-6 rounded-2xl border border-dashed border-line"></div>
              {item.previewUrl
                ? <img src={item.previewUrl} alt={item.title} className="max-w-[82%] max-h-[88%] object-contain"/>
                : <ColoringArt artKey={item.art} className="w-[68%] h-[78%]"/>}
              {item.isNew && (
                <span className="absolute top-4 left-4 inline-flex items-center gap-1 px-3 py-1.5 rounded-full bg-coral text-white text-[12px] font-bold">
                  <IconSparkle size={13}/> NEU
                </span>
              )}
            </div>
            <div className="mt-5 flex flex-wrap items-center gap-2 text-[13px] text-inkSoft">
              <span className="inline-flex items-center gap-1.5"><IconImage size={14}/>A4 · PDF · 300 dpi</span>
              <span>·</span>
              <span className="inline-flex items-center gap-1.5"><IconPalette size={14}/>{item.difficulty}</span>
              <span>·</span>
              <span className="inline-flex items-center gap-1.5"><IconShield size={14}/>Kostenlos für private Nutzung</span>
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="lg:col-span-5">
          <span className={cls("inline-flex items-center px-2.5 py-1 rounded-full text-[12px] font-semibold", tone.soft, tone.text)}>
            {cat.name}
          </span>
          <h1 className="mt-3 font-display text-4xl sm:text-5xl font-bold leading-tight tracking-tight">{item.title}</h1>
          <p className="mt-4 text-inkSoft leading-relaxed">
            Ein zauberhaftes Motiv mit klaren Linien und vielen Flächen zum Ausmalen, perfekt für Kinder ab 4 Jahren. Geeignet für Buntstifte, Filzstifte oder Wasserfarben.
          </p>

          <div className="mt-5 flex flex-wrap gap-2">
            {item.tags.map(t => (
              <span key={t} className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full bg-paper ring-1 ring-line text-[12px] font-semibold">
                <IconTag size={12}/>{t}
              </span>
            ))}
          </div>

          <div className="relative mt-7 grid grid-cols-2 gap-3">
            <div className="relative">
              <Btn size="lg" leading={<IconDownload size={18}/>} className="w-full"
                onClick={() => bump('download')}>Herunterladen</Btn>
              {bursts.filter(b => b.kind === 'download').map(b => (
                <span key={b.id}
                  className="point-burst absolute -top-1 left-1/2 -translate-x-1/2 px-2.5 py-1 rounded-full bg-sun text-ink text-xs font-bold pointer-events-none">
                  ⭐ {b.value}
                </span>
              ))}
            </div>
            <div className="relative">
              <Btn size="lg" variant="secondary" leading={<IconPrinter size={18}/>} className="w-full"
                onClick={() => bump('print')}>Drucken</Btn>
              {bursts.filter(b => b.kind === 'print').map(b => (
                <span key={b.id}
                  className="point-burst absolute -top-1 left-1/2 -translate-x-1/2 px-2.5 py-1 rounded-full bg-sun text-ink text-xs font-bold pointer-events-none">
                  ⭐ {b.value}
                </span>
              ))}
            </div>
          </div>

          {toggleCollect && (() => {
            const inMappe = collection && collection.some(x => x.id === item.id);
            return (
              <button onClick={() => toggleCollect(item)}
                className={cls("mt-3 w-full inline-flex items-center justify-center gap-2 px-5 py-3.5 rounded-full font-bold text-[15px] transition ring-2",
                  inMappe ? 'bg-mint text-emerald-900 ring-emerald-700/30 hover:bg-emerald-200'
                          : 'bg-paper text-ink ring-line hover:ring-coral')}>
                {inMappe ? <><IconCheck size={18}/>In Sammelmappe</> : <><span aria-hidden="true">🎒</span> Zur Sammelmappe hinzufügen</>}
              </button>
            );
          })()}

          <div className="mt-6 flex items-start gap-3 p-4 rounded-2xl bg-mint/30 ring-1 ring-mint">
            <IconShield size={18} className="text-emerald-700 mt-0.5"/>
            <div className="text-sm">
              <strong>Kostenlos für private Nutzung.</strong>
              <span className="text-inkSoft"> Druck und Einsatz in Kita, Schule und zuhause sind erlaubt.</span>
            </div>
          </div>

          {/* AdSense, sidebar */}
          <div className="mt-5">
            <AdBanner slot="sidebar" size="medium" user={user}/>
          </div>
        </div>
      </div>

      {/* Similar */}
      <section className="mt-16">
        <SectionHeading kicker="Empfehlung" title="Ähnliche Ausmalbilder"/>
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {related.map(c => <ColoringCard key={c.id} item={c} navigate={navigate} collection={collection} toggleCollect={toggleCollect}/>)}
        </div>
      </section>

      <CommentSection slug={item.slug} user={user} navigate={navigate}
        openAuth={() => window.dispatchEvent(new CustomEvent('aw:open-auth'))}/>
    </main>
  );
};

const StatPill = ({ icon, label, value, tone = 'sky' }) => {
  const t = TONE_CLASSES[tone];
  return (
    <div className="bg-paper rounded-2xl ring-1 ring-line p-4">
      <div className="flex items-center gap-2 text-[11px] uppercase tracking-wider font-bold text-inkSoft">
        <span className={cls("inline-flex w-6 h-6 rounded-full items-center justify-center", t.soft, t.text)}>{icon}</span>
        {label}
      </div>
      <div className="mt-1.5 font-display text-2xl font-bold leading-none">{value}</div>
    </div>
  );
};

// === RANKING ===
const RankingPage = ({ navigate, collection, toggleCollect, user }) => {
  const [period, setPeriod] = React.useState('monat');
  const [view, setView] = React.useState('bilder'); // 'bilder' | 'kategorien'
  const [catFilter, setCatFilter] = React.useState('alle');
  const [diffFilter, setDiffFilter] = React.useState('alle');
  const seedShift = { heute: 0, woche: 1, monat: 2, jahr: 3, letztesJahr: 4, gesamt: 5 }[period] || 0;

  // Re-derive ranking based on period (mock: rotate + scale points)
  const list = React.useMemo(() => {
    const arr = [...COLORINGS].map((c, i) => ({
      ...c,
      points: Math.max(40, Math.round(c.points * (period==='heute'?0.04:period==='woche'?0.22:period==='monat'?1:period==='jahr'?6:period==='letztesJahr'?5:14)
        - (i+seedShift)*7))
    })).sort((a,b)=>b.points-a.points).map((c, idx) => ({...c, rank: idx+1}));
    return arr;
  }, [period]);

  // Apply filters (only used in 'bilder' view)
  const filtered = React.useMemo(() => {
    let arr = list;
    if (catFilter !== 'alle')  arr = arr.filter(c => c.category === catFilter);
    if (diffFilter !== 'alle') arr = arr.filter(c => c.difficulty === diffFilter);
    return arr.map((c, idx) => ({ ...c, rank: idx + 1 }));
  }, [list, catFilter, diffFilter]);

  // Aggregate per-category points for the "Top Kategorien" view
  const categoryRanking = React.useMemo(() => {
    const totals = {};
    list.forEach(c => { totals[c.category] = (totals[c.category] || 0) + c.points; });
    return CATEGORIES.map(cat => {
      const items = list.filter(c => c.category === cat.slug);
      const top = items[0];
      return {
        ...cat,
        points: totals[cat.slug] || 0,
        items: items.length,
        top,
      };
    }).sort((a, b) => b.points - a.points).map((c, idx) => ({ ...c, rank: idx + 1 }));
  }, [list]);

  return (
    <main className="max-w-7xl mx-auto px-5 sm:px-8 pt-10 pb-16">
      <Crumbs items={[{label:'Start', target:{view:'home'}},{label:'Beliebteste Ausmalbilder'}]} navigate={navigate}/>
      <div className="mt-4 mb-6">
        <div className="inline-flex items-center gap-2 bg-coral text-white rounded-full pl-1.5 pr-4 py-1.5 mb-4">
          <span className="inline-flex w-7 h-7 rounded-full bg-white text-coral items-center justify-center"><IconTrophy size={15}/></span>
          <span className="text-[12px] font-bold tracking-wide">Charts</span>
        </div>
        <h1 className="font-display text-4xl sm:text-5xl font-extrabold tracking-tight">Beliebteste Ausmalbilder</h1>
        <p className="text-inkSoft mt-3 max-w-2xl">Punkte sammeln Bilder durch Downloads und Druckvorgänge. So siehst du sofort, was gerade angesagt ist.</p>
      </div>

      {/* Time tabs */}
      <div className="flex flex-wrap items-center gap-3">
        <Tabs tabs={[
          {label:'Heute', value:'heute'},
          {label:'Diese Woche', value:'woche'},
          {label:'Dieser Monat', value:'monat'},
          {label:'Dieses Jahr', value:'jahr'},
          {label:'Letztes Jahr', value:'letztesJahr'},
          {label:'Insgesamt', value:'gesamt'},
        ]} value={period} onChange={setPeriod}/>
      </div>

      {/* Bilder/Kategorien switch */}
      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
        <div className="inline-flex items-center bg-paper ring-2 ring-line rounded-full p-1">
          {[
            {l:'🏆 Top Bilder',     v:'bilder'},
            {l:'🏷️ Top Kategorien', v:'kategorien'},
          ].map(t => (
            <button key={t.v} onClick={() => setView(t.v)}
              className={cls("px-4 py-2 rounded-full text-sm font-bold transition",
                view === t.v ? 'bg-ink text-white' : 'text-ink hover:bg-ink/5')}>
              {t.l}
            </button>
          ))}
        </div>

        {view === 'bilder' && (
          <div className="flex flex-wrap items-center gap-2">
            <span className="text-[12px] font-bold uppercase tracking-wider text-inkSoft inline-flex items-center gap-1.5">
              <IconFilter size={14}/>Filter:
            </span>
            <FilterSelect value={catFilter} onChange={setCatFilter}
              options={[{value:'alle', label:'Alle Kategorien'}, ...CATEGORIES.map(c => ({value:c.slug, label:c.name}))]}/>
            <FilterSelect value={diffFilter} onChange={setDiffFilter}
              options={[
                {value:'alle', label:'Alle Schwierigkeiten'},
                {value:'Einfach', label:'Einfach'},
                {value:'Mittel', label:'Mittel'},
                {value:'Detailreich', label:'Detailreich'},
              ]}/>
            {(catFilter !== 'alle' || diffFilter !== 'alle') && (
              <button onClick={() => { setCatFilter('alle'); setDiffFilter('alle'); }}
                className="text-[12px] font-bold text-coralDeep hover:underline">Filter zurücksetzen</button>
            )}
          </div>
        )}
      </div>

      {/* AdSense, leaderboard above ranking content */}
      <div className="mt-6 max-w-4xl mx-auto">
        <AdBanner slot="inline" size="leaderboard" user={user}/>
      </div>

      {/* === Top Bilder === */}
      {view === 'bilder' && (
        <>
          {filtered.length === 0 ? (
            <div className="mt-10 bg-paper rounded-3xl ring-2 ring-line p-12 text-center">
              <div className="text-5xl mb-3">🤔</div>
              <div className="font-display text-xl font-extrabold">Keine Bilder gefunden</div>
              <div className="text-inkSoft mt-1">Versuche andere Filter.</div>
            </div>
          ) : (
            <>
              <div className="grid sm:grid-cols-3 gap-5 mt-8">
                {filtered.slice(0,3).map((c, i) => (
                  <PodiumCard key={c.id} item={c} place={i+1} navigate={navigate}/>
                ))}
              </div>
              {filtered.length > 3 && (
                <div className="mt-10 bg-paper rounded-xl3 ring-1 ring-line overflow-hidden">
                  {filtered.slice(3).map((c, idx) => (
                    <RankRow key={c.id} item={c} navigate={navigate} divider={idx !== 0}/>
                  ))}
                </div>
              )}
            </>
          )}
        </>
      )}

      {/* === Top Kategorien === */}
      {view === 'kategorien' && (
        <div className="mt-8 grid lg:grid-cols-2 gap-5">
          {categoryRanking.map((c, idx) => {
            const tone = TONE_CLASSES[c.tone];
            return (
              <button key={c.slug} onClick={() => navigate({ view:'category', slug: c.slug })}
                className="text-left bg-paper rounded-3xl ring-2 ring-line hover:ring-ink/20 hover:shadow-card transition overflow-hidden group stagger-fade"
                style={{animationDelay:`${idx*40}ms`}}>
                <div className="flex items-center gap-4 p-5">
                  <RankBadge rank={c.rank} size="lg"/>
                  <div className={cls("w-20 h-20 rounded-2xl flex items-center justify-center shrink-0", tone.bg)}>
                    <ColoringArt artKey={c.art} className="w-14 h-14 group-hover:scale-110 group-hover:-rotate-3 transition-transform"/>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-display text-2xl font-extrabold leading-tight">{c.name}</div>
                    <div className="text-[13px] text-inkSoft mt-0.5">
                      {c.count} Bilder · Top: <strong className="text-ink">{c.top?.title}</strong>
                    </div>
                    <div className="mt-2 flex items-center gap-3 text-[13px]">
                      <span className="inline-flex items-center gap-1 font-extrabold">
                        <IconStar size={15} className="text-sunDeep"/>{c.points.toLocaleString('de-DE')}
                      </span>
                      <span className="text-inkSoft">Punkte gesamt</span>
                    </div>
                  </div>
                  <IconChevronR size={20} className="text-inkSoft group-hover:text-coralDeep transition"/>
                </div>
              </button>
            );
          })}
        </div>
      )}
    </main>
  );
};

const FilterSelect = ({ value, onChange, options }) => (
  <div className="relative">
    <select value={value} onChange={(e) => onChange(e.target.value)}
      className="appearance-none bg-paper ring-2 ring-line rounded-full pl-4 pr-9 py-2 text-sm font-bold cursor-pointer hover:ring-ink/30 outline-none focus:ring-coral transition">
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
    <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2">
      <IconChevronR size={14} className="rotate-90 text-inkSoft"/>
    </span>
  </div>
);

const PodiumCard = ({ item, place, navigate }) => {
  const cat = findCategory(item.category);
  const tone = TONE_CLASSES[cat.tone];
  const podiumTone = place === 1 ? 'bg-sun' : place === 2 ? 'bg-sky' : 'bg-coral';
  const lift = place === 1 ? '-translate-y-3' : place === 2 ? 'translate-y-1' : 'translate-y-3';
  return (
    <button onClick={() => navigate({view:'detail', slug:item.slug})}
      className={cls("text-left bg-paper rounded-xl3 ring-1 ring-line hover:shadow-card transition overflow-hidden", lift)}>
      <div className={cls("relative paper-bg p-5 aspect-[5/4] flex items-center justify-center")}>
        <ColoringArt artKey={item.art} className="w-[68%] h-[78%]"/>
        <span className={cls("absolute top-3 left-3 inline-flex items-center justify-center w-12 h-12 rounded-full font-display font-bold text-lg", podiumTone, place===3?'text-white':'text-ink')}>
          #{place}
        </span>
        {place === 1 && (
          <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">
            <IconTrophy size={12}/>Top Download
          </span>
        )}
        {place === 2 && (
          <span className="absolute top-3 right-3 inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-mint text-emerald-900 text-[11px] font-bold">
            <IconHeart size={12}/>Beliebt bei Kindern
          </span>
        )}
      </div>
      <div className="p-5">
        <div className={cls("inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold mb-1.5", tone.soft, tone.text)}>{cat.name}</div>
        <div className="font-display text-xl font-bold leading-tight">{item.title}</div>
        <div className="mt-3 flex items-center justify-between text-[13px]">
          <span className="inline-flex items-center gap-1.5 font-semibold"><IconStar size={15} className="text-sunDeep"/>{item.points.toLocaleString('de-DE')} Punkte</span>
          <span className="text-inkSoft inline-flex items-center gap-1"><IconDownload size={14}/>{item.downloads.toLocaleString('de-DE')}</span>
        </div>
      </div>
    </button>
  );
};

const RankRow = ({ item, navigate, divider }) => {
  const cat = findCategory(item.category);
  const tone = TONE_CLASSES[cat.tone];
  return (
    <button onClick={() => navigate({view:'detail', slug:item.slug})}
      className={cls("w-full text-left flex items-center gap-4 px-4 sm:px-6 py-4 hover:bg-cream/60 transition",
        divider && 'border-t border-line')}>
      <RankBadge rank={item.rank}/>
      <div className={cls("hidden sm:flex w-16 h-16 rounded-2xl items-center justify-center shrink-0", tone.soft)}>
        <ColoringArt artKey={item.art} className="w-12 h-12"/>
      </div>
      <div className="flex-1 min-w-0">
        <div className={cls("inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold mb-0.5", tone.soft, tone.text)}>{cat.name}</div>
        <div className="font-display text-lg font-bold leading-tight truncate">{item.title}</div>
      </div>
      <div className="hidden md:flex items-center gap-5 text-[13px] text-inkSoft">
        <span className="inline-flex items-center gap-1"><IconDownload size={14}/>{item.downloads.toLocaleString('de-DE')}</span>
        <span className="inline-flex items-center gap-1"><IconPrinter size={14}/>{item.prints.toLocaleString('de-DE')}</span>
      </div>
      <div className="font-display text-lg font-bold inline-flex items-center gap-1.5">
        <IconStar size={16} className="text-sunDeep"/>{item.points.toLocaleString('de-DE')}
      </div>
      <IconChevronR size={18} className="text-inkSoft"/>
    </button>
  );
};

// === Breadcrumbs (used by several pages) ===
const Crumbs = ({ items, navigate }) => (
  <nav className="text-[13px] text-inkSoft flex items-center gap-1.5 flex-wrap">
    {items.map((it, i) => (
      <React.Fragment key={i}>
        {it.target ? (
          <button className="hover:text-ink" onClick={() => navigate(it.target)}>{it.label}</button>
        ) : (
          <span className="text-ink font-semibold">{it.label}</span>
        )}
        {i < items.length - 1 && <IconChevronR size={14}/>}
      </React.Fragment>
    ))}
  </nav>
);

Object.assign(window, {
  HomePage, CategoryIndexPage, CategoryPage, DetailPage, RankingPage, Crumbs,
});
