// Heute (Today) screen — landing view

function ScreenHeute({ wide, activeGroupId, onChangeGroup, onOpenWeekly, onOpenDates, onOpenSession, onOpenNotif, notifUnread = 0, onOpenProfile, onOpenAddFriend }) {
  const t = window.t;
  const filterGroupId = activeGroupId === 'all' ? null : activeGroupId;
  const onlineFriends = window.FRIENDS
    .filter(f => f.online && f.id !== 'me')
    .filter(f => !filterGroupId || (window.GROUPS_BY_ID[filterGroupId]?.memberIds || []).includes(f.id));
  const [, bumpRsvp] = React.useReducer(x => x + 1, 0);
  // One-tap "join anyway": override the auto-decline by saying we're in.
  const onReactivate = (s) => {
    window.fbSaveResponse?.(window.sessionKey?.(s), { rsvp: 'in', voteGameId: null });
    bumpRsvp();
  };

  const sessions = window.getHomeSessions(activeGroupId);
  const liveSessions = sessions.filter(s => !s.autoDeclined);

  const tonight = liveSessions.find(s => s.dayOffset === 0) || liveSessions[0] || sessions[0];
  const upcoming = sessions.filter(s => s !== tonight).slice(0, 6);

  // My RSVP status for tonight — default answer is "dabei" (in)
  const myStatus = tonight
    ? ((window.__MY_RESPONSES || {})[window.sessionKey?.(tonight)]?.rsvp || 'in')
    : null;
  const STATUS_META = {
    in:    { label: t('bin_dabei'),  color: 'var(--accent)', mark: '✓ ' },
    maybe: { label: t('maybe'),      color: 'var(--violet)', mark: '' },
    out:   { label: t('kann_nicht'), color: 'var(--pink)',   mark: '' },
  };
  const statusColor = STATUS_META[myStatus]?.color || 'var(--accent)';

  // recurring next-up (within next 7 days, filtered by group)
  const recurring = window.RECURRING_SESSIONS
    .filter(r => !filterGroupId || r.groupId === filterGroupId)
    .map(r => {
      const off = ((r.dow - window.TODAY_DOW) + 7) % 7;
      return { ...r, dayOffset: off };
    })
    .sort((a,b) => a.dayOffset - b.dayOffset)
    .slice(0, 2);

  // ── Desktop / tablet: multi-column dashboard ───────────────────────────────
  if (wide) {
    return (
      <div>
        <div style={{ marginBottom: 24 }}>
          <div style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 13, fontWeight: 500,
            color: 'var(--muted)', letterSpacing: 0.5, textTransform: 'uppercase',
          }}>{window.todayDateLabel()}</div>
          <div style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 34, fontWeight: 700,
            color: 'var(--text)', letterSpacing: -1, marginTop: 2,
          }}>{t('servus', window.FRIENDS_BY_ID['me']?.name || 'Zocker')}</div>
        </div>

        {sessions.length === 0 ? (
          <div style={{ maxWidth: 620 }}>
            <InviteBanner onOpenAddFriend={onOpenAddFriend} />
          </div>
        ) : (
          <div style={{
            display: 'grid', gridTemplateColumns: 'minmax(0, 1.7fr) minmax(0, 1fr)',
            gap: 24, alignItems: 'start',
          }}>
            {/* main column */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
              {tonight && <TonightHero tonight={tonight} myStatus={myStatus} onOpenSession={onOpenSession} />}
              {upcoming.length > 0 && (
                <div>
                  <SectionHead title={t('vorschlaege')} />
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {upcoming.map((s, i) => (
                      <SessionRow key={i} session={s} onClick={() => onOpenSession(s)} onReactivate={onReactivate} />
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* side column */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <QuickAction label={t('wochenplan')} desc={t('wochenplan_desc')} icon={<IconClock />} onClick={onOpenWeekly} />
                <QuickAction label={t('freie_tage')} desc={t('freie_tage_desc')} icon={<IconCalendar />} onClick={onOpenDates} />
              </div>

              {recurring.length > 0 && (
                <div>
                  <SectionHead title={t('raid_nights')} />
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {recurring.map(r => (
                      <RecurringRow key={r.id} item={r} onOpen={() => {
                        const group = window.GROUPS_BY_ID[r.groupId];
                        const friends = [...r.confirmed, ...r.maybe];
                        onOpenSession({
                          dow: r.dow, from: r.from, to: r.to,
                          friends, topGame: window.GAMES_BY_ID[r.gameId], topVotes: r.confirmed.length,
                          dayOffset: ((r.dow - window.TODAY_DOW) + 7) % 7,
                          groups: group ? [group] : [],
                          recurring: r,
                        });
                      }} />
                    ))}
                  </div>
                </div>
              )}

              {onlineFriends.length > 0 && (
                <div>
                  <SectionHead title={t('jetzt_online')} />
                  <Card style={{ padding: 14 }}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
                      {onlineFriends.map(f => (
                        <div key={f.id} style={{
                          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                        }}>
                          <Avatar id={f.id} size={48} showStatus />
                          <span style={{
                            fontFamily: 'Space Grotesk, system-ui', fontSize: 12,
                            color: 'var(--text)', fontWeight: 500,
                          }}>{f.name}</span>
                        </div>
                      ))}
                    </div>
                  </Card>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div style={{ padding: '16px 16px 100px' }}>
      {/* Top hello row */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '4px 4px 14px',
      }}>
        <div>
          <div style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 13, fontWeight: 500,
            color: 'var(--muted)', letterSpacing: 0.5, textTransform: 'uppercase',
          }}>
            {window.todayDateLabel()}
          </div>
          <div style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 30, fontWeight: 700,
            color: 'var(--text)', letterSpacing: -0.8, marginTop: 2,
          }}>{t('servus', window.FRIENDS_BY_ID['me']?.name || 'Zocker')}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={onOpenNotif} style={{
            appearance: 'none', cursor: 'pointer',
            width: 38, height: 38, borderRadius: 999,
            background: 'var(--surface)', border: '1px solid var(--border)',
            color: 'var(--text)', position: 'relative',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/>
              <path d="M13.7 21a2 2 0 0 1-3.4 0"/>
            </svg>
            {notifUnread > 0 && (
              <div style={{
                position: 'absolute', top: 7, right: 9,
                width: 8, height: 8, borderRadius: '50%',
                background: 'var(--accent)',
                boxShadow: '0 0 6px var(--accent)',
              }} />
            )}
          </button>
          <button onClick={onOpenProfile} aria-label={t('profile')} style={{
            appearance: 'none', cursor: 'pointer', border: 0, padding: 0,
            background: 'transparent', borderRadius: '50%',
          }}>
            <Avatar id="me" size={42} ring />
          </button>
        </div>
      </div>

      {/* Group filter chips */}
      <GroupFilter active={activeGroupId} onChange={onChangeGroup} />

      {/* No matches yet → invite-friends banner */}
      {sessions.length === 0 && (
        <InviteBanner onOpenAddFriend={onOpenAddFriend} />
      )}

      {/* Tonight hero */}
      {tonight && (
        <div style={{ marginBottom: 22 }}>
          <TonightHero tonight={tonight} myStatus={myStatus} onOpenSession={onOpenSession} />
        </div>
      )}

      {/* Quick actions */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 22,
      }}>
        <QuickAction
          label={t('wochenplan')}
          desc={t('wochenplan_desc')}
          icon={<IconClock />}
          onClick={onOpenWeekly}
        />
        <QuickAction
          label={t('freie_tage')}
          desc={t('freie_tage_desc')}
          icon={<IconCalendar />}
          onClick={onOpenDates}
        />
      </div>

      {/* Recurring / Raid Nights */}
      {recurring.length > 0 && (
        <div style={{ marginBottom: 22 }}>
          <SectionHead title={t('raid_nights')} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {recurring.map(r => (
              <RecurringRow key={r.id} item={r} onOpen={() => {
                const group = window.GROUPS_BY_ID[r.groupId];
                const friends = [...r.confirmed, ...r.maybe];
                onOpenSession({
                  dow: r.dow, from: r.from, to: r.to,
                  friends, topGame: window.GAMES_BY_ID[r.gameId], topVotes: r.confirmed.length,
                  dayOffset: ((r.dow - window.TODAY_DOW) + 7) % 7,
                  groups: group ? [group] : [],
                  recurring: r,
                });
              }} />
            ))}
          </div>
        </div>
      )}

      {/* Online now */}
      {onlineFriends.length > 0 && (
        <div style={{ marginBottom: 22 }}>
          <SectionHead title={t('jetzt_online')} />
          <div style={{
            display: 'flex', gap: 10, overflowX: 'auto',
            margin: '0 -16px', padding: '4px 16px',
            scrollbarWidth: 'none',
          }}>
            {onlineFriends.map(f => (
              <div key={f.id} style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                gap: 6, flexShrink: 0,
              }}>
                <Avatar id={f.id} size={52} showStatus />
                <span style={{
                  fontFamily: 'Space Grotesk, system-ui', fontSize: 12,
                  color: 'var(--text)', fontWeight: 500,
                }}>{f.name}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Upcoming overlap suggestions */}
      {upcoming.length > 0 && (
        <>
          <SectionHead title={t('vorschlaege')} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {upcoming.map((s, i) => (
              <SessionRow key={i} session={s} onClick={() => onOpenSession(s)} onReactivate={onReactivate} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function TonightHero({ tonight, myStatus, onOpenSession }) {
  const t = window.t;
  const [, bumpReady] = React.useReducer(x => x + 1, 0);
  const readyActive = window.sessionReadyCheckActive?.(tonight);
  const readyTargets = readyActive ? window.sessionReadyTargets(tonight) : [];
  const readyCount = readyActive ? window.sessionReadyCount(tonight) : null;
  const askReady = async (e) => {
    e.stopPropagation();
    await window.fbRequestReadyCheck?.(tonight);
    const n = window.sessionReadyTargets(tonight).filter(id => id !== 'me').length;
    window.zockerToast?.({ title: t('ready_sent_title'), body: t('ready_sent_body', n) });
    bumpReady();
  };
  const STATUS_META = {
    in:    { label: t('bin_dabei'),  color: 'var(--accent)', mark: '✓ ' },
    maybe: { label: t('maybe'),      color: 'var(--violet)', mark: '' },
    out:   { label: t('kann_nicht'), color: 'var(--pink)',   mark: '' },
  };
  const statusColor = STATUS_META[myStatus]?.color || 'var(--accent)';
  return (
    <Card style={{
      background: `linear-gradient(155deg, color-mix(in oklab, ${statusColor} 14%, var(--surface)) 0%, var(--surface) 60%)`,
      borderColor: `color-mix(in oklab, ${statusColor} 30%, var(--border))`,
      padding: 18,
    }} onClick={() => onOpenSession(tonight)}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          color: statusColor, fontFamily: 'Space Grotesk, system-ui',
          fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase',
        }}>
          <span style={{
            width: 7, height: 7, borderRadius: '50%', background: statusColor,
            boxShadow: `0 0 10px ${statusColor}`, animation: 'pulse 2s infinite',
          }} />
          {t('heute_abend')}
        </div>
        {tonight.groups && tonight.groups.length > 0 && (
          <GroupBadges groups={tonight.groups} max={2} />
        )}
      </div>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14,
      }}>
        <Mono size={32} color="var(--text)" style={{ fontWeight: 600, letterSpacing: -1 }}>
          {window.fmtHour(tonight.from)}
        </Mono>
        <span style={{ color: 'var(--muted)', fontSize: 16 }}>–</span>
        <Mono size={20} color="var(--muted)">{window.fmtHour(tonight.to)}</Mono>
      </div>

      {tonight.topGame && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: 10, borderRadius: 14,
          background: 'var(--bg-deep)',
          border: '1px solid var(--border)',
          marginBottom: 12,
        }}>
          <GameCover game={tonight.topGame} size={48} rounded={10} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'Space Grotesk, system-ui', fontSize: 16, fontWeight: 600,
              color: 'var(--text)', marginBottom: 2,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{tonight.topGame.title}</div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: 'var(--muted)',
            }}>
              {tonight.topVotes}/{tonight.friends.length} {t('stimmen')} · {tonight.topGame.tag}
            </div>
          </div>
          <MoodBadge mood="chill" />
        </div>
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <AvatarStack ids={tonight.friends} size={28} />
          <span style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 13, color: 'var(--muted)',
          }}>
            {t('n_dabei', tonight.friends.length)}
          </span>
        </div>
        <div style={{
          fontFamily: 'Space Grotesk, system-ui', fontSize: 14, fontWeight: 700,
          color: STATUS_META[myStatus]?.color || 'var(--accent)',
        }}>{(STATUS_META[myStatus]?.mark || '') + (STATUS_META[myStatus]?.label || t('bin_dabei'))}</div>
      </div>

      {/* Optional readiness check — ask the crew if they're ready right now */}
      <div style={{ marginTop: 14, borderTop: '1px solid var(--border)', paddingTop: 14 }}>
        {readyActive ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              {readyTargets.slice(0, 6).map(fid => {
                const meta = window.readyStatusMeta(window.sessionReadyStatus(tonight, fid));
                return <Avatar key={fid} id={fid} size={28} ringColor={meta.color} />;
              })}
            </div>
            <span style={{
              flex: 1, fontFamily: 'Space Grotesk, system-ui', fontSize: 12, fontWeight: 600,
              color: 'var(--muted)',
            }}>{t('ready_check')} · {t('ready_count', readyCount.ready, readyCount.total)}</span>
          </div>
        ) : (
          <button onClick={askReady} style={{
            appearance: 'none', cursor: 'pointer', width: '100%',
            padding: '10px 12px', borderRadius: 12,
            background: 'color-mix(in oklab, var(--accent) 12%, transparent)',
            border: '1px solid color-mix(in oklab, var(--accent) 38%, var(--border))',
            color: 'var(--accent)',
            fontFamily: 'Space Grotesk, system-ui', fontSize: 13, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 15 }}>⚡</span>{t('ready_check_btn')}
          </button>
        )}
      </div>
    </Card>
  );
}

function InviteBanner({ onOpenAddFriend }) {
  const t = window.t;
  return (
    <Card style={{
      background: `linear-gradient(155deg, color-mix(in oklab, var(--accent) 16%, var(--surface)) 0%, color-mix(in oklab, var(--violet) 10%, var(--surface)) 100%)`,
      borderColor: 'color-mix(in oklab, var(--accent) 30%, var(--border))',
      padding: 18, marginBottom: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 13, flexShrink: 0,
          background: 'color-mix(in oklab, var(--accent) 18%, transparent)',
          color: 'var(--accent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
            <circle cx="9" cy="7" r="4" />
            <path d="M19 8v6M22 11h-6" />
          </svg>
        </div>
        <div style={{
          fontFamily: 'Space Grotesk, system-ui', fontSize: 18, fontWeight: 700,
          color: 'var(--text)', letterSpacing: -0.3,
        }}>{t('no_matches_title')}</div>
      </div>
      <div style={{
        fontFamily: 'Space Grotesk, system-ui', fontSize: 13, lineHeight: 1.55,
        color: 'var(--muted)', marginBottom: 14,
      }}>{t('no_matches_body')}</div>
      <Button full onClick={onOpenAddFriend}>{t('invite_now')}</Button>
    </Card>
  );
}

function GroupFilter({ active, onChange }) {
  const t = window.t;
  return (
    <div style={{
      display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none',
      margin: '0 -16px 16px', padding: '0 16px',
    }}>
      <Chip color="mint" active={active === 'all'} onClick={() => onChange('all')}>
        ◎ {t('alle_gruppen')}
      </Chip>
      {window.groupsByPriority().map(g => (
        <Chip key={g.id} color="mint" active={active === g.id} onClick={() => onChange(active === g.id ? 'all' : g.id)} style={{
          color: active === g.id ? `oklch(0.85 0.16 ${g.hue})` : undefined,
          background: active === g.id ? `oklch(0.85 0.16 ${g.hue} / 0.12)` : undefined,
          borderColor: active === g.id ? `oklch(0.85 0.16 ${g.hue} / 0.3)` : undefined,
        }}>
          <span style={{ marginRight: 6, opacity: 0.9 }}>{g.glyph}</span>
          {window.groupName(g)}
        </Chip>
      ))}
    </div>
  );
}

function GroupBadges({ groups, max = 3 }) {
  const shown = groups.slice(0, max);
  const extra = groups.length - shown.length;
  return (
    <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
      {shown.map(g => (
        <span key={g.id} title={window.groupName(g)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          fontFamily: 'Space Grotesk, system-ui', fontSize: 10, fontWeight: 700,
          letterSpacing: 0.4, textTransform: 'uppercase',
          color: `oklch(0.85 0.16 ${g.hue})`,
          padding: '2px 7px', borderRadius: 999,
          background: `oklch(0.85 0.16 ${g.hue} / 0.12)`,
          border: `1px solid oklch(0.85 0.16 ${g.hue} / 0.3)`,
          whiteSpace: 'nowrap',
        }}>
          <span>{g.glyph}</span>
          {window.groupName(g)}
        </span>
      ))}
      {extra > 0 && (
        <span style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700,
          color: 'var(--muted)',
          padding: '2px 6px', borderRadius: 999,
          background: 'var(--surface-2)',
          border: '1px solid var(--border)',
        }}>+{extra}</span>
      )}
    </div>
  );
}

function RecurringRow({ item, onOpen }) {
  const t = window.t;
  const game  = window.GAMES_BY_ID[item.gameId];
  const group = window.GROUPS_BY_ID[item.groupId];
  if (!group || !game) return null; // group/game not loaded yet
  const isToday = item.dayOffset === 0;
  const dow = window.dayLabelsShort()[item.dow];
  const dayLabel = isToday ? t('heute') : item.dayOffset === 1 ? t('morgen') : dow;
  const name = (window.__LANG || 'de') === 'en' ? item.nameEn : item.nameDe;
  return (
    <Card onClick={onOpen} style={{
      padding: 12,
      background: 'linear-gradient(95deg, color-mix(in oklab, var(--violet) 10%, var(--surface)) 0%, var(--surface) 70%)',
      borderColor: 'color-mix(in oklab, var(--violet) 25%, var(--border))',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, flexShrink: 0,
          background: `oklch(0.3 0.06 ${group.hue})`,
          color: `oklch(0.88 0.16 ${group.hue})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 22,
          border: `1px solid oklch(0.85 0.16 ${group.hue} / 0.4)`,
        }}>{group.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4,
          }}>
            <span style={{
              fontFamily: 'Space Grotesk, system-ui', fontSize: 15, fontWeight: 600,
              color: 'var(--text)',
            }}>{name}</span>
            <span style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9, fontWeight: 600,
              letterSpacing: 0.8, textTransform: 'uppercase',
              color: 'var(--violet)',
              padding: '2px 6px', borderRadius: 999,
              background: 'color-mix(in oklab, var(--violet) 15%, transparent)',
              border: '1px solid color-mix(in oklab, var(--violet) 30%, transparent)',
            }}>↻ {t('recurring')}</span>
          </div>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
            color: 'var(--muted)',
          }}>
            {dayLabel} · {window.fmtHour(item.from)}–{window.fmtHour(item.to)} · {game.title}
          </div>
        </div>
        <AvatarStack ids={item.confirmed} size={22} max={3} />
      </div>
    </Card>
  );
}

function QuickAction({ label, desc, icon, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer', textAlign: 'left',
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 18, padding: 14,
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 10,
        background: 'color-mix(in oklab, var(--accent) 16%, transparent)',
        color: 'var(--accent)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{icon}</div>
      <div>
        <div style={{
          fontFamily: 'Space Grotesk, system-ui', fontSize: 15, fontWeight: 600,
          color: 'var(--text)',
        }}>{label}</div>
        <div style={{
          fontFamily: 'Space Grotesk, system-ui', fontSize: 12,
          color: 'var(--muted)', marginTop: 2,
        }}>{desc}</div>
      </div>
    </button>
  );
}

function SessionRow({ session, onClick, onReactivate }) {
  const t = window.t;
  const dow = window.dayLabelsShort()[session.dow];
  const isToday = session.dayOffset === 0;
  const isTomorrow = session.dayOffset === 1;
  const dayLabel = isToday ? t('heute') : isTomorrow ? t('morgen') : dow;
  const declined = session.autoDeclined;
  return (
    <Card onClick={onClick} style={{
      padding: 12, display: 'flex', flexDirection: 'column', gap: declined ? 10 : 0,
      borderColor: declined ? 'color-mix(in oklab, var(--pink) 25%, var(--border))' : undefined,
    }}>
      {/* Main row — dimmed when the session is auto-declined */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        opacity: declined ? 0.5 : 1,
      }}>
        <div style={{
          width: 50, textAlign: 'center', flexShrink: 0,
          borderRight: '1px solid var(--border)', paddingRight: 12, marginRight: 2,
        }}>
          <div style={{
            fontFamily: 'Space Grotesk, system-ui', fontSize: 10, fontWeight: 600,
            color: 'var(--muted)', letterSpacing: 1, textTransform: 'uppercase',
          }}>{dayLabel}</div>
          <Mono size={11} color="var(--muted)" style={{ marginTop: 2, display: 'block' }}>
            {window.fmtHour(session.from)}
          </Mono>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
          }}>
            {session.topGame && <GameCover game={session.topGame} size={28} rounded={6} />}
            <div style={{
              fontFamily: 'Space Grotesk, system-ui', fontSize: 14, fontWeight: 600,
              color: 'var(--text)',
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              flex: 1,
            }}>{session.topGame ? session.topGame.title : t('noch_kein_pick')}</div>
            {session.groups && session.groups[0] && (
              <span style={{
                fontFamily: 'Space Grotesk, system-ui', fontSize: 9, fontWeight: 700,
                letterSpacing: 0.4, textTransform: 'uppercase',
                color: `oklch(0.85 0.16 ${session.groups[0].hue})`,
                padding: '2px 6px', borderRadius: 999,
                background: `oklch(0.85 0.16 ${session.groups[0].hue} / 0.12)`,
                border: `1px solid oklch(0.85 0.16 ${session.groups[0].hue} / 0.3)`,
                flexShrink: 0,
              }}>{session.groups[0].glyph}</span>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <AvatarStack ids={session.friends} size={20} max={5} />
            <Mono size={11} color="var(--muted)">
              {window.fmtHour(session.from)}–{window.fmtHour(session.to)}
            </Mono>
          </div>
        </div>
      </div>

      {/* Decline footer — kept on its own row so nothing overlaps */}
      {declined && (
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 10, flexWrap: 'wrap',
          borderTop: '1px solid var(--border)', paddingTop: 10,
        }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0,
            fontFamily: 'Space Grotesk, system-ui', fontSize: 12, fontWeight: 600,
            color: 'var(--pink)',
          }}>
            <span style={{ flexShrink: 0 }}>✕</span>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {session.declinedBy ? t('declined_by', window.groupName(session.declinedBy)) : t('auto_declined')}
            </span>
          </span>
          {onReactivate && (
            <button type="button" onClick={(e) => { e.stopPropagation(); onReactivate(session); }} style={{
              appearance: 'none', cursor: 'pointer', flexShrink: 0,
              padding: '7px 14px', borderRadius: 999,
              background: 'color-mix(in oklab, var(--accent) 12%, transparent)',
              border: '1px solid color-mix(in oklab, var(--accent) 45%, var(--border))',
              color: 'var(--accent)',
              fontFamily: 'Space Grotesk, system-ui', fontSize: 12, fontWeight: 700,
              whiteSpace: 'nowrap',
            }}>{t('reactivate')}</button>
          )}
        </div>
      )}
    </Card>
  );
}

function IconClock() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 2" />
    </svg>
  );
}
function IconCalendar() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M8 3v4M16 3v4M3 10h18" />
    </svg>
  );
}

Object.assign(window, { ScreenHeute, IconClock, IconCalendar, GroupFilter, GroupBadges, InviteBanner });
