// beta.jsx — Beta-spezifische UI: Welcome-Modal + Feedback-Tab.
// Wird nur auf *.beta.haikara.it angezeigt (HK_ENV === 'beta').

// Apps mit Platzhalter-Namen, für die Tester Vorschläge abgeben können.
// Keys müssen mit ALLOWED_APP_KEYS in server/feedback.js übereinstimmen.
// Haikara (Plattform-Brand) bleibt fest und steht hier bewusst NICHT drin.
const BETA_NAME_APPS = [
  { key: 'hub',     current: 'Hub',     desc: 'Zentrale App-Übersicht' },
  { key: 'heronry', current: 'Heronry', desc: 'Wissens-Hub (Notizen, Karten, Termine)' },
  { key: 'egret',   current: 'Egret',   desc: 'Subnet-Rechner' },
  { key: 'plumage', current: 'Plumage', desc: 'Cheatsheets' },
];

const BETA_FEATURES = [
  { key: 'notes',       label: 'Notizen',           desc: 'Markdown-Editor, Tags, Verbindungen, Pinned' },
  { key: 'deadlines',   label: 'Termine & Kalender', desc: 'Termin-Liste, Monatskalender, ICS-Export' },
  { key: 'flashcards',  label: 'Lernkarten',        desc: 'Anlegen, lernen, durchblättern' },
  { key: 'chat',        label: 'Section-Chat',      desc: 'Live-Chat pro Lernfeld mit Mentions' },
  { key: 'dms',         label: 'Direktnachrichten', desc: '1:1 Chat zwischen Usern' },
  { key: 'search',      label: 'Suche',             desc: 'Global über Notizen + Termine + Karten' },
  { key: 'graph',       label: 'Graph / Mindmap',   desc: 'Note-Verbindungen visuell' },
  { key: 'twofa',       label: '2FA',               desc: 'TOTP, Telegram, E-Mail-OTP' },
  { key: 'avatars',     label: 'Avatare',           desc: 'Upload, Cropper, Cross-App-Anzeige' },
  { key: 'hub',         label: 'Hub & App-Wechsler', desc: 'Übersicht, Bookmarks, Wetter' },
  { key: 'egret',       label: 'Egret',             desc: 'Subnet-Rechner' },
  { key: 'plumage',     label: 'Plumage',           desc: 'Cheatsheets' },
  { key: 'ux',          label: 'Allgemeine UX',     desc: 'Sidebar, Dark/Light, Tweaks-Panel' },
  { key: 'performance', label: 'Performance / Stabilität', desc: 'Ladezeiten, Bugs, Crashes' },
];

// ─── Sterne-Picker ────────────────────────────────────────────────────────────
const StarRating = ({ value, onChange, size = 22 }) => {
  const [hover, setHover] = React.useState(0);
  const display = hover || value;
  return (
    <div style={{ display: 'inline-flex', gap: 2 }} onMouseLeave={() => setHover(0)}>
      {[1, 2, 3, 4, 5].map(n => (
        <button key={n} type="button"
          onMouseEnter={() => setHover(n)}
          onClick={() => onChange(value === n ? 0 : n)}
          style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: 2,
            color: n <= display ? '#f59e0b' : 'var(--text-dim)',
            transition: 'color 0.1s ease',
          }}
          title={`${n}/5`}
        >
          <Icon name={n <= display ? 'starFilled' : 'star'} size={size} />
        </button>
      ))}
      {value > 0 && (
        <span style={{ marginLeft: 8, alignSelf: 'center', fontSize: 12, color: 'var(--text-muted)' }}>
          {value}/5
        </span>
      )}
    </div>
  );
};

// ─── Beta-Welcome-Modal ──────────────────────────────────────────────────────
// Wird bei jedem Login angezeigt, solange tweaks.betaWelcomeSeen !== true und
// HK_ENV === 'beta'. Schließen ohne Checkbox = "kommt beim nächsten Login wieder";
// Schließen mit Checkbox = onDismissForever (setzt das Tweak-Flag).
const BetaWelcomeModal = ({ open, user, onClose, onDismissForever, onGotoFeedback }) => {
  const [dontShowAgain, setDontShowAgain] = React.useState(false);
  React.useEffect(() => { if (open) setDontShowAgain(false); }, [open]);
  if (!open || !user) return null;
  const handleClose = () => {
    if (dontShowAgain) onDismissForever?.();
    else onClose();
  };
  const handleGotoFeedback = () => {
    if (dontShowAgain) onDismissForever?.();
    else onClose();
    onGotoFeedback?.();
  };
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1100,
      background: 'rgba(0,0,0,0.78)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 12, maxWidth: 620, width: '100%', maxHeight: '90vh',
        overflow: 'auto', padding: 0,
      }}>
        {/* Header */}
        <div style={{
          padding: '28px 32px 20px',
          background: 'linear-gradient(135deg, #f59e0b 0%, #ea580c 100%)',
          borderRadius: '12px 12px 0 0',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{
              fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 4,
              background: '#1a1728', color: '#f59e0b', letterSpacing: '0.05em',
            }}>BETA</span>
            <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.85)', fontFamily: 'var(--font-mono)' }}>
              beta.haikara.it
            </span>
          </div>
          <h2 style={{ margin: 0, fontSize: 24, fontWeight: 700, color: '#fff', letterSpacing: '-0.02em' }}>
            Willkommen in der Beta, {user.name?.split(' ')[0] || 'Tester'}!
          </h2>
          <p style={{ margin: '6px 0 0', fontSize: 14, color: 'rgba(255,255,255,0.92)' }}>
            Danke, dass du Heronry vor dem Live-Release ausprobierst.
          </p>
        </div>

        {/* Body */}
        <div style={{ padding: '24px 32px 28px', fontSize: 14, lineHeight: 1.6, color: 'var(--text)' }}>
          <h3 style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 600 }}>Was ist die Beta?</h3>
          <p style={{ margin: '0 0 16px', color: 'var(--text-muted)' }}>
            Eine separate Version der App, die wir auf Herz und Nieren testen, bevor sie auf{' '}
            <span style={{ fontFamily: 'var(--font-mono)' }}>haikara.it</span> live geht. Bugs sind hier
            ausdrücklich erwünscht — je mehr du findest, desto besser wird der Release.
          </p>

          <h3 style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 600 }}>Was kannst du machen?</h3>
          <ul style={{ margin: '0 0 16px', paddingLeft: 18, color: 'var(--text-muted)' }}>
            <li>Alle Features ausprobieren — du startest mit der <strong>Writer-Rolle</strong>, kannst also Notizen, Termine und Karten anlegen.</li>
            <li>Section-Chat & Direktnachrichten testen (gerne mit anderen Beta-Testern).</li>
            <li>2FA einrichten (TOTP-App, Telegram über <span style={{ fontFamily: 'var(--font-mono)' }}>@HaikaraBetaBot</span>, oder E-Mail).</li>
            <li>Hub, Egret (Subnet-Rechner) und Plumage (Cheatsheets) anschauen — alles ist Beta.</li>
          </ul>

          <h3 style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 600 }}>Wo gibst du Feedback?</h3>
          <p style={{ margin: '0 0 12px', color: 'var(--text-muted)' }}>
            Im neuen <strong>Beta-Feedback-Tab</strong> (links in der Sidebar, gelber Stern). Dort kannst du
            jedes Feature mit 1–5 Sternen bewerten und Anmerkungen schreiben. Alles geht direkt an mich.
          </p>

          <div style={{
            margin: '16px 0',
            padding: '14px 16px',
            background: 'rgba(155, 92, 246, 0.08)',
            border: '1px solid rgba(155, 92, 246, 0.25)',
            borderLeft: '3px solid var(--accent)',
            borderRadius: 8,
            fontSize: 13, color: 'var(--text)', fontStyle: 'italic',
          }}>
            „Große Veränderungen entstehen durch aussagekräftiges Feedback." — Je konkreter du
            schreibst (was hast du gemacht, was hast du erwartet, was ist passiert), desto eher
            schafft es deine Anmerkung in den Live-Release.
          </div>

          <h3 style={{ margin: '20px 0 8px', fontSize: 15, fontWeight: 600 }}>Verhaltensregeln</h3>
          <p style={{ margin: '0 0 8px', color: 'var(--text-muted)' }}>
            Damit das hier ein Ort bleibt, an dem man gerne testet, gilt für Chat, Direktnachrichten,
            Notiz-Inhalte und Feedback-Texte ein paar Basics:
          </p>
          <ul style={{ margin: '0 0 12px', paddingLeft: 18, color: 'var(--text-muted)' }}>
            <li>Keine Beleidigungen, kein Bashing gegen andere Tester.</li>
            <li>Keine Hassrede, kein Rassismus, keine Diskriminierung — egal wem gegenüber.</li>
            <li>Keine illegalen Inhalte, keine Gewaltdarstellungen, keine sexuellen Inhalte.</li>
            <li>Kein Spam, keine Werbung, keine Manipulation der Test-Daten.</li>
            <li>Respektvoller Umgangston, auch wenn etwas nicht funktioniert.</li>
          </ul>
          <div style={{
            padding: '12px 14px',
            background: 'rgba(248, 113, 113, 0.08)',
            border: '1px solid rgba(248, 113, 113, 0.3)',
            borderLeft: '3px solid #f87171',
            borderRadius: 8, fontSize: 13, color: 'var(--text)',
          }}>
            <strong style={{ color: '#f87171' }}>Wichtig:</strong> Verstöße gegen diese Regeln
            führen zum <strong>sofortigen Ausschluss aus der Beta</strong> — ohne Vorwarnung,
            ohne Diskussion. Im Wiederholungsfall auch beim späteren Live-Release.
          </div>

          <div style={{
            marginTop: 16, padding: '12px 14px',
            background: 'var(--bg-elevated, #f0eefa)', border: '1px solid var(--border)',
            borderRadius: 8, fontSize: 13, color: 'var(--text-muted)',
          }}>
            <strong style={{ color: 'var(--text)' }}>Bonus:</strong> Alle Beta-Tester bekommen beim
            offiziellen Release einen <strong style={{ color: 'var(--accent)' }}>Beta-Tester-Titel</strong>{' '}
            auf Live verliehen. Du bist bereits auf der Liste.
          </div>

          {/* Actions */}
          <div style={{
            display: 'flex', gap: 12, marginTop: 24, alignItems: 'center', flexWrap: 'wrap',
            justifyContent: 'space-between',
          }}>
            <label style={{
              display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
              fontSize: 12, color: 'var(--text-muted)', userSelect: 'none',
            }}>
              <input
                type="checkbox"
                checked={dontShowAgain}
                onChange={(e) => setDontShowAgain(e.target.checked)}
                style={{ accentColor: 'var(--accent)', cursor: 'pointer' }}
              />
              Diese Übersicht beim nächsten Login nicht mehr anzeigen
            </label>
            <div style={{ display: 'flex', gap: 10, marginLeft: 'auto' }}>
              <Btn variant="ghost" onClick={handleClose}>Schließen</Btn>
              <Btn variant="primary" icon="star" onClick={handleGotoFeedback}>
                Direkt zum Feedback
              </Btn>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Feedback-View ───────────────────────────────────────────────────────────
const FeedbackView = ({ user }) => {
  const [ratings, setRatings] = React.useState({}); // { [key]: { stars, comment } }
  const [general, setGeneral] = React.useState('');
  const [nameSugs, setNameSugs] = React.useState({}); // { [appKey]: 'Vorschlag' }
  const [busy, setBusy] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  const setStars = (key, stars) => {
    setRatings(r => ({ ...r, [key]: { ...(r[key] || {}), stars } }));
  };
  const setComment = (key, comment) => {
    setRatings(r => ({ ...r, [key]: { ...(r[key] || {}), comment } }));
  };
  const setNameSug = (key, value) => {
    setNameSugs(s => ({ ...s, [key]: value }));
  };

  const totalRated = Object.values(ratings).filter(r => r.stars > 0).length;
  const totalComments = Object.values(ratings).filter(r => r.comment?.trim()).length;
  const totalNames = Object.values(nameSugs).filter(v => v?.trim()).length;

  const submit = async () => {
    const payload = BETA_FEATURES
      .map(f => ({
        key: f.key,
        stars: ratings[f.key]?.stars || 0,
        comment: ratings[f.key]?.comment || null,
      }))
      .filter(r => r.stars > 0 || r.comment);
    const names = {};
    for (const k of Object.keys(nameSugs)) {
      const v = nameSugs[k]?.trim();
      if (v) names[k] = v;
    }
    if (!payload.length && !general.trim() && !Object.keys(names).length) {
      window.toast?.('Bitte mindestens eine Bewertung, einen Kommentar oder einen Namensvorschlag abgeben.', 'error');
      return;
    }
    setBusy(true);
    const { ok, data } = await window.apiFetch('/api/feedback', {
      method: 'POST',
      body: {
        featureRatings: payload,
        generalComment: general.trim() || null,
        nameSuggestions: Object.keys(names).length ? names : null,
      },
    });
    setBusy(false);
    if (!ok) {
      window.toast?.(data?.error || 'Senden fehlgeschlagen.', 'error');
      return;
    }
    window.toast?.('Danke! Dein Feedback ist angekommen.', 'success');
    setSubmitted(true);
  };

  const reset = () => {
    setRatings({});
    setGeneral('');
    setNameSugs({});
    setSubmitted(false);
  };

  return (
    <div style={{ maxWidth: 880, margin: '0 auto', width: '100%', boxSizing: 'border-box', padding: '0 24px 80px' }}>
      {/* Header */}
      <div style={{ marginTop: 24, marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <span style={{
            fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 3,
            background: '#f59e0b', color: '#1a1728', letterSpacing: '0.05em',
          }}>BETA</span>
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Feedback</span>
        </div>
        <h1 style={{ margin: 0, fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--text)' }}>
          Wie läuft die Beta für dich?
        </h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: 'var(--text-muted)', maxWidth: 640 }}>
          Bewerte jedes Feature mit 1–5 Sternen und schreib gerne dazu, was gut oder doof ist.
          Du musst nicht alles ausfüllen — nur was du wirklich getestet hast.
        </p>
      </div>

      {submitted && (
        <div style={{
          padding: '14px 16px', marginBottom: 20,
          background: 'rgba(16, 185, 129, 0.1)', border: '1px solid rgba(16, 185, 129, 0.3)',
          borderRadius: 8, color: 'var(--text)', fontSize: 14,
          display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'space-between',
        }}>
          <span>✓ Dein Feedback ist angekommen — danke!</span>
          <Btn variant="ghost" size="sm" onClick={reset}>Weiteres Feedback geben</Btn>
        </div>
      )}

      {/* Feature-Liste */}
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 10,
        overflow: 'hidden', marginBottom: 24,
      }}>
        {BETA_FEATURES.map((f, i) => (
          <div key={f.key} style={{
            padding: '16px 20px',
            borderBottom: i < BETA_FEATURES.length - 1 ? '1px solid var(--border)' : 'none',
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 240px', minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{f.label}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{f.desc}</div>
              </div>
              <div style={{ flex: '0 0 auto' }}>
                <StarRating
                  value={ratings[f.key]?.stars || 0}
                  onChange={(n) => setStars(f.key, n)}
                />
              </div>
            </div>
            <textarea
              value={ratings[f.key]?.comment || ''}
              onChange={(e) => setComment(f.key, e.target.value)}
              placeholder={`Anmerkung zu „${f.label}"… (optional)`}
              rows={2}
              style={{
                width: '100%', boxSizing: 'border-box', marginTop: 10,
                background: 'var(--bg)', border: '1px solid var(--border)',
                borderRadius: 6, padding: '8px 10px', fontSize: 13,
                color: 'var(--text)', fontFamily: 'var(--font-sans)', resize: 'vertical',
              }}
              maxLength={4000}
            />
          </div>
        ))}
      </div>

      {/* Namensvorschläge für die Apps */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
          <label style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>
            Namensvorschläge
          </label>
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
            Die aktuellen Namen sind Platzhalter — alles willkommen.
          </span>
        </div>
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 10,
          overflow: 'hidden',
        }}>
          {BETA_NAME_APPS.map((a, i) => (
            <div key={a.key} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
              borderBottom: i < BETA_NAME_APPS.length - 1 ? '1px solid var(--border)' : 'none',
              flexWrap: 'wrap',
            }}>
              <div style={{ flex: '0 0 180px', minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>
                  {a.current}
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 1 }}>{a.desc}</div>
              </div>
              <div style={{ flex: '1 1 240px', minWidth: 200, display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 14, color: 'var(--text-dim)' }}>→</span>
                <input
                  type="text"
                  value={nameSugs[a.key] || ''}
                  onChange={(e) => setNameSug(a.key, e.target.value)}
                  placeholder={`Wie sollte „${a.current}" heißen?`}
                  maxLength={200}
                  style={{
                    flex: 1, background: 'var(--bg)', border: '1px solid var(--border)',
                    borderRadius: 6, padding: '8px 10px', fontSize: 13,
                    color: 'var(--text)', fontFamily: 'var(--font-sans)',
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Allgemeiner Kommentar */}
      <div style={{ marginBottom: 24 }}>
        <label style={{ display: 'block', fontSize: 14, fontWeight: 600, color: 'var(--text)', marginBottom: 8 }}>
          Allgemeines Feedback
        </label>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 8 }}>
          Was fehlt? Was ist verwirrend? Bug-Reports? Wünsche?
        </div>
        <textarea
          value={general}
          onChange={(e) => setGeneral(e.target.value)}
          placeholder="Frei Schnauze…"
          rows={6}
          style={{
            width: '100%', boxSizing: 'border-box',
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 8, padding: '12px 14px', fontSize: 14,
            color: 'var(--text)', fontFamily: 'var(--font-sans)', resize: 'vertical',
          }}
          maxLength={8000}
        />
      </div>

      {/* Submit */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '16px 0', borderTop: '1px solid var(--border)',
      }}>
        <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>
          {totalRated} Bewertung{totalRated === 1 ? '' : 'en'}, {totalComments} Anmerkung{totalComments === 1 ? '' : 'en'}
          {totalNames > 0 && `, ${totalNames} Namensvorschlag${totalNames === 1 ? '' : 'e'}`}
          {general.trim() && ', + Allgemein'}
        </div>
        <Btn variant="primary" icon="check" onClick={submit} disabled={busy}>
          {busy ? 'Sende…' : 'Feedback abschicken'}
        </Btn>
      </div>
    </div>
  );
};

// ─── Admin: Feedback-Auswertung ──────────────────────────────────────────────
// Liest /api/feedback (Admin-only), aggregiert client-seitig:
//   - Gesamt-Stats: Anzahl Eintraege, Gesamt-Avg
//   - Pro Feature: Avg-Sterne, Anzahl Bewertungen, Sterne-Verteilung
//   - Namensvorschlaege: pro App gruppiert mit Counts
//   - Liste aller Eintraege mit Expand fuer Volltext.
const FeedbackAdminView = () => {
  const [items, setItems] = React.useState(null); // null = loading, [] = leer
  const [error, setError] = React.useState(null);
  const [expanded, setExpanded] = React.useState(new Set());

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const { ok, data } = await window.apiFetch('/api/feedback?limit=500');
      if (cancelled) return;
      if (!ok) { setError(data?.error || 'Laden fehlgeschlagen.'); setItems([]); return; }
      setItems(data.feedback || []);
    })();
    return () => { cancelled = true; };
  }, []);

  const toggleExpand = (id) => {
    setExpanded(s => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  };

  if (items === null) {
    return <div style={{ padding: 24, color: 'var(--text-muted)', fontSize: 13 }}>Lade Feedback…</div>;
  }
  if (error) {
    return <div style={{ padding: 24, color: '#f87171', fontSize: 13 }}>Fehler: {error}</div>;
  }

  // Aggregation
  const featureMap = {}; // key → { stars: [], comments: 0 }
  for (const f of BETA_FEATURES) featureMap[f.key] = { stars: [], comments: 0 };
  const nameMap = {}; // appKey → Map<vorschlag, count>
  for (const a of BETA_NAME_APPS) nameMap[a.key] = new Map();

  for (const it of items) {
    const ratings = Array.isArray(it.featureRatings) ? it.featureRatings : [];
    for (const r of ratings) {
      if (!featureMap[r.key]) continue;
      if (r.stars > 0) featureMap[r.key].stars.push(r.stars);
      if (r.comment?.trim()) featureMap[r.key].comments += 1;
    }
    const names = it.nameSuggestions || {};
    for (const k of Object.keys(names)) {
      if (!nameMap[k]) continue;
      const v = String(names[k]).trim();
      if (!v) continue;
      nameMap[k].set(v, (nameMap[k].get(v) || 0) + 1);
    }
  }

  // Gesamtdurchschnitt aus allen Sternen aller Features
  const allStars = Object.values(featureMap).flatMap(f => f.stars);
  const overallAvg = allStars.length ? (allStars.reduce((a, b) => a + b, 0) / allStars.length) : 0;
  const totalRatings = allStars.length;

  const renderStarsAvg = (avg) => {
    const filled = Math.round(avg);
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 1 }}>
        {[1, 2, 3, 4, 5].map(n => (
          <Icon key={n} name={n <= filled ? 'starFilled' : 'star'} size={14}
            color={n <= filled ? '#f59e0b' : 'var(--text-dim)'} />
        ))}
      </span>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Gesamt-Header */}
      <div style={{
        display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap',
        padding: '20px 24px', background: 'var(--surface)',
        border: '1px solid var(--border)', borderRadius: 12,
      }}>
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Gesamt-Bewertung
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
            <span style={{ fontSize: 28, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>
              {overallAvg ? overallAvg.toFixed(2) : '—'}
            </span>
            <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>/ 5</span>
            <span style={{ marginLeft: 8 }}>{renderStarsAvg(overallAvg)}</span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>
            aus {totalRatings} Einzelbewertung{totalRatings === 1 ? '' : 'en'}
          </div>
        </div>
        <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--border)' }} />
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Eingegangenes Feedback
          </div>
          <div style={{ fontSize: 28, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-mono)', marginTop: 4 }}>
            {items.length}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>
            Submissions insgesamt
          </div>
        </div>
      </div>

      {/* Feature-Stats */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', fontSize: 13, fontWeight: 600 }}>
          Bewertungen pro Feature
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: 'var(--surface-2, transparent)' }}>
              <th style={{ textAlign: 'left',  padding: '8px 16px', fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Feature</th>
              <th style={{ textAlign: 'right', padding: '8px 16px', fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Avg</th>
              <th style={{ textAlign: 'left',  padding: '8px 16px', fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Sterne</th>
              <th style={{ textAlign: 'right', padding: '8px 16px', fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Bewertungen</th>
              <th style={{ textAlign: 'right', padding: '8px 16px', fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Anmerkungen</th>
            </tr>
          </thead>
          <tbody>
            {BETA_FEATURES.map(f => {
              const m = featureMap[f.key];
              const count = m.stars.length;
              const avg = count ? (m.stars.reduce((a, b) => a + b, 0) / count) : 0;
              return (
                <tr key={f.key} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: '10px 16px' }}>
                    <div style={{ fontWeight: 500 }}>{f.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{f.key}</div>
                  </td>
                  <td style={{ padding: '10px 16px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
                    {count ? avg.toFixed(2) : <span style={{ color: 'var(--text-dim)' }}>—</span>}
                  </td>
                  <td style={{ padding: '10px 16px' }}>
                    {count ? renderStarsAvg(avg) : <span style={{ color: 'var(--text-dim)' }}>—</span>}
                  </td>
                  <td style={{ padding: '10px 16px', textAlign: 'right', fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{count}</td>
                  <td style={{ padding: '10px 16px', textAlign: 'right', fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{m.comments}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Namensvorschläge gruppiert */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', fontSize: 13, fontWeight: 600 }}>
          Namensvorschläge
        </div>
        {BETA_NAME_APPS.map((a, i) => {
          const sugs = Array.from(nameMap[a.key].entries()).sort((x, y) => y[1] - x[1]);
          return (
            <div key={a.key} style={{
              padding: '12px 20px',
              borderTop: i === 0 ? 'none' : '1px solid var(--border)',
              display: 'flex', gap: 16, alignItems: 'flex-start', flexWrap: 'wrap',
            }}>
              <div style={{ flex: '0 0 140px' }}>
                <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>{a.current}</div>
                <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 1 }}>
                  {sugs.length} Vorschlag{sugs.length === 1 ? '' : 'e'}
                </div>
              </div>
              <div style={{ flex: 1, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {sugs.length === 0 && <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>— noch nichts —</span>}
                {sugs.map(([name, cnt]) => (
                  <span key={name} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '4px 10px', background: 'var(--surface-2, var(--bg))',
                    border: '1px solid var(--border)', borderRadius: 14,
                    fontSize: 12,
                  }}>
                    <span style={{ fontWeight: 500 }}>{name}</span>
                    {cnt > 1 && (
                      <span style={{ fontSize: 10, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>×{cnt}</span>
                    )}
                  </span>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {/* Liste aller Submissions */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', fontSize: 13, fontWeight: 600 }}>
          Alle Submissions
        </div>
        {items.length === 0 && (
          <div style={{ padding: 24, fontSize: 13, color: 'var(--text-muted)', textAlign: 'center' }}>
            Noch kein Feedback eingegangen.
          </div>
        )}
        {items.map(it => {
          const ratings = Array.isArray(it.featureRatings) ? it.featureRatings : [];
          const ratedCount = ratings.filter(r => r.stars > 0).length;
          const commentCount = ratings.filter(r => r.comment?.trim()).length;
          const namesCount = it.nameSuggestions ? Object.keys(it.nameSuggestions).length : 0;
          const isOpen = expanded.has(it.id);
          const itemAvg = ratedCount
            ? (ratings.filter(r => r.stars > 0).reduce((a, b) => a + b.stars, 0) / ratedCount)
            : 0;
          return (
            <div key={it.id} style={{ borderTop: '1px solid var(--border)' }}>
              <button
                onClick={() => toggleExpand(it.id)}
                style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 20px', background: 'transparent', border: 'none',
                  cursor: 'pointer', textAlign: 'left', color: 'var(--text)',
                }}
              >
                <Icon name={isOpen ? 'chevronDown' : 'chevronRight'} size={14} color="var(--text-muted)" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                    <span style={{ fontWeight: 500 }}>{it.userName || '—'}</span>
                    <span style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
                      {it.userEmail || '—'}
                    </span>
                    <span style={{
                      fontSize: 10, padding: '1px 6px', borderRadius: 3,
                      background: it.env === 'beta' ? '#f59e0b' : 'var(--text-dim)',
                      color: '#1a1728', fontWeight: 700, letterSpacing: '0.05em',
                    }}>{(it.env || '?').toUpperCase()}</span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
                    #{it.id} · {new Date(it.createdAt).toLocaleString('de-DE')}
                    {' · '}
                    {ratedCount} Bewert. {commentCount > 0 && `(${commentCount} Anm.)`}
                    {namesCount > 0 && ` · ${namesCount} Namen`}
                    {it.generalComment && ' · + Allgemein'}
                  </div>
                </div>
                {ratedCount > 0 && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>
                    {itemAvg.toFixed(1)} {renderStarsAvg(itemAvg)}
                  </div>
                )}
              </button>
              {isOpen && (
                <div style={{ padding: '0 20px 16px 46px', fontSize: 13, color: 'var(--text)', display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {ratings.filter(r => r.stars > 0 || r.comment?.trim()).length > 0 && (
                    <div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Feature-Bewertungen</div>
                      {ratings.filter(r => r.stars > 0 || r.comment?.trim()).map((r, idx) => {
                        const meta = BETA_FEATURES.find(f => f.key === r.key);
                        return (
                          <div key={idx} style={{ display: 'flex', gap: 12, padding: '6px 0', alignItems: 'flex-start' }}>
                            <div style={{ flex: '0 0 140px', fontWeight: 500 }}>{meta?.label || r.key}</div>
                            <div style={{ flex: '0 0 110px' }}>
                              {r.stars > 0 ? (
                                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                                  {renderStarsAvg(r.stars)}
                                  <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>({r.stars}/5)</span>
                                </span>
                              ) : <span style={{ color: 'var(--text-dim)', fontSize: 12 }}>— keine Wertung —</span>}
                            </div>
                            <div style={{ flex: 1, color: 'var(--text-muted)', whiteSpace: 'pre-wrap' }}>
                              {r.comment || <span style={{ color: 'var(--text-dim)' }}>—</span>}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                  {namesCount > 0 && (
                    <div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Namensvorschläge</div>
                      {Object.entries(it.nameSuggestions).map(([k, v]) => (
                        <div key={k} style={{ padding: '4px 0' }}>
                          <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{k}</span>
                          {' → '}
                          <strong>{v}</strong>
                        </div>
                      ))}
                    </div>
                  )}
                  {it.generalComment && (
                    <div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Allgemeiner Kommentar</div>
                      <div style={{
                        padding: 10, background: 'var(--surface-2, var(--bg))',
                        borderLeft: '3px solid var(--accent)', borderRadius: 6,
                        whiteSpace: 'pre-wrap', lineHeight: 1.5,
                      }}>{it.generalComment}</div>
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { BetaWelcomeModal, FeedbackView, FeedbackAdminView, BETA_FEATURES, BETA_NAME_APPS });
