// Comments + public profile view for a user.
// Comments are stored in localStorage 'aw.comments' = { [coloringSlug]: [{id, email, name, colorIdx, text, at, likes}] }

const _commentsKey = 'aw.comments';
const loadComments = (slug) => {
  try {
    const all = JSON.parse(localStorage.getItem(_commentsKey) || '{}');
    return all[slug] || [];
  } catch { return []; }
};
const saveComments = (slug, list) => {
  try {
    const all = JSON.parse(localStorage.getItem(_commentsKey) || '{}');
    all[slug] = list;
    localStorage.setItem(_commentsKey, JSON.stringify(all));
  } catch {}
};

// Find any user profile (creds entry) by email for the "public profile" view.
const findProfileByEmail = (email) => {
  try {
    const creds = JSON.parse(localStorage.getItem('aw.creds') || '{}');
    return creds[(email || '').toLowerCase()] || null;
  } catch { return null; }
};

// === CommentSection, used inside DetailPage ===
const CommentSection = ({ slug, user, openAuth, navigate }) => {
  const [comments, setComments] = React.useState(() => loadComments(slug));
  const [text, setText] = React.useState('');

  React.useEffect(() => { setComments(loadComments(slug)); }, [slug]);

  const add = (e) => {
    e.preventDefault();
    if (!user) { openAuth(); return; }
    const t = text.trim();
    if (!t) return;
    const c = {
      id: Date.now(),
      email: (user.email || '').toLowerCase(),
      name: user.name,
      colorIdx: user.colorIdx ?? 0,
      text: t,
      at: new Date().toISOString(),
      likes: 0,
    };
    const next = [c, ...comments];
    setComments(next);
    saveComments(slug, next);
    setText('');
  };

  const like = (id) => {
    const next = comments.map(c => c.id === id ? { ...c, likes: (c.likes || 0) + 1 } : c);
    setComments(next);
    saveComments(slug, next);
  };
  const remove = (id) => {
    if (!confirm('Kommentar löschen?')) return;
    const next = comments.filter(c => c.id !== id);
    setComments(next);
    saveComments(slug, next);
  };

  return (
    <section className="mt-16">
      <SectionHeading kicker={`${comments.length} ${comments.length === 1 ? 'Kommentar' : 'Kommentare'}`} title="Was sagt die Community?"/>

      {/* Compose */}
      <form onSubmit={add} className="bg-paper rounded-3xl ring-2 ring-line p-5 mb-5">
        {user ? (
          <div className="flex items-start gap-3">
            <Avatar user={user} size={42}/>
            <div className="flex-1 min-w-0">
              <textarea value={text} onChange={(e) => setText(e.target.value.slice(0, 500))}
                rows="3" placeholder="Schreib was Nettes zu diesem Bild …"
                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"/>
              <div className="mt-2 flex items-center justify-between">
                <div className="text-[11px] text-inkSoft">{text.length}/500 · Bleib freundlich 💛</div>
                <Btn type="submit" size="sm" disabled={!text.trim()}
                  className={!text.trim() ? 'opacity-50 cursor-not-allowed' : ''}>
                  Kommentar senden
                </Btn>
              </div>
            </div>
          </div>
        ) : (
          <div className="flex items-center justify-between gap-3">
            <div>
              <div className="font-display text-lg font-extrabold">Mitreden?</div>
              <div className="text-[13px] text-inkSoft">Erstelle ein Profil oder melde dich an, um Kommentare zu schreiben.</div>
            </div>
            <Btn size="md" onClick={openAuth}>Anmelden</Btn>
          </div>
        )}
      </form>

      {/* List */}
      {comments.length === 0 ? (
        <div className="text-center py-10 bg-paper rounded-3xl ring-2 ring-line">
          <div className="text-5xl mb-2">💬</div>
          <div className="font-display text-lg font-extrabold">Noch keine Kommentare</div>
          <div className="text-[13px] text-inkSoft">Sei der/die Erste!</div>
        </div>
      ) : (
        <div className="grid gap-3">
          {comments.map(c => (
            <CommentRow key={c.id} c={c} navigate={navigate}
              canDelete={user && (c.email === (user.email || '').toLowerCase())}
              onLike={() => like(c.id)} onDelete={() => remove(c.id)}/>
          ))}
        </div>
      )}
    </section>
  );
};

const CommentRow = ({ c, navigate, onLike, onDelete, canDelete }) => {
  const profile = { name: c.name, colorIdx: c.colorIdx, email: c.email };
  const dateLabel = new Date(c.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
  return (
    <div className="bg-paper rounded-2xl ring-2 ring-line p-4 flex items-start gap-3 stagger-fade">
      <button onClick={() => navigate({ view: 'publicProfile', email: c.email })}
        title={`Profil von ${c.name} ansehen`}>
        <Avatar user={profile} size={42}/>
      </button>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-1">
          <button onClick={() => navigate({ view: 'publicProfile', email: c.email })}
            className="font-display font-extrabold leading-tight hover:text-coralDeep transition truncate">
            {c.name}
          </button>
          <span className="text-[11px] text-inkSoft">· {dateLabel}</span>
        </div>
        <p className="text-[14px] text-ink leading-relaxed" style={{wordBreak:'break-word'}}>{c.text}</p>
        <div className="mt-2 flex items-center gap-3">
          <button onClick={onLike}
            className="text-[12px] inline-flex items-center gap-1 font-bold text-inkSoft hover:text-coralDeep transition">
            <IconHeart size={14}/> {c.likes || 0}
          </button>
          <button onClick={() => navigate({ view: 'publicProfile', email: c.email })}
            className="text-[12px] font-bold text-inkSoft hover:text-coralDeep transition inline-flex items-center gap-1">
            <IconUser size={12}/> Profil ansehen
          </button>
          {canDelete && (
            <button onClick={onDelete}
              className="ml-auto text-[11px] font-bold text-coralDeep hover:underline">
              Löschen
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

// === PublicProfilePage, read-only view of another user's profile ===
const PublicProfilePage = ({ email, navigate }) => {
  const profile = findProfileByEmail(email);
  if (!profile) {
    return (
      <main className="max-w-3xl mx-auto px-5 sm:px-8 pt-16 pb-24 text-center">
        <div className="text-6xl mb-4">🤷</div>
        <h1 className="font-display text-3xl font-extrabold">Profil nicht gefunden</h1>
        <p className="text-inkSoft mt-2">Dieses Profil existiert nicht mehr oder wurde gelöscht.</p>
        <Btn className="mt-6" onClick={() => navigate({ view: 'home' })}>Zurück zur Startseite</Btn>
      </main>
    );
  }

  // Compute achievements from this profile's perspective.
  // We need their mappen + suggestions, for simplicity use what's stored under their key.
  let theirMappen = [];
  try {
    theirMappen = JSON.parse(localStorage.getItem(`aw.mappen.${email}`) || '[]');
  } catch {}
  const { all: allAch, earned, stats } = evaluateAchievements(profile, theirMappen, []);

  // Count comments by this user across all coloring pages.
  let totalComments = 0;
  try {
    const all = JSON.parse(localStorage.getItem('aw.comments') || '{}');
    Object.values(all).forEach(arr => (arr || []).forEach(c => { if (c.email === (email || '').toLowerCase()) totalComments++; }));
  } catch {}

  const bereich = BEREICH_OPTIONS.find(b => b.value === profile.bereich);
  const isPrem = !!(profile.premium && profile.premium.active);
  const memberSince = profile.joined ? new Date(profile.joined) : null;
  const daysSince = memberSince ? Math.max(1, Math.floor((Date.now() - memberSince.getTime()) / 86400e3)) : 0;

  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:`Profil: ${profile.name}`}]} navigate={navigate}/>

      {/* Header card */}
      <section className="mt-5 rounded-[36px] ring-2 ring-line p-6 sm:p-8 relative overflow-hidden bg-gradient-to-br from-paper via-paper to-sky/20">
        {isPrem && (
          <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>
        )}
        <div className="flex flex-col sm:flex-row sm:items-center gap-6">
          <Avatar user={profile} size={96}/>
          <div className="flex-1 min-w-0">
            <div className="text-[12px] font-bold uppercase tracking-[0.12em] text-coralDeep">Profil</div>
            <h1 className="font-display text-3xl sm:text-4xl font-extrabold leading-tight">{profile.name}</h1>
            {profile.bio && <p className="mt-2 text-inkSoft leading-relaxed max-w-2xl">{profile.bio}</p>}
            <div className="mt-3 flex flex-wrap items-center gap-2 text-[13px]">
              {bereich && (
                <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper ring-1 ring-line font-semibold">
                  <span aria-hidden="true">{bereich.emoji}</span>{bereich.label}
                </span>
              )}
              {profile.city && (
                <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper ring-1 ring-line font-semibold">
                  📍 {profile.city}
                </span>
              )}
              {memberSince && (
                <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper ring-1 ring-line font-semibold">
                  📅 Seit {memberSince.toLocaleDateString('de-DE', {month:'long', year:'numeric'})}
                </span>
              )}
              <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper ring-1 ring-line font-semibold">
                🏆 {earned.length} Auszeichnung{earned.length === 1 ? '' : 'en'}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* Stats row */}
      <div className="mt-6 grid sm:grid-cols-4 gap-3">
        <PublicStat label="Dabei seit" value={`${daysSince} Tag${daysSince === 1 ? '' : 'e'}`} icon="📅"/>
        <PublicStat label="Auszeichnungen" value={`${earned.length}/${allAch.length}`} icon="🏆"/>
        <PublicStat label="Kommentare" value={totalComments} icon="💬"/>
        <PublicStat label="Sammelmappen" value={theirMappen.length} icon="🎒"/>
      </div>

      {/* Achievements */}
      <section className="mt-8">
        <SectionHeading kicker="Trophäenschrank" title={`Auszeichnungen (${earned.length})`}/>
        {earned.length === 0 ? (
          <div className="text-center py-10 bg-paper rounded-3xl ring-2 ring-line">
            <div className="text-5xl mb-2">🌱</div>
            <div className="font-display text-lg font-extrabold">Noch keine Auszeichnungen</div>
            <div className="text-[13px] text-inkSoft">Bald sammelt {profile.name} die erste Trophäe!</div>
          </div>
        ) : (
          <AchievementGrid list={earned}/>
        )}
        {allAch.length > earned.length && (
          <details className="mt-5 bg-paper rounded-2xl ring-1 ring-line p-4">
            <summary className="cursor-pointer text-sm font-bold inline-flex items-center gap-2">
              <IconChevronR size={14}/> Noch nicht erreicht ({allAch.length - earned.length})
            </summary>
            <div className="mt-4">
              <AchievementGrid list={allAch.filter(a => !a.earned)}/>
            </div>
          </details>
        )}
      </section>
    </main>
  );
};

const PublicStat = ({ label, value, icon }) => (
  <div className="bg-paper rounded-2xl ring-1 ring-line p-4 flex items-center gap-3">
    <span className="inline-flex w-10 h-10 rounded-xl bg-cream 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">{label}</div>
      <div className="font-display text-xl font-extrabold leading-tight truncate">{value}</div>
    </div>
  </div>
);

Object.assign(window, {
  CommentSection, PublicProfilePage, findProfileByEmail,
  loadComments, saveComments,
});
