
"use client";

import { motion, AnimatePresence } from 'motion/react';
import { ActiveFilters } from '@/components/active-filters';
import { LanguageSwitch } from '@/components/language-switch';
import { useTranslation } from '@/lib/i18n/context';

interface Participant {
  id: number;
  display_name: string | null;
  is_creator: number;
  is_active: number;
  vetos_used: number;
}

interface SessionInfoSheetProps {
  visible: boolean;
  onClose: () => void;
  code: string;
  session: any;
  participants: Participant[];
  myParticipantId: number | null;
  iAmCreator: boolean;
  onKick: (participantId: number) => void;
  onInvite: () => void;
  onLeave: () => void;
}

function getInitials(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '?';
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[1][0]).toUpperCase();
}

/**
 * Buendelt Session-Filter, Teilnehmerliste UND die Session-weiten Aktionen
 * (Einladen, Verlassen, Sprachwahl) in einem Popup, geoeffnet ueber den
 * Drei-Punkte-Button im Session-Header.
 *
 * BUGFIX (zwei Runden): sowohl die dicke Pink-Umrandung als auch die pinke,
 * fette Vetos-Zahl waren faelschlicherweise an isHost gekoppelt statt an
 * isMe - der Gruppenleiter sah dadurch IMMER wie "du" aus, auch wenn eine
 * andere Person Host ist. Jetzt konsequent zwei unabhaengige Signale:
 *  - "Das bist du" (isMe): solide Zeile + dicke Pink-Umrandung + Glow +
 *    fette pinke Vetos-Zahl.
 *  - "Host" (isHost): Verlaufs-Avatar (Pink->Teal) + Krone-Icon.
 * Beide koennen unabhaengig voneinander zutreffen oder auch gar nicht.
 */
export function SessionInfoSheet({
  visible, onClose, code, session, participants, myParticipantId, iAmCreator, onKick, onInvite, onLeave,
}: SessionInfoSheetProps) {
  const { t } = useTranslation();
  const activeParticipants = participants.filter((p) => p.is_active === 1);

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/70 backdrop-blur-sm p-0 sm:p-4"
          onClick={onClose}
        >
          <motion.div
            initial={{ y: 40, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 40, opacity: 0 }}
            transition={{ type: 'spring', stiffness: 260, damping: 26 }}
            onClick={(e) => e.stopPropagation()}
            className="w-full sm:max-w-md max-h-[85vh] overflow-y-auto bg-neutral-900 border border-white/10 rounded-t-3xl sm:rounded-3xl shadow-2xl flex flex-col relative safe-bottom"
          >
            <div
              aria-hidden
              className="absolute top-0 left-0 w-full h-32 bg-gradient-to-b from-yumder-teal/10 to-transparent pointer-events-none rounded-t-3xl"
            />
            <div className="w-8 h-1.5 rounded-full bg-neutral-700 mx-auto mt-2 mb-1 sm:hidden relative z-10" />
            <div className="p-5 flex flex-col gap-4 relative z-10">
              <div className="flex items-center justify-between gap-2">
                <div
                  className="flex items-center gap-2 rounded-full px-4 py-1.5 bg-neutral-900"
                  style={{
                    background: 'linear-gradient(#0a0a0a, #0a0a0a) padding-box, linear-gradient(90deg, #FE3C72, #ec4899, #00C2A8) border-box',
                    border: '1.5px solid transparent',
                  }}
                >
                  <span className="text-xs text-neutral-400 font-medium tracking-wider uppercase">{t.matchHistory.sessionLabel}</span>
                  <span className="font-bold tracking-widest text-white">{code}</span>
                </div>
                <div className="flex items-center gap-3">
                  <LanguageSwitch />
                  <button
                    type="button"
                    onClick={onClose}
                    className="bg-neutral-800 hover:bg-neutral-700 text-neutral-400 hover:text-white rounded-full p-2 transition-colors"
                    aria-label={t.sessionInfo.closeAriaLabel}
                  >
                    <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
              </div>

              {session && <ActiveFilters session={session} />}

              <div className="flex flex-col gap-3">
                <p className="text-xs font-bold text-neutral-400 uppercase tracking-widest pl-1">
                  {t.sessionInfo.participantsHeading(activeParticipants.length)}
                </p>
                <ul className="flex flex-col gap-2 list-none m-0 p-0">
                  {activeParticipants.map((p) => {
                    const isMe = p.id === myParticipantId;
                    const isHost = p.is_creator === 1;
                    const displayName = p.display_name || t.sessionInfo.guestFallbackName;
                    const initials = getInitials(displayName);
                    const usesTealAvatar = p.id % 2 === 0;

                    return (
                      <li
                        key={p.id}
                        className={
                          isMe
                            ? 'rounded-2xl px-4 py-3 flex items-center justify-between border border-yumder-pink bg-neutral-900 shadow-[0_0_15px_rgba(254,60,114,0.05)]'
                            : 'rounded-xl border border-white/5 bg-neutral-800 px-4 py-3 flex items-center justify-between hover:bg-neutral-700 transition-colors'
                        }
                      >
                        <div className="flex items-center gap-3">
                          <div
                            className={
                              isHost
                                ? 'w-10 h-10 shrink-0 rounded-full bg-gradient-to-tr from-yumder-pink via-pink-400 to-yumder-teal text-white flex items-center justify-center font-bold shadow-md'
                                : `w-10 h-10 shrink-0 rounded-full flex items-center justify-center font-bold ${
                                    usesTealAvatar
                                      ? 'bg-yumder-teal text-neutral-900'
                                      : 'bg-yumder-pink text-white'
                                  }`
                            }
                          >
                            {initials}
                          </div>
                          <div className="flex items-center flex-wrap gap-1.5">
                            <span className={isMe ? 'font-bold text-neutral-100' : 'font-semibold text-neutral-300'}>
                              {displayName}
                            </span>
                            {isMe && (
                              <span className="text-xs text-neutral-500 font-medium whitespace-nowrap">
                                {t.sessionInfo.youSuffix}
                              </span>
                            )}
                            {isHost && (
                              <svg
                                viewBox="0 0 24 24"
                                className="w-4 h-4 text-yellow-500 drop-shadow-sm ml-0.5"
                                fill="currentColor"
                                aria-hidden="true"
                              >
                                <title>{t.sessionInfo.hostBadgeLabel}</title>
                                <path d="M5 16L3 5L8.5 10L12 4L15.5 10L21 5L19 16H5ZM19 19C19 19.5523 18.5523 20 18 20H6C5.44772 20 5 19.5523 5 19V18H19V19Z" />
                              </svg>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-3 shrink-0">
                          <span className={isMe ? 'text-sm font-bold text-yumder-pink' : 'text-sm font-medium text-neutral-400'}>
                            {t.sessionInfo.vetosUsedOf3(p.vetos_used)}
                          </span>
                          {iAmCreator && !isMe && (
                            <button
                              onClick={() => onKick(p.id)}
                              className="text-neutral-500 hover:text-yumder-pink hover:-translate-y-0.5 hover:scale-105 transition-all duration-200"
                              aria-label={t.sessionInfo.removeButton}
                              title={t.sessionInfo.removeButton}
                            >
                              <svg viewBox="0 0 24 24" className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M13 7a4 4 0 11-8 0 4 4 0 018 0zM9 14a6 6 0 00-6 6v1h12v-1a6 6 0 00-6-6zM21 12h-6" />
                              </svg>
                            </button>
                          )}
                        </div>
                      </li>
                    );
                  })}
                </ul>
              </div>

              <div className="flex flex-col gap-3 mt-2">
                <motion.button
                  onClick={onInvite}
                  whileTap={{ scale: 0.97 }}
                  className="w-full flex items-center justify-center gap-2 text-sm font-bold bg-yumder-teal text-neutral-900 rounded-xl py-3.5 px-4 shadow-[0_0_20px_rgba(0,194,168,0.3)] hover:-translate-y-0.5 hover:scale-[1.02] transition-all duration-200"
                >
                  <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M15 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
                    <circle cx="8.5" cy="7" r="4" />
                    <path d="M19 8v6" />
                    <path d="M16 11h6" />
                  </svg>
                  {t.session.inviteButton}
                </motion.button>
                <motion.button
                  onClick={onLeave}
                  whileTap={{ scale: 0.97 }}
                  className="w-full flex items-center justify-center gap-2 text-sm font-semibold bg-neutral-900 border border-yumder-pink text-yumder-pink rounded-xl py-3.5 px-4 shadow-[0_0_15px_rgba(254,60,114,0.05)] hover:bg-neutral-800 hover:-translate-y-0.5 hover:scale-[1.02] transition-all duration-200"
                >
                  <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                    <polyline points="16 17 21 12 16 7" />
                    <line x1="21" y1="12" x2="9" y2="12" />
                  </svg>
                  {t.session.leaveSessionButton}
                </motion.button>
              </div>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
