// Multi-Sammelmappe panel: list of mappen → drill into one mappe with drag-drop reorder
// (premium feature) and child-assignment chips.

const MappePanel = ({ open, onClose, mappen, focusMappeId, setFocusMappeId,
  createMappe, renameMappe, deleteMappe, removeFromMappe,
  reorderInMappe, assignChild,
  childrenList, addChild, renameChild, deleteChild,
  navigate, openPrintFor, user, openAuth }) => {
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  const [newChild, setNewChild] = React.useState('');
  const [showChildren, setShowChildren] = React.useState(false);
  const [dragIdx, setDragIdx] = React.useState(null);
  const [overIdx, setOverIdx] = React.useState(null);
  const [settings] = useSettings();

  if (!open) return null;
  const focused = mappen.find(m => m.id === focusMappeId);
  const totalItems = mappen.reduce((s, m) => s + m.items.length, 0);
  const isPremium = isUserPremium(user);
  const reorderIsPremium = settings.premium.enabled && settings.premium.features.multiMappen;

  // Hard auth gate
  if (!user) {
    return (
      <div className="fixed inset-0 z-50 flex">
        <div className="absolute inset-0 bg-ink/40 backdrop-blur-sm" onClick={onClose}></div>
        <aside className="ml-auto relative w-full sm:w-[480px] h-full bg-cream flex flex-col shadow-2xl panel-slide-in">
          <div className="flex items-center gap-3 p-5 border-b-2 border-line bg-paper">
            <span className="inline-flex w-12 h-12 rounded-2xl bg-coral text-white items-center justify-center text-2xl shadow-pop">🎒</span>
            <div className="flex-1 min-w-0">
              <div className="font-display text-xl font-extrabold leading-none">Sammelmappen</div>
              <div className="text-[13px] text-inkSoft mt-1">Nur für angemeldete Nutzer</div>
            </div>
            <button onClick={onClose} className="p-2 rounded-full hover:bg-ink/5"><IconClose/></button>
          </div>
          <div className="flex-1 overflow-y-auto scroll-soft p-6 flex flex-col items-center justify-center text-center">
            <div className="w-24 h-24 rounded-full bg-sun/40 flex items-center justify-center text-5xl mb-5">🔒</div>
            <div className="font-display text-2xl font-extrabold mb-2">Melde dich an</div>
            <p className="text-[14px] text-inkSoft max-w-[320px] mb-5 leading-relaxed">
              Sammelmappen sind an dein Profil geknüpft, damit deine Lieblingsbilder auf jedem Gerät verfügbar sind.
            </p>
            <div className="flex flex-col gap-2 w-full max-w-[280px]">
              <Btn size="lg" onClick={() => { onClose(); openAuth(); }}>Profil erstellen oder anmelden</Btn>
              <button onClick={onClose} className="text-[13px] text-inkSoft hover:text-ink font-bold py-2">Später</button>
            </div>
          </div>
        </aside>
      </div>
    );
  }

  // Drag handlers
  const onDragStart = (idx) => () => setDragIdx(idx);
  const onDragOver = (idx) => (e) => { e.preventDefault(); setOverIdx(idx); };
  const onDrop = (idx) => (e) => {
    e.preventDefault();
    if (dragIdx === null || dragIdx === idx) { setDragIdx(null); setOverIdx(null); return; }
    reorderInMappe(focused.id, dragIdx, idx);
    setDragIdx(null); setOverIdx(null);
  };
  const onDragEnd = () => { setDragIdx(null); setOverIdx(null); };

  // Mappe -> assigned child object
  const childOf = (m) => (childrenList || []).find(c => c.id === m.childId);

  return (
    <div className="fixed inset-0 z-50 flex">
      <div className="absolute inset-0 bg-ink/40 backdrop-blur-sm" onClick={onClose}></div>
      <aside className="ml-auto relative w-full sm:w-[500px] h-full bg-cream flex flex-col shadow-2xl panel-slide-in">
        <div className="flex items-center gap-3 p-5 border-b-2 border-line bg-paper">
          {focused && (
            <button onClick={() => setFocusMappeId(null)} className="p-2 rounded-full hover:bg-ink/5 -ml-2">
              <IconChevronL size={20}/>
            </button>
          )}
          <span className="inline-flex w-12 h-12 rounded-2xl bg-coral text-white items-center justify-center text-2xl shadow-pop bag-bounce">
            {focused ? focused.emoji : '🎒'}
          </span>
          <div className="flex-1 min-w-0">
            <div className="font-display text-xl font-extrabold leading-none truncate">
              {focused ? focused.name : 'Deine Sammelmappen'}
            </div>
            <div className="text-[13px] text-inkSoft mt-1">
              {focused
                ? `${focused.items.length} Bild${focused.items.length === 1 ? '' : 'er'}${childOf(focused) ? ` · für ${childOf(focused).name}` : ''}`
                : `${mappen.length} Mappe${mappen.length === 1 ? '' : 'n'} · ${totalItems} Bild${totalItems === 1 ? '' : 'er'} insgesamt`}
            </div>
          </div>
          <button onClick={onClose} className="p-2 rounded-full hover:bg-ink/5"><IconClose/></button>
        </div>

        {/* LIST view */}
        {!focused && (
          <div className="flex-1 overflow-y-auto scroll-soft p-5 space-y-3">
            {/* Children section */}
            <div className="bg-paper rounded-2xl ring-2 ring-line p-3">
              <button onClick={() => setShowChildren(s => !s)}
                className="w-full flex items-center gap-2 text-left">
                <span className="text-xl">👨‍👩‍👧</span>
                <div className="flex-1 min-w-0">
                  <div className="font-display text-sm font-extrabold leading-tight">Kinder verwalten</div>
                  <div className="text-[11px] text-inkSoft">
                    {(childrenList || []).length === 0 ? 'Mappen Kindern zuordnen' : `${childrenList.length} Kind${childrenList.length === 1 ? '' : 'er'} hinterlegt`}
                  </div>
                </div>
                <IconChevronR size={16} className={cls("text-inkSoft transition", showChildren && 'rotate-90')}/>
              </button>
              {showChildren && (
                <div className="mt-3 pt-3 border-t border-line grid gap-2">
                  {(childrenList || []).map(c => (
                    <div key={c.id} className="flex items-center gap-2 bg-cream rounded-xl px-3 py-2">
                      <span className="text-xl">{c.emoji || '🧒'}</span>
                      <input value={c.name} onChange={(e) => renameChild(c.id, e.target.value)}
                        className="flex-1 min-w-0 bg-transparent outline-none text-sm font-semibold"/>
                      <button onClick={() => { if (confirm(`Kind „${c.name}" löschen? Mappen werden nicht gelöscht.`)) deleteChild(c.id); }}
                        className="p-1.5 rounded-lg hover:bg-coral/10 text-coralDeep">
                        <IconTrash size={14}/>
                      </button>
                    </div>
                  ))}
                  <div className="flex gap-2">
                    <input value={newChild} onChange={(e) => setNewChild(e.target.value)}
                      placeholder="Name des Kindes" maxLength={30}
                      className="flex-1 min-w-0 px-3 py-2 rounded-xl bg-cream ring-1 ring-line outline-none focus:ring-2 focus:ring-coral text-sm"/>
                    <Btn size="sm" onClick={() => { if (!newChild.trim()) return; addChild(newChild.trim()); setNewChild(''); }}
                      leading={<IconPlus size={14}/>}>Hinzufügen</Btn>
                  </div>
                </div>
              )}
            </div>

            {mappen.map(m => {
              const ch = childOf(m);
              return (
                <button key={m.id} onClick={() => setFocusMappeId(m.id)}
                  className="w-full text-left flex items-center gap-3 bg-paper rounded-2xl ring-2 ring-line hover:ring-coral hover:bg-coral/5 transition p-3 stagger-fade">
                  <span className="inline-flex w-14 h-14 rounded-2xl bg-cream items-center justify-center text-3xl shrink-0">{m.emoji}</span>
                  <div className="flex-1 min-w-0">
                    <div className="font-display text-lg font-extrabold leading-tight truncate">{m.name}</div>
                    <div className="text-[12px] text-inkSoft flex items-center gap-2">
                      <span>{m.items.length === 0 ? 'Leer' : `${m.items.length} Bilder`}</span>
                      {ch && (
                        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-sun/40 text-amber-900 text-[10px] font-bold">
                          {ch.emoji || '🧒'} {ch.name}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="hidden sm:flex items-center gap-1">
                    {m.items.slice(0, 3).map(it => (
                      <div key={it.id} className="w-8 h-8 rounded-lg bg-cream ring-1 ring-line items-center justify-center flex">
                        <ColoringArt artKey={it.art} className="w-6 h-6"/>
                      </div>
                    ))}
                  </div>
                  <IconChevronR size={18} className="text-inkSoft"/>
                </button>
              );
            })}

            {creating ? (
              <div className="bg-coral/5 ring-2 ring-coral rounded-2xl p-4">
                <div className="text-[13px] font-bold mb-2">Name der neuen Mappe</div>
                <input value={newName} onChange={(e) => setNewName(e.target.value)} autoFocus
                  placeholder="z. B. Geburtstag Mia"
                  className="w-full px-4 py-3 rounded-xl bg-paper ring-1 ring-line outline-none focus:ring-2 focus:ring-coral"/>
                <div className="mt-3 flex gap-2">
                  <Btn size="sm" onClick={() => {
                    if (!newName.trim()) return;
                    createMappe(newName.trim());
                    setNewName(''); setCreating(false);
                  }}>Anlegen</Btn>
                  <Btn size="sm" variant="ghost" onClick={() => { setCreating(false); setNewName(''); }}>Abbrechen</Btn>
                </div>
              </div>
            ) : (
              <button onClick={() => setCreating(true)}
                className="w-full text-left flex items-center gap-3 bg-paper rounded-2xl ring-2 ring-dashed ring-line hover:ring-coral hover:bg-coral/5 transition p-4">
                <span className="inline-flex w-12 h-12 rounded-xl bg-coral text-white items-center justify-center"><IconPlus size={20}/></span>
                <div>
                  <div className="font-display text-base font-extrabold">Neue Sammelmappe</div>
                  <div className="text-[12px] text-inkSoft">Z. B. pro Kind, Anlass oder Thema</div>
                </div>
              </button>
            )}
          </div>
        )}

        {/* DETAIL view */}
        {focused && (
          <>
            <div className="flex-1 overflow-y-auto scroll-soft p-5 space-y-3">
              {/* Child assignment chips */}
              {(childrenList || []).length > 0 && (
                <div className="bg-paper rounded-2xl ring-2 ring-line p-3">
                  <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-2 inline-flex items-center gap-1.5">
                    <span>👨‍👩‍👧</span> Diese Mappe gehört zu …
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <button onClick={() => assignChild(focused.id, null)}
                      className={cls("inline-flex items-center gap-1 px-3 py-1.5 rounded-full ring-2 text-[12px] font-bold transition",
                        !focused.childId ? 'ring-coral bg-coral/10 text-coralDeep' : 'ring-line bg-cream hover:ring-ink/30')}>
                     , keinem Kind -
                    </button>
                    {childrenList.map(c => (
                      <button key={c.id} onClick={() => assignChild(focused.id, c.id)}
                        className={cls("inline-flex items-center gap-1 px-3 py-1.5 rounded-full ring-2 text-[12px] font-bold transition",
                          focused.childId === c.id ? 'ring-coral bg-coral/10 text-coralDeep' : 'ring-line bg-cream hover:ring-ink/30')}>
                        <span>{c.emoji || '🧒'}</span> {c.name}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Reorder hint */}
              {focused.items.length > 1 && (
                <div className={cls("rounded-2xl ring-1 p-3 text-[12px] leading-relaxed",
                  isPremium ? 'bg-mint/30 ring-mint text-emerald-900' : 'bg-sun/30 ring-sun text-amber-900')}>
                  {isPremium ? (
                    <><strong>✋ Tipp:</strong> Per Drag &amp; Drop kannst du die Druckreihenfolge ändern. Die Mappe wird in dieser Reihenfolge gedruckt.</>
                  ) : (
                    <><strong>⭐ Premium:</strong> Mit Premium kannst du per Drag &amp; Drop die Druckreihenfolge ändern. {' '}
                      <button onClick={() => { onClose(); navigate({view:'profile', tab:'premium'}); }}
                        className="font-extrabold underline">Jetzt upgraden</button>.</>
                  )}
                </div>
              )}

              {focused.items.length === 0 ? (
                <div className="text-center py-12">
                  <div className="text-6xl mb-4 wiggle">🖍️</div>
                  <div className="font-display text-xl font-extrabold mb-1">Mappe ist leer</div>
                  <p className="text-inkSoft text-sm max-w-[28ch] mx-auto leading-relaxed">
                    Sammle deine Lieblings-Ausmalbilder und drucke sie alle auf einmal!
                  </p>
                  <Btn className="mt-5" onClick={() => { onClose(); navigate({view:'categoryIndex'}); }}>
                    Bilder entdecken
                  </Btn>
                </div>
              ) : focused.items.map((item, idx) => {
                const cat = findCategory(item.category);
                const tone = TONE_CLASSES[cat.tone];
                const canDrag = isPremium;
                const isDragged = dragIdx === idx;
                const isOver = overIdx === idx && dragIdx !== null && dragIdx !== idx;
                return (
                  <div key={item.id}
                    draggable={canDrag}
                    onDragStart={canDrag ? onDragStart(idx) : undefined}
                    onDragOver={canDrag ? onDragOver(idx) : undefined}
                    onDrop={canDrag ? onDrop(idx) : undefined}
                    onDragEnd={canDrag ? onDragEnd : undefined}
                    className={cls("flex items-center gap-3 bg-paper rounded-2xl ring-2 p-3 stagger-fade transition",
                      isDragged ? 'opacity-50 ring-coral' :
                      isOver    ? 'ring-coral ring-4 -translate-y-0.5 shadow-pop' :
                                  'ring-line',
                      canDrag && 'cursor-grab active:cursor-grabbing')}
                    style={{animationDelay:`${idx*40}ms`}}>
                    {canDrag && (
                      <span className="text-inkSoft/60 select-none text-base shrink-0" title="Ziehen zum Sortieren">⋮⋮</span>
                    )}
                    <span className="font-display text-xs font-extrabold text-inkSoft w-6 text-center shrink-0">{idx+1}.</span>
                    <div className={cls("w-14 h-14 rounded-xl flex items-center justify-center shrink-0", tone.bg)}>
                      <ColoringArt artKey={item.art} className="w-10 h-10"/>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-display font-extrabold leading-tight truncate">{item.title}</div>
                      <div className="text-[12px] text-inkSoft">{cat.name}</div>
                    </div>
                    <button onClick={() => printColoring(item)}
                      className="p-2 rounded-lg hover:bg-sky/30 text-skyDeep" title="Drucken">
                      <IconPrinter size={16}/>
                    </button>
                    <button onClick={() => removeFromMappe(focused.id, item.id)}
                      className="p-2 rounded-lg hover:bg-coral/10 text-coralDeep" title="Entfernen">
                      <IconTrash size={16}/>
                    </button>
                  </div>
                );
              })}
            </div>

            {focused.items.length > 0 && (
              <div className="border-t-2 border-line p-5 bg-paper grid gap-2">
                <Btn size="lg" leading={<IconPrinter size={20}/>} onClick={() => openPrintFor(focused.id)}>
                  Alle {focused.items.length} Bilder drucken
                </Btn>
                <div className="flex gap-2">
                  <Btn variant="soft" size="sm" className="flex-1" leading={<IconEdit size={14}/>}
                    onClick={() => {
                      const name = prompt('Neuer Name:', focused.name);
                      if (name && name.trim()) renameMappe(focused.id, name.trim());
                    }}>
                    Umbenennen
                  </Btn>
                  <Btn variant="ghost" size="sm" onClick={() => {
                      if (confirm(`Mappe „${focused.name}" wirklich löschen?`)) {
                        deleteMappe(focused.id);
                        setFocusMappeId(null);
                      }
                    }}
                    className="text-coralDeep hover:bg-coral/10" leading={<IconTrash size={14}/>}>
                    Löschen
                  </Btn>
                </div>
              </div>
            )}
          </>
        )}
      </aside>
    </div>
  );
};

Object.assign(window, { MappePanel });
