import React, { useCallback, useContext, useEffect, useMemo, useState } from "react";
import reviewingstyles from "@/styles/reviewing.module.css";
import Button from "@/components/Button";
import Popup from "@/components/PopUp";
import ZoomInMapIcon from "@mui/icons-material/ZoomInMap";
import { ReviewCriteria, ReviewState, SettingsState, SessionState, WsEvent, VoteType } from "@/lib/SessionData/Enums";
import type {
    Initalisation,
    ReviewCounts,
    ReviewUpdatePayload,
    VoteData,
    Update,
    WsData,
    User,
} from "@/lib/SessionData/Interfaces";
import { SessionHandlerContext } from "./Session";
import { useRouter } from "next/router";

const defaultCounts: ReviewCounts = { dreamer: 0, realist: 0, critic: 0 };
const defaultVotesForIdea: Record<ReviewCriteria, string | null> = {
    dreamer: null,
    realist: null,
    critic: null,
};

// Helper function to convert ReviewCriteria to VoteType
const criteriaToVoteType = (criteria: ReviewCriteria): VoteType => {
    switch (criteria) {
        case ReviewCriteria.Dreamer:
            return VoteType.Dreamer;
        case ReviewCriteria.Realist:
            return VoteType.Realist;
        case ReviewCriteria.Critic:
            return VoteType.Critic;
    }
};

// Helper function to convert VoteType to ReviewCriteria field name
const voteTypeToField = (voteType: VoteType): keyof ReviewCounts => {
    switch (voteType) {
        case VoteType.Dreamer:
            return 'dreamer';
        case VoteType.Realist:
            return 'realist';
        case VoteType.Critic:
            return 'critic';
        default:
            return 'critic';
    }
};

// Extract ideaId from sketchId (format: ideaId-imgIndex)
const extractIdeaId = (sketchId: string): string => {
    const lastDashIndex = sketchId.lastIndexOf('-');
    if (lastDashIndex === -1) return sketchId;
    return sketchId.substring(0, lastDashIndex);
};

const criteriaConfig = [
    {
        key: ReviewCriteria.Dreamer,
        label: "Träumer",
        title: "Träumer",
        lines: [
            "Welche Idee begeistert dich am meisten?",
            "Welche Idee hat das größte Potenzial, die Zukunft zu verändern?",
            "Kreativität, Mut, Inspiration.",
        ],
        icon: (
            <svg
                className={reviewingstyles.ratingIcon}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            >
                <path d="M12 2l2.4 6.1 6.6.5-5 4.2 1.6 6.4L12 15.8 6.4 19.2 8 12.8 3 8.6l6.6-.5L12 2z" />
            </svg>
        ),
    },
    {
        key: ReviewCriteria.Realist,
        label: "Realist",
        title: "Realist",
        lines: [
            "Welche Idee ist am praktikabelsten?",
            "Welche hat die größte Chance auf erfolgreiche Umsetzung?",
            "Machbarkeit, Ressourcen, Zeitrahmen.",
        ],
        icon: (
            <svg
                className={reviewingstyles.ratingIcon}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            >
                <circle cx="12" cy="12" r="9" />
                <path d="M8 12l3 3 5-5" />
            </svg>
        ),
    },
    {
        key: ReviewCriteria.Critic,
        label: "Kritiker",
        title: "Kritiker",
        lines: [
            "Welche Idee hat die größten Risiken oder Schwächen?",
            "Welche Idee sollte man eher kritisch hinterfragen?",
            "Logik, Risiko, Nachhaltigkeit.",
        ],
        icon: (
            <svg
                className={reviewingstyles.ratingIcon}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            >
                <path d="M12 2l9 16H3L12 2z" />
                <path d="M12 9v4" />
                <path d="M12 17h.01" />
            </svg>
        ),
    },
];

function Reviewing({
    sessionId,
    onEndSession,
    isPdfMode = false,
    pdfData,
}: {
    sessionId: string;
    onEndSession?: () => void;
    isPdfMode?: boolean;
    pdfData?: {
        topic: string;
        users: User[];
        ideas: Array<{ id: string; images: string[]; ownerIndex: number }>;
        reviewCounts: Record<string, ReviewCounts>;
    };
}) {
    const [activeSlide, setActiveSlide] = useState(0);
    const [topic, setTopic] = useState(pdfData?.topic || "Themenüberschrift");
    const [reviewCounts, setReviewCounts] = useState<Record<string, ReviewCounts>>(pdfData?.reviewCounts || {});
    // userVotes is now per-idea: Record<ideaId, Record<criteria, sketchId>>
    const [userVotes, setUserVotes] = useState<Record<string, Record<ReviewCriteria, string | null>>>({});
    const [ideas, setIdeas] = useState<Array<{ id: string; images: string[]; ownerIndex: number }>>(pdfData?.ideas || []);
    const [users, setUsers] = useState<Array<User>>(pdfData?.users || []);
    const [showEndPopup, setShowEndPopup] = useState(false);
    const [pdfLoading, setPdfLoading] = useState(false);
    const [pdfError, setPdfError] = useState<string | null>(null);
    const [showPdfProgressPopup, setShowPdfProgressPopup] = useState(false);
    const [pdfProgress, setPdfProgress] = useState(0);
    const [pdfProgressMode, setPdfProgressMode] = useState<'export' | 'end'>('export');
    const slides = useMemo(() => Array.from({ length: ideas.length }, (_, index) => index), [ideas]);
    const [lightbox, setLightbox] = useState<{ src: string; drawingId: string } | null>(null);
    const sessionHandler = useContext(SessionHandlerContext);
    const router = useRouter();
    const maxCountsByCriteria = useMemo(() => {
        const maxes: ReviewCounts = { dreamer: 0, realist: 0, critic: 0 };
        ideas.forEach((idea) => {
            idea.images.forEach((_, imgIndex) => {
                const drawingId = `${idea.id}-${imgIndex}`;
                const counts = reviewCounts[drawingId];
                if (!counts) return;
                if (counts.dreamer > maxes.dreamer) maxes.dreamer = counts.dreamer;
                if (counts.realist > maxes.realist) maxes.realist = counts.realist;
                if (counts.critic > maxes.critic) maxes.critic = counts.critic;
            });
        });
        return maxes;
    }, [ideas, reviewCounts]);

    // Request initialization data immediately when the component mounts (nur wenn nicht im PDF-Modus)
    useEffect(() => {
        if (isPdfMode) return; // PDF-Modus hat bereits Daten
        if (!sessionHandler) return;
        sessionHandler.sendEvent({
            event: WsEvent.RequestInit,
            data: {
                type: SessionState.Loading,
                value: null,
            },
            message: null,
            error: null,
        });
    }, [sessionHandler, isPdfMode]);

    useEffect(() => {
        if (isPdfMode) return; // PDF-Modus braucht keinen visibility listener
        if (!sessionHandler) return;
        const handleVisibilityChange = () => {
            if (document.visibilityState === 'visible') {
                sessionHandler.sendEvent({
                    event: WsEvent.RequestInit,
                    data: {
                        type: SessionState.Loading,
                        value: null,
                    },
                    message: null,
                    error: null,
                });
            }
        };
        document.addEventListener('visibilitychange', handleVisibilityChange);
        return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
    }, [sessionHandler, isPdfMode]);

    const handleWsData = useCallback((wsData: WsData) => {
        if (wsData.event === WsEvent.Initalisation) {
            const data = wsData.data as Initalisation;
            setReviewCounts(data.review?.counts ?? ({} as Record<string, ReviewCounts>));
            // userVotes is now per-idea
            const incomingVotes = data.review?.userVotes ?? {};
            setUserVotes(incomingVotes as Record<string, Record<ReviewCriteria, string | null>>);
            if (data.settings?.topic) {
                setTopic(data.settings.topic);
            }
            if (data.ideas) {
                setIdeas(data.ideas);
            }
            if (data.users) {
                setUsers(data.users);
            }
            return;
        }

        if (wsData.event === WsEvent.SettingUpdate) {
            const update = wsData.data as Update;
            if (update.type === SettingsState.Topic && typeof update.value === "string") {
                setTopic(update.value);
            }
            return;
        }
        if (wsData.event !== WsEvent.ReviewUpdate) return;
        const update = wsData.data as Update;
        
        // Handle VoteAdd events
        if (update.type === ReviewState.VoteAdd) {
            const voteData = update.value as VoteData;
            const field = voteTypeToField(voteData.type);
            const ideaId = extractIdeaId(voteData.sketchId);
            setReviewCounts((prev) => ({
                ...prev,
                [voteData.sketchId]: {
                    ...defaultCounts,
                    ...prev[voteData.sketchId],
                    [field]: (prev[voteData.sketchId]?.[field] ?? 0) + 1,
                },
            }));
            // Update userVotes if this is my own vote (per idea)
            if (sessionHandler && voteData.userId === sessionHandler.getClientId()) {
                setUserVotes((prev) => ({
                    ...prev,
                    [ideaId]: {
                        ...defaultVotesForIdea,
                        ...prev[ideaId],
                        [field]: voteData.sketchId,
                    },
                }));
            }
            return;
        }
        
        // Handle VoteRemove events
        if (update.type === ReviewState.VoteRemove) {
            const voteData = update.value as VoteData;
            const field = voteTypeToField(voteData.type);
            const ideaId = extractIdeaId(voteData.sketchId);
            setReviewCounts((prev) => ({
                ...prev,
                [voteData.sketchId]: {
                    ...defaultCounts,
                    ...prev[voteData.sketchId],
                    [field]: Math.max(0, (prev[voteData.sketchId]?.[field] ?? 1) - 1),
                },
            }));
            // Update userVotes if this is my own vote (per idea)
            if (sessionHandler && voteData.userId === sessionHandler.getClientId()) {
                setUserVotes((prev) => ({
                    ...prev,
                    [ideaId]: {
                        ...defaultVotesForIdea,
                        ...prev[ideaId],
                        [field]: null,
                    },
                }));
            }
            return;
        }
        
        // Handle Sync events (for full state updates)
        if (update.type !== ReviewState.Sync) return;
        const payload = update.value as ReviewUpdatePayload | null;
        if (!payload) return;
        setReviewCounts((prev) => ({
            ...prev,
            [payload.drawingId]: payload.counts,
        }));
    }, [sessionHandler]);

    useEffect(() => {
        if (!sessionHandler) return;
        sessionHandler.registerListener(
            [WsEvent.Initalisation, WsEvent.SettingUpdate, WsEvent.ReviewUpdate],
            handleWsData,
        );
    }, [sessionHandler, handleWsData]);

    const goToSlide = (index: number) => {
        const normalized = (index + slides.length) % slides.length;
        setActiveSlide(normalized);
    };

    const handleVote = async (drawingId: string, criteria: ReviewCriteria) => {
        if (!sessionHandler) return;
        const ideaId = extractIdeaId(drawingId);
        const currentlySelected = userVotes[ideaId]?.[criteria];
        const isDeselecting = currentlySelected === drawingId;
        
        // Kein lokales Update - Button wird erst aktiviert wenn Server-Antwort kommt
        if (isDeselecting) {
            // Server-Event senden: VoteRemove
            sessionHandler.sendEvent({
                event: WsEvent.ReviewUpdate,
                data: {
                    type: ReviewState.VoteRemove,
                    value: {
                        userId: sessionHandler.getClientId() || "",
                        sketchId: drawingId,
                        type: criteriaToVoteType(criteria),
                    } as VoteData,
                } as Update,
                message: null,
                error: null,
            });
        } else {
            // Server-Event senden: VoteAdd - der Server handhabt die Abwahl des alten Votes automatisch
            sessionHandler.sendEvent({
                event: WsEvent.ReviewUpdate,
                data: {
                    type: ReviewState.VoteAdd,
                    value: {
                        userId: sessionHandler.getClientId() || "",
                        sketchId: drawingId,
                        type: criteriaToVoteType(criteria),
                    } as VoteData,
                } as Update,
                message: null,
                error: null,
            });
        }
    };

    const handleDownloadPdf = useCallback(async (opts?: { silent?: boolean; mode?: 'export' | 'end' }) => {
        setPdfError(null);
        setPdfLoading(true);
        setPdfProgress(0);
        setPdfProgressMode(opts?.mode ?? 'export');
        setShowPdfProgressPopup(true);
        
        // Starte die Progress-Animation (30 Sekunden = 30000ms)
        const progressDuration = 30000;
        const progressInterval = 100; // Update alle 100ms
        const progressStep = 100 / (progressDuration / progressInterval);
        
        const progressTimer = setInterval(() => {
            setPdfProgress((prev) => {
                const next = prev + progressStep;
                if (next >= 99) {
                    return 99; // Stoppe bei 99% bis PDF fertig ist
                }
                return next;
            });
        }, progressInterval);
        
        try {
            const res = await fetch("/api/session/pdf", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    code: sessionId,
                    token: sessionHandler?.getWsClientToken(),
                }),
            });
            if (!res.ok) {
                const json = await res.json().catch(() => null);
                throw new Error(json?.message ?? "PDF-Erstellung fehlgeschlagen");
            }
            const json = await res.json();
            const pdfPath = json?.path;
            
            // Progress auf 100% setzen und Timer stoppen
            clearInterval(progressTimer);
            setPdfProgress(100);
            
            // Kurz warten damit der User 100% sieht, dann Popup schließen
            await new Promise((resolve) => setTimeout(resolve, 500));
            setShowPdfProgressPopup(false);
            setPdfProgress(0);
            
            if (!opts?.silent && pdfPath && typeof window !== "undefined") {
                window.open(pdfPath, "_blank", "noopener");
            }
        } catch (err) {
            clearInterval(progressTimer);
            setShowPdfProgressPopup(false);
            setPdfProgress(0);
            setPdfError(err instanceof Error ? err.message : "PDF-Erstellung fehlgeschlagen");
        } finally {
            setPdfLoading(false);
        }
    }, [sessionId, sessionHandler]);

    const handleEndPopupCancel = useCallback(() => {
        setShowEndPopup(false);
    }, []);

    const handleEndPopupConfirm = useCallback(async () => {
        setShowEndPopup(false);
        // automatisch PDF generieren mit Progress-Popup
        await handleDownloadPdf({ silent: true, mode: 'end' });
        onEndSession?.();
        router.push("/");
    }, [handleDownloadPdf, onEndSession, router]);

    return (
        <div className={reviewingstyles.page} data-session-id={sessionId} data-pdf-mode={isPdfMode ? "true" : undefined}>
            <div className={reviewingstyles.noPrint}>
            <div className={reviewingstyles.header}>
                <div className={reviewingstyles.titleGroup}>
                    <h1 className={reviewingstyles.title}>{topic}</h1>
                </div>
                <p className={reviewingstyles.hint}>
                    Bewertet eure Ideen. Nutzt die Kriterien als Orientierung.
                </p>
            </div>

            <div className={reviewingstyles.slider}>
                <div
                    className={reviewingstyles.sliderTrack}
                    style={{ transform: `translateX(-${activeSlide * 100}%)` }}
                >
                    {slides.map((slide) => {
                        const idea = ideas[slide];
                        if (!idea) return null;
                        const ownerName = users[idea.ownerIndex]?.name ?? `Idee ${slide + 1}`;
                        const images = idea.images ?? [];
                        const columns =
                            images.length <= 6 ? 3 :
                            images.length <= 12 ? 4 :
                            4;

                        return (
                            <div className={reviewingstyles.slide} key={slide}>
                                <h2 className={reviewingstyles.ideaTitle}>{ownerName}</h2>
                                <div
                                    className={reviewingstyles.grid}
                                    style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
                                >
                                    {images.map((imageSrc, imgIndex) => {
                                        const drawingId = `${idea.id}-${imgIndex}`;
                                        const counts = reviewCounts[drawingId] ?? defaultCounts;
                                        return (
                                            <div
                                                className={reviewingstyles.placeholder}
                                                key={drawingId}
                                                onClick={() =>
                                                    setLightbox({ src: imageSrc, drawingId })
                                                }
                                            >
                                                {/* eslint-disable-next-line @next/next/no-img-element */}
                                                <img
                                                    src={imageSrc}
                                                    alt={`${ownerName} – Bild ${imgIndex + 1}`}
                                                    className={reviewingstyles.image}
                                                />
                                                <button
                                                    type="button"
                                                    className={reviewingstyles.zoomButton}
                                                    aria-label="Bild vergrößern"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        setLightbox({ src: imageSrc, drawingId });
                                                    }}
                                                >
                                                    <ZoomInMapIcon fontSize="small" className={reviewingstyles.zoomIcon} />
                                                </button>
                                                <div className={reviewingstyles.ratingButtons}>
                                                    {criteriaConfig.map((criteria) => {
                                                        const ideaIdForCheck = extractIdeaId(drawingId);
                                                        const isSelected = userVotes[ideaIdForCheck]?.[criteria.key] === drawingId;
                                                        const count = counts[criteria.key] ?? 0;
                                                        const buttonClass = isSelected
                                                            ? `${reviewingstyles.ratingButton} ${reviewingstyles.ratingButtonActive}`
                                                            : reviewingstyles.ratingButton;
                                                        return (
                                                            <button
                                                                key={`${drawingId}-${criteria.key}`}
                                                                type="button"
                                                                className={buttonClass}
                                                                onClick={(e) => {
                                                                    e.stopPropagation();
                                                                    handleVote(drawingId, criteria.key);
                                                                }}
                                                                aria-label={criteria.label}
                                                                aria-pressed={isSelected}
                                                            >
                                                                {criteria.icon}
                                                                {count > 0 && (
                                                                    <span className={reviewingstyles.ratingCount}>
                                                                        {count}
                                                                    </span>
                                                                )}
                                                                <span className={reviewingstyles.tooltip} aria-hidden="true">
                                                                    <span className={reviewingstyles.tooltipTitle}>
                                                                        {criteria.title}
                                                                    </span>
                                                                    <span className={reviewingstyles.tooltipBody}>
                                                                        {criteria.lines.map((line, index) => (
                                                                            <span
                                                                                key={`${drawingId}-${criteria.key}-${index}`}
                                                                                className={reviewingstyles.tooltipLine}
                                                                            >
                                                                                {line}
                                                                            </span>
                                                                        ))}
                                                                    </span>
                                                                </span>
                                                            </button>
                                                        );
                                                    })}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>

            <div className={reviewingstyles.controls}>
                <div className={reviewingstyles.sliderControls}>
                    <button
                        type="button"
                        className={reviewingstyles.arrowButton}
                        onClick={() => goToSlide(activeSlide - 1)}
                        aria-label="Vorherige Seite"
                    >
                        <svg
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                        >
                            <path d="M15 18l-6-6 6-6" />
                        </svg>
                    </button>
                    <div className={reviewingstyles.dots} role="tablist" aria-label="Reviewing Seiten">
                        {slides.map((slide) => (
                            <button
                                key={`dot-${slide}`}
                                type="button"
                                className={
                                    slide === activeSlide
                                        ? reviewingstyles.dotActive
                                        : reviewingstyles.dot
                                }
                                onClick={() => goToSlide(slide)}
                                aria-label={`Seite ${slide + 1}`}
                                aria-current={slide === activeSlide ? "true" : "false"}
                            />
                        ))}
                    </div>
                    <button
                        type="button"
                        className={reviewingstyles.arrowButton}
                        onClick={() => goToSlide(activeSlide + 1)}
                        aria-label="Nächste Seite"
                    >
                        <svg
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                        >
                            <path d="M9 6l6 6-6 6" />
                        </svg>
                    </button>
                </div>
                <div style={{ display: "flex", gap: "12px", alignItems: "center" }}>
                    <Button
                        variant="secondary"
                        onClick={() => handleDownloadPdf({ mode: 'export' })}
                        disabled={pdfLoading}
                    >
                        {pdfLoading ? "Erstelle PDF..." : "PDF exportieren"}
                    </Button>
                    <Button
                        variant="primary"
                        className={reviewingstyles.endButton}
                        onClick={() => setShowEndPopup(true)}
                    >
                        Session beenden
                    </Button>
                </div>
            </div>
            <Popup
                isOpen={!!lightbox}
                onClose={() => setLightbox(null)}
            >
                {lightbox && (
                    <div className={reviewingstyles.lightboxBody}>
                        <div className={reviewingstyles.lightboxImageWrap}>
                            {/* eslint-disable-next-line @next/next/no-img-element */}
                            <img
                                src={lightbox.src}
                                alt="Zeichnung in Großansicht"
                                className={reviewingstyles.lightboxImage}
                            />
                        </div>
                        <div className={reviewingstyles.lightboxActions}>
                            {criteriaConfig.map((criteria) => {
                                const ideaIdForLightbox = extractIdeaId(lightbox.drawingId);
                                const isSelected = userVotes[ideaIdForLightbox]?.[criteria.key] === lightbox.drawingId;
                                const counts = reviewCounts[lightbox.drawingId] ?? defaultCounts;
                                const count = counts[criteria.key] ?? 0;
                                const buttonClass = isSelected
                                    ? `${reviewingstyles.ratingButton} ${reviewingstyles.ratingButtonActive}`
                                    : reviewingstyles.ratingButton;
                                return (
                                    <button
                                        key={`lb-${lightbox.drawingId}-${criteria.key}`}
                                        type="button"
                                        className={buttonClass}
                                        onClick={() => handleVote(lightbox.drawingId, criteria.key)}
                                        aria-label={criteria.label}
                                        aria-pressed={isSelected}
                                    >
                                        {criteria.icon}
                                        {count > 0 && (
                                            <span className={reviewingstyles.ratingCount}>{count}</span>
                                        )}
                                    </button>
                                );
                            })}
                        </div>
                    </div>
                )}
            </Popup>
            <Popup isOpen={showEndPopup} onClose={handleEndPopupCancel}>
                <div className="flex flex-col gap-4 text-left">
                    <h2 className="text-xl font-semibold">Session beenden</h2>
                    <p>Bist du sicher, dass du die Session beenden möchtest?</p>
                    {pdfError && (
                        <p style={{ color: "red", margin: 0 }}>{pdfError}</p>
                    )}
                    <div style={{ display: "flex", gap: "var(--spacing-md)", justifyContent: "flex-end", marginTop: "var(--spacing-lg)" }}>
                        <Button variant="secondary" onClick={handleEndPopupCancel}>
                            Abbrechen
                        </Button>
                        <Button variant="primary" onClick={handleEndPopupConfirm}>
                            Session beenden
                        </Button>
                    </div>
                </div>
            </Popup>
            <Popup isOpen={showPdfProgressPopup} onClose={() => {}}>
                <div className="flex flex-col gap-4 text-center">
                    <h2 className="text-xl font-semibold">
                        {pdfProgressMode === 'end' ? 'Session wird beendet...' : 'PDF wird erstellt...'}
                    </h2>
                    <p style={{ color: '#666', marginBottom: '8px' }}>
                        {pdfProgressMode === 'end' 
                            ? 'Bitte warte, während das PDF generiert wird.' 
                            : 'Das PDF wird generiert, bitte warte einen Moment.'}
                    </p>
                    <div style={{
                        width: '100%',
                        height: '24px',
                        backgroundColor: '#e0e0e0',
                        borderRadius: '12px',
                        overflow: 'hidden',
                        position: 'relative'
                    }}>
                        <div style={{
                            width: `${pdfProgress}%`,
                            height: '100%',
                            backgroundColor: 'var(--color-primary, #4a90d9)',
                            borderRadius: '12px',
                            transition: 'width 0.1s linear'
                        }} />
                    </div>
                    <p style={{ fontSize: '14px', color: '#888', marginTop: '4px' }}>
                        {Math.round(pdfProgress)}%
                    </p>
                </div>
            </Popup>
            </div>
            <div className={reviewingstyles.printOnly}>
                <h1 className={reviewingstyles.printTitle}>{topic}</h1>
                {ideas.length === 0 && <p>Es sind noch keine Zeichnungen vorhanden.</p>}
                {ideas.map((idea, ideaIndex) => {
                    const ownerName = users[idea.ownerIndex]?.name ?? `Idee ${ideaIndex + 1}`;
                    const images = idea.images ?? [];
                    // Grid-Logik: bis 6 Bilder -> 3 Spalten (2x3), ab 7 -> 4 Spalten
                    const columns = images.length <= 6 ? 3 : 4;
                    return (
                        <div className={reviewingstyles.printIdea} key={`print-${idea.id}`}>
                            <h2 className={reviewingstyles.printIdeaTitle}>{ownerName}</h2>
                            <div
                                className={reviewingstyles.printImages}
                                style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
                            >
                                {images.map((imageSrc, imgIndex) => {
                                    const drawingId = `${idea.id}-${imgIndex}`;
                                    const counts = reviewCounts[drawingId] ?? defaultCounts;
                                    return (
                                        <div className={reviewingstyles.printImageCard} key={`print-${idea.id}-${imgIndex}`}>
                                            {/* eslint-disable-next-line @next/next/no-img-element */}
                                            <img
                                                src={imageSrc}
                                                alt={`${ownerName} – Bild ${imgIndex + 1}`}
                                                className={reviewingstyles.printImage}
                                            />
                                            <div className={reviewingstyles.printCounts}>
                                                {criteriaConfig.map((criteria) => {
                                                    const count = counts[criteria.key] ?? 0;
                                                    const isTop =
                                                        (criteria.key === ReviewCriteria.Dreamer && count > 0 && count === maxCountsByCriteria.dreamer) ||
                                                        (criteria.key === ReviewCriteria.Realist && count > 0 && count === maxCountsByCriteria.realist) ||
                                                        (criteria.key === ReviewCriteria.Critic && count > 0 && count === maxCountsByCriteria.critic);
                                                    return (
                                                        <span
                                                            key={`print-${drawingId}-${criteria.key}`}
                                                            className={
                                                                isTop
                                                                    ? `${reviewingstyles.printCountItem} ${reviewingstyles.printCountTop}`
                                                                    : reviewingstyles.printCountItem
                                                            }
                                                        >
                                                            {criteria.label}: {count}
                                                        </span>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}

export default Reviewing;