// Profile / Auth: AuthModal, ProfilePill, ProfilePage (Mappen, Vorschläge, Einstellungen)

const initials = (name) => {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/);
  return (parts[0]?.[0] || '').toUpperCase() + (parts[1]?.[0] || '').toUpperCase();
};

// === Avatar bubble ===
const Avatar = ({ user, size = 36 }) => {
  if (!user) return null;
  const palette = AVATAR_PALETTE[user.colorIdx ?? 0];
  return (
    <span
      className="inline-flex items-center justify-center rounded-full font-display font-extrabold shrink-0"
      style={{
        width: size, height: size,
        background: palette.bg, color: palette.fg,
        fontSize: size * 0.42, lineHeight: 1,
      }}>
      {initials(user.name)}
    </span>
  );
};

// === Header pill (signed in) / sign-in button ===
const ProfilePill = ({ user, navigate, openAuth, onSignOut }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  if (!user) {
    return (
      <button onClick={openAuth}
        className="inline-flex items-center gap-2 px-3.5 py-2.5 rounded-full bg-paper ring-2 ring-line hover:ring-ink/30 font-bold text-sm transition">
        <IconUser size={16}/> <span className="hidden sm:inline">Anmelden</span>
      </button>
    );
  }
  const bereich = BEREICH_OPTIONS.find(b => b.value === user.bereich);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(!open)}
        className="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">
        <Avatar user={user} size={32}/>
        <span className="hidden sm:inline font-bold text-sm">{user.name.split(' ')[0]}</span>
        <IconChevronR size={14} 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">
          <div className="p-4 bg-cream border-b-2 border-line flex items-center gap-3">
            <Avatar user={user} size={44}/>
            <div className="min-w-0">
              <div className="font-display font-extrabold leading-tight truncate">{user.name}</div>
              <div className="text-[12px] text-inkSoft truncate">
                {bereich ? `${bereich.emoji} ${bereich.label}` : user.email}
              </div>
            </div>
          </div>
          <div className="p-1.5 grid">
            <MenuItem icon={<IconUser size={16}/>} label="Mein Profil"
              onClick={() => { setOpen(false); navigate({ view: 'profile', tab: 'overview' }); }}/>
            <MenuItem icon={<span aria-hidden="true">🎒</span>} label="Meine Sammelmappen"
              onClick={() => { setOpen(false); navigate({ view: 'profile', tab: 'mappen' }); }}/>
            <MenuItem icon={<IconSparkle size={16}/>} label="Vorschlag einreichen"
              onClick={() => { setOpen(false); navigate({ view: 'profile', tab: 'submit' }); }}/>
            <MenuItem icon={<IconSettings size={16}/>} label="Profil bearbeiten"
              onClick={() => { setOpen(false); navigate({ view: 'profile', tab: 'settings' }); }}/>
            <div className="h-px bg-line my-1"></div>
            <MenuItem icon={<IconClose size={16}/>} label="Abmelden" tone="coral"
              onClick={() => { setOpen(false); onSignOut(); }}/>
          </div>
        </div>
      )}
    </div>
  );
};

const MenuItem = ({ icon, label, onClick, tone }) => (
  <button onClick={onClick}
    className={cls("w-full text-left flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-semibold transition",
      tone === 'coral' ? 'text-coralDeep hover:bg-coral/10' : 'hover:bg-cream')}>
    <span className="inline-flex w-7 h-7 rounded-lg bg-cream items-center justify-center">{icon}</span>
    {label}
  </button>
);

// === Auth modal (sign-up + sign-in) ===
// Demo-only credential store: localStorage 'aw.creds' = { [email]: { password, name, bereich, colorIdx } }
const loadCreds = () => { try { return JSON.parse(localStorage.getItem('aw.creds') || '{}'); } catch { return {}; } };
const saveCreds = (c) => { try { localStorage.setItem('aw.creds', JSON.stringify(c)); } catch {} };

const AuthModal = ({ open, onClose, onSignIn }) => {
  const [mode, setMode] = React.useState('signin'); // default to login, register is step 2
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [bereich, setBereich] = React.useState('familie');
  const [colorIdx, setColorIdx] = React.useState(2);
  const [agree, setAgree] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => { if (open) { setErr(''); setPassword(''); } }, [open, mode]);
  if (!open) return null;

  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    const key = email.trim().toLowerCase();
    if (mode === 'signup') {
      if (!name.trim()) return setErr('Bitte gib deinen Namen ein.');
      if (!email.includes('@')) return setErr('Bitte gib eine gültige E-Mail ein.');
      if (password.length < 6) return setErr('Bitte wähle ein Passwort mit mind. 6 Zeichen.');
      if (!agree) return setErr('Bitte stimme den Hinweisen zu.');
      setErr(''); setBusy(true);
      const res = await awRegister({ name, email: key, password, bereich, colorIdx });
      setBusy(false);
      if (!res.ok) return setErr(res.error || 'Registrierung fehlgeschlagen.');
      onSignIn(res.profile);
    } else {
      if (!email.includes('@')) return setErr('Bitte gib eine gültige E-Mail ein.');
      if (!password) return setErr('Bitte gib dein Passwort ein.');
      setErr(''); setBusy(true);
      const res = await awLogin({ email: key, password });
      setBusy(false);
      if (!res.ok) return setErr(res.error || 'Anmeldung fehlgeschlagen.');
      onSignIn(res.profile);
    }
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-ink/50 backdrop-blur-sm" onClick={onClose}></div>
      <div className="relative w-full max-w-md bg-paper rounded-3xl ring-2 ring-line shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
        <div className="p-6 pb-3 bg-cream border-b-2 border-line flex items-start gap-3">
          <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">
            <div className="font-display text-2xl font-extrabold leading-tight">
              {mode === 'signup' ? 'Profil erstellen' : 'Willkommen zurück'}
            </div>
            <div className="text-[13px] text-inkSoft mt-1">
              {mode === 'signup'
                ? 'Speichere Sammelmappen und reiche neue Bilder ein.'
                : 'Melde dich an, um auf deine Sammelmappen zuzugreifen.'}
            </div>
          </div>
          <button onClick={onClose} className="p-2 rounded-full hover:bg-ink/5 -mt-1 -mr-1"><IconClose/></button>
        </div>

        <form onSubmit={submit} className="p-6 grid gap-4 overflow-y-auto scroll-soft">
          {mode === 'signup' && (
            <>
              <Field label="Dein Name">
                <input value={name} onChange={(e) => setName(e.target.value)}
                  placeholder="z. B. Anna Müller" autoFocus
                  className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
              </Field>
              <Field label="Wo malst du am häufigsten?" hint="Hilft uns, passende Bilder vorzuschlagen.">
                <div className="grid grid-cols-2 gap-2">
                  {BEREICH_OPTIONS.map(b => (
                    <button key={b.value} type="button" onClick={() => setBereich(b.value)}
                      className={cls("text-left px-3 py-2.5 rounded-xl ring-2 transition flex items-center gap-2",
                        bereich === b.value ? 'ring-coral bg-coral/5' : 'ring-line bg-paper hover:ring-ink/30')}>
                      <span className="text-lg" aria-hidden="true">{b.emoji}</span>
                      <span className="text-[13px] font-bold leading-tight">{b.label}</span>
                    </button>
                  ))}
                </div>
              </Field>
            </>
          )}

          <Field label="E-Mail-Adresse">
            <input value={email} onChange={(e) => setEmail(e.target.value)} type="email"
              placeholder="du@beispiel.de"
              className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
          </Field>

          <Field label="Passwort" hint={mode === 'signup' ? 'Mind. 6 Zeichen, speichere es gut.' : null}>
            <div className="relative">
              <input value={password} onChange={(e) => setPassword(e.target.value)}
                type={showPw ? 'text' : 'password'}
                placeholder={mode === 'signup' ? 'Mind. 6 Zeichen' : 'Dein Passwort'}
                autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
                className="w-full pl-4 pr-20 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
              <button type="button" onClick={() => setShowPw(s => !s)}
                className="absolute right-2 top-1/2 -translate-y-1/2 px-2.5 py-1.5 rounded-lg text-[12px] font-bold text-inkSoft hover:bg-ink/5">
                {showPw ? 'Verbergen' : 'Zeigen'}
              </button>
            </div>
          </Field>

          {mode === 'signup' && (
            <Field label="Wähle deine Avatar-Farbe">
              <div className="flex gap-2">
                {AVATAR_PALETTE.map((p, i) => (
                  <button key={i} type="button" onClick={() => setColorIdx(i)}
                    className={cls("w-11 h-11 rounded-full ring-2 transition flex items-center justify-center font-display font-extrabold",
                      colorIdx === i ? 'ring-ink scale-110' : 'ring-transparent')}
                    style={{ background: p.bg, color: p.fg }}>
                    {initials(name || 'Du')}
                  </button>
                ))}
              </div>
            </Field>
          )}

          {mode === 'signup' && (
            <label className="flex items-start gap-3 text-[13px] text-inkSoft leading-snug cursor-pointer">
              <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)}
                className="mt-0.5 w-5 h-5 rounded accent-coral"/>
              <span>Ich bin mit den Hinweisen zu Datenschutz und Nutzung einverstanden. Du kannst dein Profil jederzeit löschen.</span>
            </label>
          )}

          {err && <div className="text-[13px] text-coralDeep bg-coral/10 ring-1 ring-coral/30 rounded-xl px-3 py-2">{err}</div>}

          <Btn type="submit" size="lg" className="w-full mt-1" disabled={busy}>
            {busy ? 'Bitte warten …' : (mode === 'signup' ? 'Profil erstellen' : 'Anmelden')}
          </Btn>

          <div className="text-center text-[13px] text-inkSoft">
            {mode === 'signup' ? 'Schon einen Account?' : 'Noch kein Profil?'}
            <button type="button" onClick={() => setMode(mode === 'signup' ? 'signin' : 'signup')}
              className="ml-1.5 font-bold text-coralDeep hover:underline">
              {mode === 'signup' ? 'Anmelden' : 'Profil erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

const Field = ({ label, hint, children }) => (
  <div>
    <div className="text-[13px] font-bold mb-1.5">{label}</div>
    {children}
    {hint && <div className="text-[12px] text-inkSoft mt-1.5">{hint}</div>}
  </div>
);

// === "Choose mappe" small popover when collecting an item ===
const MappePicker = ({ open, onClose, mappen, onPick, onCreate }) => {
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[55] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-ink/40 backdrop-blur-sm" onClick={onClose}></div>
      <div className="relative w-full max-w-sm bg-paper rounded-3xl ring-2 ring-line shadow-2xl p-5">
        <div className="flex items-center justify-between mb-3">
          <div className="font-display text-xl font-extrabold">In welche Mappe?</div>
          <button onClick={onClose} className="p-1.5 rounded-full hover:bg-ink/5"><IconClose size={18}/></button>
        </div>
        <div className="grid gap-2 max-h-[50vh] overflow-y-auto scroll-soft">
          {mappen.map(m => (
            <button key={m.id} onClick={() => { onPick(m.id); onClose(); }}
              className="text-left flex items-center gap-3 px-3 py-3 rounded-2xl ring-2 ring-line hover:ring-coral hover:bg-coral/5 transition">
              <span className="text-2xl" aria-hidden="true">{m.emoji}</span>
              <div className="flex-1 min-w-0">
                <div className="font-display font-extrabold leading-tight truncate">{m.name}</div>
                <div className="text-[12px] text-inkSoft">{m.items.length} Bild{m.items.length === 1 ? '' : 'er'}</div>
              </div>
              <IconChevronR size={16} className="text-inkSoft"/>
            </button>
          ))}
          {creating ? (
            <div className="ring-2 ring-coral rounded-2xl p-3 bg-coral/5">
              <div className="text-[13px] font-bold mb-1.5">Name der neuen Mappe</div>
              <div className="flex gap-2">
                <input value={newName} onChange={(e) => setNewName(e.target.value)} autoFocus
                  placeholder="z. B. Geburtstag Lina"
                  className="flex-1 px-3 py-2 rounded-xl bg-paper ring-1 ring-line outline-none focus:ring-2 focus:ring-coral text-sm"/>
                <Btn size="sm" onClick={() => {
                  if (!newName.trim()) return;
                  onCreate(newName.trim());
                  setNewName(''); setCreating(false);
                }}>Anlegen</Btn>
              </div>
            </div>
          ) : (
            <button onClick={() => setCreating(true)}
              className="text-left flex items-center gap-3 px-3 py-3 rounded-2xl ring-2 ring-dashed ring-line hover:ring-coral hover:bg-coral/5 transition">
              <span className="inline-flex w-9 h-9 rounded-full bg-coral text-white items-center justify-center"><IconPlus size={16}/></span>
              <div className="font-bold">Neue Mappe erstellen</div>
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

// === Profile page (overview, mappen, submit, premium, settings) ===
const ProfilePage = ({ user, mappen, navigate, tab, setTab,
  createMappe, renameMappe, deleteMappe, removeFromMappe, openMappeFor, openPrintFor,
  suggestions, addSuggestion, updateUser, signOut, deleteAccount, purchasePremium }) => {
  const [settings] = useSettings();
  const isPremium = isUserPremium(user);

  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:'Mein Profil'}]} navigate={navigate}/>

      {/* Profile header */}
      <section className="mt-5 bg-paper rounded-[36px] ring-2 ring-line p-6 sm:p-8 flex flex-col sm:flex-row sm:items-center gap-6 relative overflow-hidden">
        {isPremium && (
          <span className="absolute top-4 right-4 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-sun ring-2 ring-sunDeep text-ink text-[12px] font-extrabold">
            ⭐ Premium
          </span>
        )}
        <Avatar user={user} size={88}/>
        <div className="flex-1 min-w-0">
          <div className="text-[12px] font-bold uppercase tracking-[0.12em] text-coralDeep">Hallo!</div>
          <h1 className="font-display text-3xl sm:text-4xl font-extrabold leading-tight">{user.name}</h1>
          <div className="mt-2 flex flex-wrap items-center gap-2 text-[13px]">
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-cream ring-1 ring-line font-semibold">
              {(BEREICH_OPTIONS.find(b => b.value === user.bereich) || {}).emoji}
              {(BEREICH_OPTIONS.find(b => b.value === user.bereich) || {}).label || 'Bereich'}
            </span>
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-cream ring-1 ring-line font-semibold">
              <span aria-hidden="true">🎒</span>
              {mappen.length} Sammelmappe{mappen.length === 1 ? '' : 'n'}
            </span>
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-cream ring-1 ring-line font-semibold">
              <IconSparkle size={13}/>
              {suggestions.length} Vorschläge
            </span>
          </div>
        </div>
      </section>

      {/* Tabs */}
      <div className="mt-7 mb-6 overflow-x-auto scroll-soft">
        <Tabs tabs={[
          {label:'🎒 Meine Mappen', value:'mappen'},
          {label:'🏆 Auszeichnungen', value:'badges'},
          {label:'✨ Vorschläge', value:'submit'},
          ...(settings.premium.enabled ? [{label:'⭐ Premium', value:'premium'}] : []),
          ...(settings.referral.enabled ? [{label:'🎁 Freunde einladen', value:'referral'}] : []),
          {label:'⚙ Einstellungen', value:'settings'},
        ]} value={tab === 'overview' ? 'mappen' : tab} onChange={setTab}/>
      </div>

      {(tab === 'mappen' || tab === 'overview') && (
        <ProfileMappenTab
          mappen={mappen} navigate={navigate} user={user}
          createMappe={createMappe} renameMappe={renameMappe} deleteMappe={deleteMappe}
          removeFromMappe={removeFromMappe} openMappeFor={openMappeFor} openPrintFor={openPrintFor}/>
      )}
      {tab === 'badges' && (
        <ProfileBadgesTab user={user} mappen={mappen} suggestions={suggestions}/>
      )}
      {tab === 'submit' && (
        <ProfileSubmitTab user={user} suggestions={suggestions} addSuggestion={addSuggestion}/>
      )}
      {tab === 'premium' && settings.premium.enabled && (
        <ProfilePremiumTab user={user} settings={settings} purchasePremium={purchasePremium}/>
      )}
      {tab === 'referral' && settings.referral.enabled && (
        <ProfileReferralTab user={user} settings={settings} updateUser={updateUser}/>
      )}
      {tab === 'settings' && (
        <ProfileSettingsTab user={user} updateUser={updateUser} signOut={signOut} deleteAccount={deleteAccount}/>
      )}
    </main>
  );
};

const ProfileBadgesTab = ({ user, mappen, suggestions }) => {
  const { all, earned, stats } = evaluateAchievements(user, mappen, suggestions);
  const progress = Math.round((earned.length / all.length) * 100);
  return (
    <div className="grid gap-5">
      <Card title="Dein Fortschritt">
        <div className="flex items-center gap-5 flex-wrap">
          <div className="text-center">
            <div className="relative inline-flex">
              <svg width="120" height="120" viewBox="0 0 120 120">
                <circle cx="60" cy="60" r="52" fill="none" stroke="#E7E0CE" strokeWidth="10"/>
                <circle cx="60" cy="60" r="52" fill="none" stroke="#F26A56" strokeWidth="10"
                  strokeDasharray={`${progress * 3.27} 327`} strokeLinecap="round"
                  transform="rotate(-90 60 60)"/>
              </svg>
              <span className="absolute inset-0 flex flex-col items-center justify-center">
                <span className="font-display text-3xl font-extrabold leading-none">{earned.length}</span>
                <span className="text-[11px] text-inkSoft mt-0.5">von {all.length}</span>
              </span>
            </div>
          </div>
          <div className="flex-1 min-w-[200px]">
            <div className="grid grid-cols-2 gap-3 max-w-xl">
              <StatTile label="Sammelmappen"  value={stats.mappenCount} icon="🎒"/>
              <StatTile label="Bilder gesammelt" value={stats.collectedCount} icon="🌟"/>
              <StatTile label="Druckvorgänge" value={stats.prints} icon="🖨️"/>
              <StatTile label="Downloads"     value={stats.downloads} icon="⬇️"/>
              <StatTile label="Freunde geworben" value={stats.friendsInvited} icon="🎁"/>
              <StatTile label="Kommentare"    value={stats.commentsCount} icon="💬"/>
            </div>
          </div>
        </div>
      </Card>
      <Card title={`Deine Auszeichnungen (${earned.length})`} subtitle="Erreichbare Trophäen sammelst du durch Aktivität.">
        <AchievementGrid list={all}/>
      </Card>
    </div>
  );
};

const StatTile = ({ label, value, icon }) => (
  <div className="bg-cream rounded-2xl p-3 flex items-center gap-3">
    <span className="inline-flex w-10 h-10 rounded-xl bg-paper items-center justify-center text-xl shrink-0">{icon}</span>
    <div className="min-w-0">
      <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft truncate">{label}</div>
      <div className="font-display text-xl font-extrabold leading-tight">{value}</div>
    </div>
  </div>
);

const ProfilePremiumTab = ({ user, settings, purchasePremium }) => {
  const isPremium = isUserPremium(user);
  return (
    <div className="grid gap-5">
      <PremiumCard
        premium={settings.premium}
        currentPlan={isPremium ? 'active' : 'free'}
        onPurchase={purchasePremium}/>
      {isPremium && user.premium && (
        <Card title="Dein aktueller Plan">
          <div className="grid sm:grid-cols-3 gap-3">
            <div className="rounded-2xl bg-cream p-4">
              <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-1">Plan</div>
              <div className="font-display text-lg font-extrabold">⭐ {settings.premium.name}</div>
            </div>
            <div className="rounded-2xl bg-cream p-4">
              <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-1">Abrechnung</div>
              <div className="font-display text-lg font-extrabold">{
                ({ monthly: 'Monatlich (Abo)', yearly: 'Jährlich (Abo)', once: '1 Monat (Einmalkauf)', bonus: 'Bonus', admin: 'Freigeschaltet' })[user.premium.cycle] || user.premium.cycle
              }</div>
            </div>
            <div className="rounded-2xl bg-cream p-4">
              <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-1">
                {user.premium.cycle === 'once' ? 'Läuft ab am' : user.premium.expiresAt ? 'Nächste Verlängerung' : 'Mitglied seit'}
              </div>
              <div className="font-display text-lg font-extrabold">
                {user.premium.expiresAt
                  ? new Date(user.premium.expiresAt).toLocaleDateString('de-DE')
                  : (user.premium.since ? new Date(user.premium.since).toLocaleDateString('de-DE') : '-')}
              </div>
            </div>
          </div>
          {user.premium.cycle === 'once' && (
            <div className="mt-4 p-3 rounded-xl bg-sun/30 ring-1 ring-sun text-[13px] leading-relaxed">
              <strong>Einmalkauf:</strong> Dein Premium endet am {user.premium.expiresAt ? new Date(user.premium.expiresAt).toLocaleDateString('de-DE') : '-'} und verlängert sich nicht automatisch. Du kannst danach jederzeit erneut Premium kaufen.
            </div>
          )}
          <div className="mt-4 p-3 rounded-xl bg-sky/30 text-[13px]">
            <strong>Demo:</strong> Es wurde keine echte Zahlung durchgeführt. In Produktion würde hier ein Zahlungsanbieter (Stripe, PayPal, Apple Pay) eingebunden.
          </div>
        </Card>
      )}
    </div>
  );
};

const REFERRAL_THEMES = [
  { id: 'friend', emoji: '🤗', title: 'Freund:innen einladen',
    subject: 'Schau dir Malfino.de an!',
    pitch: (days) => `Hi! Ich nutze Malfino.de für kostenlose Malvorlagen, du auch? Mit meinem Code bekommst du ${days} Tage Premium gratis.` },
  { id: 'parent', emoji: '👨‍👩‍👧', title: 'Eltern einladen',
    subject: 'Tipp für kreative Pausen mit den Kindern',
    pitch: (days) => `Hi! Falls ihr nach kostenlosen Malvorlagen für die Kinder sucht, Malfino.de hat über 1.500 Bilder zum Ausdrucken. Mit meinem Code gibt's ${days} Tage Premium gratis.` },
  { id: 'kita', emoji: '🧸', title: 'Kita / Erzieher:innen',
    subject: 'Malvorlagen-Tipp für die Kita',
    pitch: (days) => `Hallo! Ich nutze Malfino.de für meine Gruppe, viele kostenlose Vorlagen + Sammelmappen für Themenwochen. Mit meinem Code gibt's ${days} Tage Premium gratis.` },
  { id: 'school', emoji: '🎒', title: 'Schule / Lehrer:innen',
    subject: 'Vorlagen für den Unterricht',
    pitch: (days) => `Hallo Kolleg:in! Malfino.de ist eine schöne Quelle für Mal- und Mandala-Vorlagen, perfekt für Vertretungen oder Klassenfeste. Mit meinem Code bekommst du ${days} Tage Premium gratis.` },
  { id: 'hort', emoji: '🏡', title: 'Hort / Tagespflege',
    subject: 'Malvorlagen-Sammlung für den Hort',
    pitch: (days) => `Hi! Falls ihr im Hort regelmäßig malt, Malfino.de hat viele kindgerechte Vorlagen. ${days} Tage Premium gratis mit meinem Code.` },
  { id: 'family', emoji: '👨‍👩‍👧‍👦', title: 'Familie',
    subject: 'Malvorlagen für die ganze Familie',
    pitch: (days) => `Hi! Schau mal, Malfino.de: Malvorlagen für Klein und Groß, mit Sammelmappen für jedes Familienmitglied. Mit meinem Code ${days} Tage Premium gratis.` },
];

const ProfileReferralTab = ({ user, settings, updateUser }) => {
  const [code, setCode] = React.useState('');
  const [msg, setMsg] = React.useState({ kind: '', text: '' });
  const [copied, setCopied] = React.useState(false);
  const [themeId, setThemeId] = React.useState('friend');
  const myCode = React.useMemo(() => getOrCreateReferralCode(user), [user]);
  const myLink = referralLink(myCode);
  const store = loadReferralStore();
  const myEntry = store[myCode] || { redeemed: [] };
  const r = settings.referral;
  const maxReached = r.maxRewardsPerUser && myEntry.redeemed.length >= r.maxRewardsPerUser;
  const earnedDays = myEntry.redeemed.length * (r.rewardDays || 30);
  const remaining = r.maxRewardsPerUser - myEntry.redeemed.length;
  const theme = REFERRAL_THEMES.find(t => t.id === themeId) || REFERRAL_THEMES[0];
  const message = `${theme.pitch(r.rewardDays || 30)}\n\nCode: ${myCode}\nLink: ${myLink}`;

  const copyLink = async () => {
    try { await navigator.clipboard.writeText(myLink); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    catch { alert('Bitte den Link manuell kopieren.'); }
  };
  const copyMessage = async () => {
    try { await navigator.clipboard.writeText(message); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    catch { alert('Bitte die Nachricht manuell kopieren.'); }
  };
  const share = async () => {
    if (navigator.share) {
      try { await navigator.share({ title: theme.subject, text: message, url: myLink }); } catch {}
    } else copyMessage();
  };
  const mailto = () => {
    window.open(`mailto:?subject=${encodeURIComponent(theme.subject)}&body=${encodeURIComponent(message)}`);
  };
  const whatsapp = () => {
    window.open(`https://wa.me/?text=${encodeURIComponent(message)}`);
  };

  const redeem = (e) => {
    e.preventDefault();
    setMsg({ kind: '', text: '' });
    const trimmed = (code || '').trim().toUpperCase();
    if (!trimmed) return setMsg({ kind: 'err', text: 'Bitte einen Code eingeben.' });
    const result = redeemReferralCode(trimmed, user.email, settings);
    if (!result.ok) return setMsg({ kind: 'err', text: result.message });
    if (r.rewardForBoth) {
      const now = Date.now();
      const cur = user.premium && user.premium.expiresAt ? new Date(user.premium.expiresAt).getTime() : now;
      const base = Math.max(cur, now);
      updateUser({
        ...user,
        referredBy: trimmed,
        premium: { active: true, cycle: 'bonus', since: user.premium?.since || new Date().toISOString(),
          expiresAt: new Date(base + (r.rewardDays || 30) * 86400e3).toISOString(), source: 'referral' },
      });
    } else { updateUser({ ...user, referredBy: trimmed }); }
    setMsg({ kind: 'ok', text: result.message });
    setCode('');
  };

  return (
    <div className="grid gap-5">
      {/* Theme selector */}
      <Card title="Wen möchtest du einladen?" subtitle="Wähle ein Thema, die Nachricht passt sich an.">
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
          {REFERRAL_THEMES.map(t => (
            <button key={t.id} type="button" onClick={() => setThemeId(t.id)}
              className={cls("text-center p-3 rounded-2xl ring-2 transition flex flex-col items-center gap-1.5",
                themeId === t.id ? 'ring-coral bg-coral/5 -translate-y-0.5 shadow-card' : 'ring-line bg-paper hover:ring-ink/30')}>
              <span className="text-3xl" aria-hidden="true">{t.emoji}</span>
              <span className="text-[12px] font-extrabold leading-tight">{t.title}</span>
            </button>
          ))}
        </div>
      </Card>

      <div className="grid lg:grid-cols-5 gap-5">
        {/* Hero invite card */}
        <div className="lg:col-span-3 rounded-3xl bg-gradient-to-br from-sun/50 via-paper to-coral/20 ring-2 ring-sun p-6 sm:p-8 relative overflow-hidden">
          <span className="absolute top-3 right-4 text-5xl twinkle">{theme.emoji}</span>
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-ink text-white text-[11px] font-extrabold tracking-wide mb-3">
            🎁 {theme.title}
          </div>
          <h3 className="font-display text-3xl sm:text-4xl font-extrabold leading-tight mb-2" style={{textWrap:'balance'}}>
            {r.rewardDays} Tage Premium gratis!
          </h3>
          <p className="text-inkSoft mb-4 max-w-md">
            {r.rewardForBoth
              ? `Du und dein:e Eingeladene:r bekommen je ${r.rewardDays} Tage „${settings.premium.name}" geschenkt.`
              : `Du bekommst ${r.rewardDays} Tage „${settings.premium.name}" geschenkt.`}
          </p>

          <div className="bg-paper rounded-2xl ring-2 ring-line p-4 mb-4">
            <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-1">Dein Einladungscode</div>
            <div className="font-display text-3xl font-extrabold tracking-wider mb-2">{myCode}</div>
            <div className="text-[12px] text-inkSoft break-all font-mono">{myLink}</div>
          </div>

          {/* Pre-written message preview */}
          <div className="bg-paper rounded-2xl ring-1 ring-line p-4 mb-4">
            <div className="text-[11px] uppercase tracking-wider font-bold text-inkSoft mb-2">Vorgeschlagene Nachricht</div>
            <p className="text-[13px] leading-relaxed whitespace-pre-line">{message}</p>
          </div>

          <div className="flex flex-wrap gap-2">
            <Btn size="md" onClick={share} leading={<span aria-hidden="true">📨</span>}>
              {copied ? 'Kopiert ✓' : 'Teilen'}
            </Btn>
            <Btn size="md" variant="soft" onClick={copyLink} leading={<span aria-hidden="true">🔗</span>}>Link kopieren</Btn>
            <Btn size="md" variant="soft" onClick={copyMessage} leading={<span aria-hidden="true">📋</span>}>Nachricht</Btn>
            <Btn size="md" variant="soft" onClick={mailto}>✉ E-Mail</Btn>
            <Btn size="md" variant="soft" onClick={whatsapp}>💬 WhatsApp</Btn>
          </div>

          {maxReached && (
            <div className="mt-4 p-3 rounded-xl bg-coral/10 ring-1 ring-coral/30 text-[12px]">
              Du hast das Maximum von {r.maxRewardsPerUser} Werbe-Boni erreicht. Danke fürs Weitersagen!
            </div>
          )}
        </div>

        <div className="lg:col-span-2 grid gap-4 content-start">
          <Card title="Deine Erfolge">
            <div className="grid grid-cols-3 gap-3">
              <div className="rounded-2xl bg-cream p-3 text-center">
                <div className="font-display text-3xl font-extrabold leading-none">{myEntry.redeemed.length}</div>
                <div className="text-[11px] text-inkSoft mt-1 leading-tight">Eingeladene<br/>Personen</div>
              </div>
              <div className="rounded-2xl bg-cream p-3 text-center">
                <div className="font-display text-3xl font-extrabold leading-none">{earnedDays}</div>
                <div className="text-[11px] text-inkSoft mt-1 leading-tight">Tage Premium<br/>verdient</div>
              </div>
              <div className="rounded-2xl bg-cream p-3 text-center">
                <div className="font-display text-3xl font-extrabold leading-none">{Math.max(0, remaining)}</div>
                <div className="text-[11px] text-inkSoft mt-1 leading-tight">Boni<br/>übrig</div>
              </div>
            </div>
          </Card>

          <Card title="Hast du einen Code?" subtitle="Code einlösen und Premium-Tage erhalten.">
            <form onSubmit={redeem} className="grid gap-3">
              <input value={code} onChange={(e) => setCode(e.target.value.toUpperCase())}
                placeholder="z. B. ANN-X7K2"
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none font-mono uppercase tracking-wider"/>
              <Btn type="submit" size="md" leading={<span aria-hidden="true">🎁</span>}>Code einlösen</Btn>
              {msg.text && (
                <div className={cls("text-[13px] rounded-xl px-3 py-2 ring-1",
                  msg.kind === 'ok' ? 'bg-mint/40 ring-mint text-emerald-900' : 'bg-coral/10 ring-coral/30 text-coralDeep')}>
                  {msg.text}
                </div>
              )}
            </form>
          </Card>

          {myEntry.redeemed.length > 0 && (
            <Card title="Geworbene Freunde">
              <div className="grid gap-2">
                {myEntry.redeemed.map((r, i) => (
                  <div key={i} className="flex items-center justify-between bg-cream rounded-xl px-3 py-2 text-[13px]">
                    <span className="font-mono text-inkSoft truncate">{r.email}</span>
                    <span className="text-[11px] text-inkSoft shrink-0 ml-2">{new Date(r.at).toLocaleDateString('de-DE')}</span>
                  </div>
                ))}
              </div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
};

const ProfileMappenTab = ({ mappen, navigate, user, createMappe, renameMappe, deleteMappe,
  removeFromMappe, openMappeFor, openPrintFor }) => {
  const [editingId, setEditingId] = React.useState(null);
  const [draft, setDraft] = React.useState('');
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  const [settings] = useSettings();

  const premium = isUserPremium(user);
  const multiIsPremium = settings.premium.enabled && settings.premium.features.multiMappen;
  const freeLimit = settings.limits.freeMappenLimit || 0;
  const canCreateMore = premium
    ? true
    : (multiIsPremium ? mappen.length < 1
                      : (freeLimit === 0 || mappen.length < freeLimit));

  return (
    <div className="grid gap-5">
      {/* New mappe card */}
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
        {mappen.map(m => (
          <div key={m.id} className="bg-paper rounded-3xl ring-2 ring-line overflow-hidden hover:ring-ink/20 hover:shadow-card transition">
            <div className="paper-bg p-4 aspect-[4/3] relative">
              <div className="absolute inset-3 rounded-2xl border-2 border-dashed border-line/80"></div>
              <div className="relative h-full grid grid-cols-2 grid-rows-2 gap-2">
                {[0,1,2,3].map(i => {
                  const it = m.items[i];
                  return (
                    <div key={i} className="bg-paper rounded-xl ring-1 ring-line flex items-center justify-center">
                      {it ? <ColoringArt artKey={it.art} className="w-[70%] h-[70%]"/>
                          : <span className="text-2xl opacity-30" aria-hidden="true">{m.emoji}</span>}
                    </div>
                  );
                })}
              </div>
              <span className="absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-paper ring-1 ring-line text-[11px] font-bold">
                {m.items.length} Bild{m.items.length === 1 ? '' : 'er'}
              </span>
            </div>
            <div className="p-4">
              <div className="flex items-center gap-2 mb-1">
                <span className="text-xl" aria-hidden="true">{m.emoji}</span>
                {editingId === m.id ? (
                  <input value={draft} onChange={(e) => setDraft(e.target.value)} autoFocus
                    onBlur={() => { if (draft.trim()) renameMappe(m.id, draft.trim()); setEditingId(null); }}
                    onKeyDown={(e) => { if (e.key === 'Enter') { if (draft.trim()) renameMappe(m.id, draft.trim()); setEditingId(null); }}}
                    className="flex-1 px-2 py-1 rounded-lg bg-cream ring-1 ring-line text-[15px] font-display font-extrabold outline-none focus:ring-coral"/>
                ) : (
                  <div className="font-display text-[18px] font-extrabold leading-tight flex-1 truncate">{m.name}</div>
                )}
                <button onClick={() => { setEditingId(m.id); setDraft(m.name); }}
                  className="p-1.5 rounded-lg hover:bg-ink/5 text-inkSoft"><IconEdit size={14}/></button>
              </div>
              <div className="mt-3 flex flex-wrap gap-2">
                <Btn size="sm" leading={<IconEye size={14}/>} onClick={() => openMappeFor(m.id)}>Öffnen</Btn>
                <Btn size="sm" variant="secondary" leading={<IconPrinter size={14}/>}
                  onClick={() => openPrintFor(m.id)}
                  disabled={m.items.length === 0}
                  className={m.items.length === 0 ? 'opacity-40 cursor-not-allowed' : ''}>
                  Drucken
                </Btn>
                <Btn size="sm" variant="ghost" leading={<IconTrash size={14}/>}
                  onClick={() => { if (confirm(`Mappe „${m.name}" wirklich löschen?`)) deleteMappe(m.id); }}
                  className="text-coralDeep hover:bg-coral/10 ml-auto">Löschen</Btn>
              </div>
            </div>
          </div>
        ))}

        {/* Create new mappe (or premium upsell if blocked) */}
        {!canCreateMore ? (
          <button onClick={() => navigate({ view: 'profile', tab: 'premium' })}
            className="bg-gradient-to-br from-sun/60 to-coral/20 rounded-3xl ring-2 ring-sun p-8 hover:ring-sunDeep transition flex flex-col items-center justify-center text-center min-h-[260px] relative overflow-hidden">
            <span className="absolute top-3 right-3 text-2xl twinkle">⭐</span>
            <span className="inline-flex w-14 h-14 rounded-2xl bg-ink text-white items-center justify-center text-2xl mb-3">⭐</span>
            <div className="font-display text-lg font-extrabold">Mehr Mappen mit Premium</div>
            <div className="text-sm text-inkSoft mt-1 max-w-[24ch]">Free-Plan erlaubt {multiIsPremium ? 1 : freeLimit} Mappe{(multiIsPremium ? 1 : freeLimit) === 1 ? '' : 'n'}. Werde Premium für unbegrenzt viele!</div>
          </button>
        ) : creating ? (
          <div className="bg-coral/5 rounded-3xl ring-2 ring-coral p-5 flex flex-col gap-3">
            <div className="font-display text-lg font-extrabold">Neue Mappe</div>
            <input value={newName} onChange={(e) => setNewName(e.target.value)} autoFocus
              placeholder="z. B. Sommerferien 2026"
              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="flex gap-2">
              <Btn size="md" onClick={() => {
                if (!newName.trim()) return;
                createMappe(newName.trim());
                setNewName(''); setCreating(false);
              }}>Anlegen</Btn>
              <Btn size="md" variant="ghost" onClick={() => { setCreating(false); setNewName(''); }}>Abbrechen</Btn>
            </div>
          </div>
        ) : (
          <button onClick={() => setCreating(true)}
            className="bg-paper rounded-3xl ring-2 ring-dashed ring-line p-8 hover:ring-coral hover:bg-coral/5 transition flex flex-col items-center justify-center text-center min-h-[260px]">
            <span className="inline-flex w-14 h-14 rounded-2xl bg-coral text-white items-center justify-center text-2xl shadow-pop mb-3">
              <IconPlus size={26}/>
            </span>
            <div className="font-display text-lg font-extrabold">Neue Sammelmappe</div>
            <div className="text-sm text-inkSoft mt-1">Z. B. für Schulklasse, Geburtstag oder ein Thema</div>
          </button>
        )}
      </div>
    </div>
  );
};

const ProfileSubmitTab = ({ user, suggestions, addSuggestion }) => {
  const [kind, setKind] = React.useState('bild'); // 'bild' | 'kategorie'
  const [title, setTitle] = React.useState('');
  const [category, setCategory] = React.useState('tiere');
  const [description, setDescription] = React.useState('');
  const [reason, setReason] = React.useState('');
  const [sent, setSent] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (!title.trim()) return;
    addSuggestion({
      id: Date.now(),
      kind, title: title.trim(), category, description: description.trim(),
      reason: reason.trim(),
      status: 'in Prüfung',
      submittedAt: new Date().toISOString(),
    });
    setTitle(''); setDescription(''); setReason('');
    setSent(true);
    setTimeout(() => setSent(false), 3500);
  };

  return (
    <div className="grid lg:grid-cols-5 gap-6">
      <form onSubmit={submit} className="lg:col-span-3 bg-paper rounded-[28px] ring-2 ring-line p-6 grid gap-4">
        <div>
          <div className="font-display text-2xl font-extrabold leading-tight">Vorschlag einreichen</div>
          <p className="text-[13px] text-inkSoft mt-1.5">Welches Bild oder welche Kategorie wünschst du dir? Wir prüfen jede Einreichung.</p>
        </div>

        <Field label="Was möchtest du vorschlagen?">
          <div className="grid grid-cols-2 gap-2">
            {[
              {v:'bild',       l:'Neues Ausmalbild', emoji:'🖼️'},
              {v:'kategorie',  l:'Neue Kategorie',   emoji:'🏷️'},
            ].map(o => (
              <button key={o.v} type="button" onClick={() => setKind(o.v)}
                className={cls("text-left px-4 py-3 rounded-2xl ring-2 transition flex items-center gap-2.5",
                  kind === o.v ? 'ring-coral bg-coral/5' : 'ring-line hover:ring-ink/30')}>
                <span className="text-2xl" aria-hidden="true">{o.emoji}</span>
                <span className="font-bold text-sm">{o.l}</span>
              </button>
            ))}
          </div>
        </Field>

        <Field label={kind === 'bild' ? 'Titel deines Vorschlags' : 'Name der Kategorie'}>
          <input value={title} onChange={(e) => setTitle(e.target.value)}
            placeholder={kind === 'bild' ? 'z. B. Drache mit Schatzkiste' : 'z. B. Unter Wasser'}
            className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
        </Field>

        {kind === 'bild' && (
          <Field label="In welche Kategorie passt es?">
            <select value={category} onChange={(e) => setCategory(e.target.value)}
              className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none">
              {CATEGORIES.map(c => <option key={c.slug} value={c.slug}>{c.name}</option>)}
            </select>
          </Field>
        )}

        <Field label="Beschreibung" hint="Was soll auf dem Bild zu sehen sein? Welche Stimmung?">
          <textarea value={description} onChange={(e) => setDescription(e.target.value)}
            rows={3} placeholder={kind === 'bild' ? 'z. B. Ein freundlicher Drache, der auf einer Schatzkiste sitzt …' : 'z. B. Meerestiere, U-Boote, Korallenriffe …'}
            className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
        </Field>

        <Field label="Warum wäre das super?">
          <textarea value={reason} onChange={(e) => setReason(e.target.value)}
            rows={2} placeholder="z. B. Meine Kita-Gruppe liebt Drachen!"
            className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
        </Field>

        <div className="flex items-center gap-3">
          <Btn type="submit" size="lg" leading={<IconSparkle size={18}/>}>Vorschlag senden</Btn>
          {sent && (
            <span className="inline-flex items-center gap-1.5 text-emerald-700 font-bold text-sm">
              <IconCheck size={16}/> Danke! Dein Vorschlag ist eingegangen.
            </span>
          )}
        </div>
      </form>

      <div className="lg:col-span-2 grid gap-3">
        <div className="bg-paper rounded-[28px] ring-2 ring-line p-5">
          <div className="font-display text-lg font-extrabold mb-3">Deine Einreichungen</div>
          {suggestions.length === 0 ? (
            <div className="text-center py-6">
              <div className="text-4xl mb-2">📝</div>
              <div className="text-sm text-inkSoft">Noch keine Vorschläge.</div>
            </div>
          ) : (
            <div className="grid gap-2">
              {suggestions.map(s => {
                const cat = findCategory(s.category);
                return (
                  <div key={s.id} className="rounded-2xl bg-cream ring-1 ring-line p-3">
                    <div className="flex items-center gap-2">
                      <span className="text-lg" aria-hidden="true">{s.kind === 'bild' ? '🖼️' : '🏷️'}</span>
                      <div className="font-bold text-sm flex-1 truncate">{s.title}</div>
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-sun/40 text-amber-900 text-[11px] font-bold">
                        {s.status}
                      </span>
                    </div>
                    {s.kind === 'bild' && cat && (
                      <div className="text-[12px] text-inkSoft mt-1">Kategorie: {cat.name}</div>
                    )}
                    {s.description && <div className="text-[12px] text-inkSoft mt-1 line-clamp-2">{s.description}</div>}
                  </div>
                );
              })}
            </div>
          )}
        </div>
        <div className="bg-sky/30 rounded-[28px] ring-1 ring-sky p-5">
          <div className="font-display text-lg font-extrabold mb-1.5">Tipp 💡</div>
          <p className="text-sm leading-relaxed text-inkSoft">
            Beliebte Vorschläge bauen wir zuerst. Mehrfach eingereichte Themen rutschen schneller nach oben.
          </p>
        </div>
      </div>
    </div>
  );
};

const ProfileSettingsTab = ({ user, updateUser, signOut, deleteAccount }) => {
  const [name, setName] = React.useState(user.name);
  const [email, setEmail] = React.useState(user.email);
  const [bereich, setBereich] = React.useState(user.bereich);
  const [colorIdx, setColorIdx] = React.useState(user.colorIdx ?? 0);
  // Extended bio fields
  const [bio, setBio] = React.useState(user.bio || '');
  const [plz, setPlz] = React.useState(user.plz || '');
  const [city, setCity] = React.useState(user.city || '');
  const [plzStatus, setPlzStatus] = React.useState(''); // '', 'loading', 'ok', 'err'
  const [gender, setGender] = React.useState(user.gender || 'keine');
  const [age, setAge] = React.useState(user.age || '');
  const [childCount, setChildCount] = React.useState(user.childCount || '');
  const [favorite, setFavorite] = React.useState(user.favorite || '');
  const [website, setWebsite] = React.useState(user.website || '');
  const [showInProfile, setShowInProfile] = React.useState(user.showInProfile !== false);

  // Auto-detect Ort from PLZ via zippopotam (free, no key). Debounced.
  React.useEffect(() => {
    if (!/^\d{5}$/.test(plz)) { setPlzStatus(''); return; }
    let cancelled = false;
    setPlzStatus('loading');
    const t = setTimeout(async () => {
      try {
        const res = await fetch(`https://api.zippopotam.us/de/${plz}`);
        if (cancelled) return;
        if (!res.ok) { setPlzStatus('err'); return; }
        const data = await res.json();
        const place = (data.places && data.places[0]) ? data.places[0]['place name'] : '';
        if (place) {
          setCity(place);
          setPlzStatus('ok');
        } else setPlzStatus('err');
      } catch {
        if (!cancelled) setPlzStatus('err');
      }
    }, 350);
    return () => { cancelled = true; clearTimeout(t); };
  }, [plz]);

  const [saved, setSaved] = React.useState(false);
  const [confirmDelete, setConfirmDelete] = React.useState(false);
  const [deletePw, setDeletePw] = React.useState('');
  const [deleteErr, setDeleteErr] = React.useState('');

  const save = (e) => {
    e.preventDefault();
    updateUser({
      ...user,
      name: name.trim() || user.name, email, bereich, colorIdx,
      bio: bio.trim(), plz: plz.trim(), city: city.trim(),
      gender, age: age, childCount,
      favorite: favorite.trim(), website: website.trim(),
      showInProfile,
    });
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const performDelete = () => {
    setDeleteErr('');
    // verify password
    try {
      const creds = JSON.parse(localStorage.getItem('aw.creds') || '{}');
      const stored = creds[(user.email || '').toLowerCase()];
      if (!stored) {
        setDeleteErr('Profil nicht gefunden.');
        return;
      }
      if (stored.password !== deletePw) {
        setDeleteErr('Passwort stimmt nicht.');
        return;
      }
    } catch {
      setDeleteErr('Fehler beim Lesen des Profils.');
      return;
    }
    deleteAccount();
  };

  return (
    <form onSubmit={save} className="grid lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2 grid gap-5">
        <Card title="Allgemeine Daten">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Name">
              <input value={name} onChange={(e) => setName(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
            </Field>
            <Field label="E-Mail">
              <input value={email} onChange={(e) => setEmail(e.target.value)} type="email"
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
            </Field>
            <div className="sm:col-span-2">
              <Field label="Bereich">
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                  {BEREICH_OPTIONS.map(b => (
                    <button key={b.value} type="button" onClick={() => setBereich(b.value)}
                      className={cls("text-left px-3 py-2.5 rounded-xl ring-2 transition flex items-center gap-2",
                        bereich === b.value ? 'ring-coral bg-coral/5' : 'ring-line bg-paper hover:ring-ink/30')}>
                      <span className="text-lg" aria-hidden="true">{b.emoji}</span>
                      <span className="text-[13px] font-bold leading-tight">{b.label}</span>
                    </button>
                  ))}
                </div>
              </Field>
            </div>
            <Field label="Avatar-Farbe">
              <div className="flex gap-2">
                {AVATAR_PALETTE.map((p, i) => (
                  <button key={i} type="button" onClick={() => setColorIdx(i)}
                    className={cls("w-11 h-11 rounded-full ring-2 transition flex items-center justify-center font-display font-extrabold",
                      colorIdx === i ? 'ring-ink scale-110' : 'ring-transparent')}
                    style={{ background: p.bg, color: p.fg }}>
                    {initials(name || 'Du')}
                  </button>
                ))}
              </div>
            </Field>
          </div>
        </Card>

        <Card title="Über dich" subtitle="Freiwillige Angaben, helfen uns, passende Bilder vorzuschlagen.">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Postleitzahl" hint={
              plzStatus === 'loading' ? '… Ort wird geladen' :
              plzStatus === 'ok'      ? '✓ Ort automatisch erkannt' :
              plzStatus === 'err'     ? 'PLZ unbekannt, Ort manuell eintragen' :
              '5-stellige deutsche PLZ, Ort wird automatisch ergänzt'
            }>
              <input value={plz} onChange={(e) => setPlz(e.target.value.replace(/\D/g, '').slice(0, 5))}
                placeholder="z. B. 20095" inputMode="numeric"
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
            </Field>
            <Field label="Ort">
              <input value={city} onChange={(e) => setCity(e.target.value)} placeholder="wird automatisch ergänzt"
                className={cls("w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 outline-none transition",
                  plzStatus === 'ok' ? 'ring-emerald-400' : 'focus:ring-coral')}/>
            </Field>
            <div className="sm:col-span-2">
              <Field label="Geschlecht">
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {[
                    {v:'weiblich',  l:'Weiblich',     e:'👩'},
                    {v:'maennlich', l:'Männlich',     e:'👨'},
                    {v:'divers',    l:'Divers',       e:'🌈'},
                    {v:'keine',     l:'Keine Angabe', e:'-'},
                  ].map(o => (
                    <button key={o.v} type="button" onClick={() => setGender(o.v)}
                      className={cls("text-left px-3 py-2.5 rounded-xl ring-2 transition flex items-center gap-2",
                        gender === o.v ? 'ring-coral bg-coral/5' : 'ring-line bg-paper hover:ring-ink/30')}>
                      <span className="text-lg" aria-hidden="true">{o.e}</span>
                      <span className="text-[13px] font-bold leading-tight">{o.l}</span>
                    </button>
                  ))}
                </div>
              </Field>
            </div>
            <Field label="Alter">
              <select value={age} onChange={(e) => setAge(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none">
                <option value="">Keine Angabe</option>
                <option value="unter-18">Unter 18</option>
                <option value="18-29">18–29</option>
                <option value="30-39">30–39</option>
                <option value="40-49">40–49</option>
                <option value="50-plus">50+</option>
              </select>
            </Field>
            <Field label="Anzahl Kinder (optional)">
              <select value={childCount} onChange={(e) => setChildCount(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none">
                <option value="">Keine Angabe</option>
                <option value="0">Keine</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4+">4 oder mehr</option>
              </select>
            </Field>
            <Field label="Lieblingsmotiv">
              <input value={favorite} onChange={(e) => setFavorite(e.target.value)} placeholder="z. B. Einhörner"
                className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
            </Field>
            <div className="sm:col-span-2">
              <Field label="Website / Blog (optional)">
                <input value={website} onChange={(e) => setWebsite(e.target.value)} placeholder="https://…"
                  className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
              </Field>
            </div>
            <div className="sm:col-span-2">
              <Field label="Über mich" hint={`${bio.length}/300 Zeichen`}>
                <textarea value={bio} onChange={(e) => setBio(e.target.value.slice(0, 300))} rows="3"
                  placeholder="Erzähle ein wenig über dich oder deine Gruppe."
                  className="w-full px-4 py-3 rounded-xl bg-cream ring-1 ring-line focus:ring-2 focus:ring-coral outline-none resize-none"/>
              </Field>
            </div>
            <div className="sm:col-span-2">
              <label className="flex items-start gap-3 text-[13px] cursor-pointer">
                <input type="checkbox" checked={showInProfile} onChange={(e) => setShowInProfile(e.target.checked)}
                  className="mt-0.5 w-5 h-5 rounded accent-coral"/>
                <span className="text-inkSoft">Diese Angaben dürfen anonymisiert für statistische Auswertungen genutzt werden.</span>
              </label>
            </div>
          </div>
        </Card>

        <div className="flex items-center gap-3">
          <Btn type="submit" size="lg" leading={<IconCheck size={18}/>}>Speichern</Btn>
          {saved && <span className="text-emerald-700 font-bold text-sm">Gespeichert ✓</span>}
        </div>
      </div>

      <div className="grid gap-3 content-start">
        <div className="bg-paper rounded-[28px] ring-2 ring-line p-5">
          <div className="font-display text-lg font-extrabold mb-2">Konto</div>
          <div className="text-[13px] text-inkSoft mb-4">
            Erstellt am {new Date(user.joined).toLocaleDateString('de-DE', {year:'numeric',month:'long',day:'numeric'})}
          </div>
          <Btn type="button" variant="soft" leading={<IconClose size={16}/>}
            onClick={signOut}
            className="w-full justify-center">
            Abmelden
          </Btn>
        </div>

        {/* Danger zone */}
        <div className="bg-coral/5 rounded-[28px] ring-2 ring-coral/30 p-5">
          <div className="font-display text-lg font-extrabold mb-2 text-coralDeep">Profil löschen</div>
          <p className="text-[13px] text-inkSoft mb-4 leading-relaxed">
            Dein Profil und alle deine Sammelmappen werden unwiderruflich gelöscht.
          </p>
          {!confirmDelete ? (
            <Btn type="button" variant="ghost" leading={<IconTrash size={16}/>}
              onClick={() => setConfirmDelete(true)}
              className="text-coralDeep hover:bg-coral/10 w-full justify-center">
              Profil dauerhaft löschen
            </Btn>
          ) : (
            <div className="grid gap-3">
              <Field label="Bitte zur Bestätigung dein Passwort eingeben">
                <input type="password" value={deletePw} onChange={(e) => setDeletePw(e.target.value)} autoFocus
                  className="w-full px-4 py-3 rounded-xl bg-paper ring-1 ring-line focus:ring-2 focus:ring-coral outline-none"/>
              </Field>
              {deleteErr && <div className="text-[12px] text-coralDeep bg-coral/10 ring-1 ring-coral/30 rounded-xl px-3 py-2">{deleteErr}</div>}
              <div className="flex gap-2">
                <Btn type="button" size="md" onClick={performDelete}
                  className="!bg-coralDeep !text-white" leading={<IconTrash size={16}/>}>
                  Endgültig löschen
                </Btn>
                <Btn type="button" variant="ghost" size="md"
                  onClick={() => { setConfirmDelete(false); setDeletePw(''); setDeleteErr(''); }}>
                  Abbrechen
                </Btn>
              </div>
            </div>
          )}
        </div>
      </div>
    </form>
  );
};

Object.assign(window, {
  Avatar, ProfilePill, AuthModal, MappePicker, ProfilePage,
});
