"use client";

import React, { useState, useMemo, useCallback, useEffect } from "react";
import { X, Download, Printer, Eye } from "lucide-react";

// ── Types ───────────────────────────────────────────────────────────────────

interface WeekPrintModalProps {
    isOpen: boolean;
    onClose: () => void;
    currentWeekStart: Date;   // Monday of currently displayed week
    viewDays: number;         // days shown in current view
    startHour: number;        // user's configured start hour
    endHour: number;          // user's configured end hour
    language: string;         // 'de' | 'en'
    weatherEnabled: boolean;  // whether weather is configured
}

// ── Helpers ─────────────────────────────────────────────────────────────────

function toDateInput(d: Date): string {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${dd}`;
}

function addDays(d: Date, n: number): Date {
    const r = new Date(d);
    r.setDate(r.getDate() + n);
    return r;
}

function getDayName(d: Date, lang: string): string {
    return d.toLocaleDateString(lang === "de" ? "de-DE" : "en-GB", { weekday: "short" });
}

function getDateLabel(d: Date, lang: string): string {
    return d.toLocaleDateString(lang === "de" ? "de-DE" : "en-GB", { day: "2-digit", month: "short" });
}

function getWeekNumber(d: Date): number {
    const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    const dayNum = date.getUTCDay() || 7;
    date.setUTCDate(date.getUTCDate() + 4 - dayNum);
    const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
    return Math.ceil((((date.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
}

// ── Sample task positions for preview ───────────────────────────────────────

const SAMPLE_TASKS = [
    { dayIdx: 0, hourOffset: 0, color: "#6366f1", w: 0.8 },
    { dayIdx: 2, hourOffset: 1, color: "#10b981", w: 0.65 },
    { dayIdx: 1, hourOffset: 2, color: "#f59e0b", w: 0.75 },
    { dayIdx: 3, hourOffset: 0, color: "#ef4444", w: 0.55 },
    { dayIdx: 4, hourOffset: 3, color: "#6366f1", w: 0.9 },
    { dayIdx: 0, hourOffset: 4, color: "#8b5cf6", w: 0.6 },
    { dayIdx: 5, hourOffset: 1, color: "#06b6d4", w: 0.7 },
    { dayIdx: 3, hourOffset: 2, color: "#10b981", w: 0.5 },
    { dayIdx: 6, hourOffset: 0, color: "#f59e0b", w: 0.8 },
    { dayIdx: 2, hourOffset: 4, color: "#ef4444", w: 0.6 },
];

// ── Toggle component ─────────────────────────────────────────────────────────

function Toggle({ checked, onChange, disabled }: { checked: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {
    return (
        <button
            type="button"
            role="switch"
            aria-checked={checked}
            disabled={disabled}
            onClick={() => !disabled && onChange(!checked)}
            style={{
                width: 36, height: 20, borderRadius: 10,
                backgroundColor: checked && !disabled ? "#6366f1" : disabled ? "#d1d5db" : "#d1d5db",
                border: "none", cursor: disabled ? "not-allowed" : "pointer",
                position: "relative", transition: "background-color 0.2s", flexShrink: 0,
                opacity: disabled ? 0.5 : 1,
            }}
        >
            <span style={{
                position: "absolute", top: 2, left: checked ? 18 : 2,
                width: 16, height: 16, borderRadius: "50%", backgroundColor: "#fff",
                transition: "left 0.2s", boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
            }} />
        </button>
    );
}

// ── Main component ───────────────────────────────────────────────────────────

export default function WeekPrintModal({
    isOpen,
    onClose,
    currentWeekStart,
    viewDays,
    startHour: defaultStartHour,
    endHour: defaultEndHour,
    language,
    weatherEnabled,
}: WeekPrintModalProps) {
    const de = language === "de";

    // ── State
    const [startDate, setStartDate] = useState(() => toDateInput(currentWeekStart));
    const [numDays, setNumDays]     = useState(() => Math.min(Math.max(viewDays, 1), 14));
    const [startHour, setStartHour] = useState(() => defaultStartHour);
    const [endHour, setEndHour]     = useState(() => defaultEndHour);
    const [showAllDay, setShowAllDay]   = useState(true);
    const [showNoTime, setShowNoTime]   = useState(true);
    const [showWeather, setShowWeather] = useState(weatherEnabled);
    const [lang, setLang] = useState(language || "de");

    // Someday tab filter — fetched once when modal opens
    const [somedayTabs, setSomedayTabs] = useState<{ key: string; label: string }[]>([]);
    const [selectedTabs, setSelectedTabs] = useState<Set<string>>(new Set());
    const [tabsLoaded, setTabsLoaded] = useState(false);

    // ── Computed
    const endDate = useMemo(() => {
        const d = new Date(startDate + "T00:00:00");
        return toDateInput(addDays(d, numDays - 1));
    }, [startDate, numDays]);

    const previewDays = useMemo(() => {
        const days: Date[] = [];
        const d = new Date(startDate + "T00:00:00");
        for (let i = 0; i < Math.min(numDays, 7); i++) {
            days.push(addDays(d, i));
        }
        return days;
    }, [startDate, numDays]);

    const previewHours = useMemo(() => {
        const range = endHour - startHour;
        const step = range <= 6 ? 1 : range <= 10 ? 2 : 3;
        const hrs: number[] = [];
        for (let h = startHour; h < endHour; h += step) hrs.push(h);
        return hrs;
    }, [startHour, endHour]);

    const numPages = useMemo(() => Math.ceil(numDays / 7), [numDays]);

    // Fetch available someday tabs once when the modal opens
    useEffect(() => {
        if (!isOpen || tabsLoaded) return;
        fetch("/api/user/someday-tabs")
            .then(r => r.json())
            .then((data: { lists: { id: string; title: string; tab: string | null }[] }) => {
                const seen = new Set<string>();
                const tabs: { key: string; label: string }[] = [];
                const defaultLabel = lang === "de" ? "Allgemein" : "General";
                for (const list of data.lists || []) {
                    // Encode null tab as the default label so it round-trips through URL params
                    const key = list.tab ?? defaultLabel;
                    const label = list.tab ?? defaultLabel;
                    if (!seen.has(key)) { seen.add(key); tabs.push({ key, label }); }
                }
                setSomedayTabs(tabs);
                setSelectedTabs(new Set(tabs.map(t => t.key))); // all selected by default
                setTabsLoaded(true);
            })
            .catch(() => setTabsLoaded(true));
    }, [isOpen, tabsLoaded, lang]);

    const pdfUrl = useMemo(() => {
        const params = new URLSearchParams({
            startDate,
            endDate,
            startHour: String(startHour),
            endHour:   String(endHour),
            lang,
            showAllDay: showAllDay ? "1" : "0",
            showNoTime: showNoTime ? "1" : "0",
            showWeather: showWeather ? "1" : "0",
        });
        // Only send tab filter if not all tabs are selected (avoids unnecessary URL noise)
        if (showNoTime && somedayTabs.length > 1 && selectedTabs.size < somedayTabs.length) {
            params.set("noTimeTabs", Array.from(selectedTabs).join(","));
        }
        return `/api/user/export-week-view?${params}`;
    }, [startDate, endDate, startHour, endHour, lang, showAllDay, showNoTime, showWeather, selectedTabs, somedayTabs]);

    const printUrl = useMemo(() => `${pdfUrl}&inline=1`, [pdfUrl]);

    const handleStartDateChange = useCallback((val: string) => {
        setStartDate(val);
    }, []);

    const handleNumDaysChange = useCallback((val: number) => {
        setNumDays(Math.min(Math.max(val, 1), 14));
    }, []);

    const handleStartHourChange = useCallback((val: number) => {
        const clamped = Math.min(Math.max(val, 0), 23);
        setStartHour(clamped);
        if (endHour <= clamped) setEndHour(Math.min(clamped + 1, 24));
    }, [endHour]);

    const handleEndHourChange = useCallback((val: number) => {
        const clamped = Math.min(Math.max(val, 1), 24);
        setEndHour(clamped);
        if (startHour >= clamped) setStartHour(Math.max(clamped - 1, 0));
    }, [startHour]);

    if (!isOpen) return null;

    const today = toDateInput(new Date());
    const numHours = endHour - startHour;

    // ── i18n
    const t = {
        title:        de ? "Woche drucken / Exportieren" : "Print / Export Week View",
        subtitle:     de ? "Als PDF exportieren oder im Browser drucken" : "Export as PDF or print in browser",
        dateRange:    de ? "Datum" : "Date",
        startDateLbl: de ? "Startdatum" : "Start date",
        numDaysLbl:   de ? "Anzahl Tage" : "Number of days",
        timeRange:    de ? "Zeitraum" : "Time range",
        fromHour:     de ? "Von" : "From",
        toHour:       de ? "Bis" : "To",
        display:      de ? "Anzeigen" : "Display",
        showAllDay:   de ? "Ganztag-Bereich" : "All-day section",
        showNoTime:   de ? "Aufgaben ohne Uhrzeit" : "Tasks without time",
        showWeather:  de ? "Wetter anzeigen" : "Show weather",
        weatherNote:  de ? "(Wetterstandort muss in Einstellungen konfiguriert sein)" : "(Weather location must be configured in settings)",
        previewTitle: de ? "Vorschau" : "Preview",
        pages:        de ? "Seiten" : "pages",
        hours:        de ? "Std." : "hrs",
        days:         de ? "Tage" : "days",
        language:     de ? "Sprache" : "Language",
        cancel:       de ? "Abbrechen" : "Cancel",
        print:        de ? "Im Browser drucken" : "Print in Browser",
        download:     de ? "PDF herunterladen" : "Download PDF",
        kw:           de ? "KW" : "W",
    };

    return (
        <div
            className="fixed inset-0 bg-black/60 flex items-center justify-center z-[200] px-4 py-6"
            onClick={onClose}
        >
            <div
                className="bg-white dark:bg-zinc-900 rounded-2xl shadow-2xl w-full max-w-2xl flex flex-col overflow-hidden"
                style={{ maxHeight: "92vh" }}
                onClick={e => e.stopPropagation()}
            >
                {/* Header */}
                <div style={{ background: "#6366f1", padding: "20px 24px", flexShrink: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                            <div style={{
                                width: 38, height: 38, borderRadius: 10,
                                background: "rgba(255,255,255,0.2)",
                                display: "flex", alignItems: "center", justifyContent: "center",
                            }}>
                                <Printer size={20} color="#fff" />
                            </div>
                            <div>
                                <div style={{ color: "#fff", fontWeight: 700, fontSize: "1rem" }}>{t.title}</div>
                                <div style={{ color: "rgba(255,255,255,0.7)", fontSize: "0.78rem", marginTop: 2 }}>{t.subtitle}</div>
                            </div>
                        </div>
                        <button
                            onClick={onClose}
                            style={{ background: "rgba(255,255,255,0.2)", border: "none", borderRadius: 8, padding: "6px 8px", cursor: "pointer", color: "#fff", display: "flex" }}
                        >
                            <X size={18} />
                        </button>
                    </div>
                </div>

                {/* Body — scrollable */}
                <div style={{ overflowY: "auto", flex: 1, padding: "20px 24px", display: "flex", flexDirection: "column", gap: 20 }}>

                    {/* ── Date & Days */}
                    <div>
                        <SectionLabel>{t.dateRange}</SectionLabel>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                            <div>
                                <FieldLabel>{t.startDateLbl}</FieldLabel>
                                <input
                                    type="date"
                                    value={startDate}
                                    onChange={e => handleStartDateChange(e.target.value)}
                                    style={{
                                        width: "100%", fontSize: "0.88rem", padding: "7px 10px",
                                        borderRadius: 6, border: "1px solid #d1d5db",
                                        background: "#fff", color: "#374151", fontFamily: "inherit",
                                        boxSizing: "border-box",
                                    }}
                                />
                            </div>
                            <div>
                                <FieldLabel>{t.numDaysLbl}</FieldLabel>
                                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                                    <input
                                        type="range"
                                        min={1}
                                        max={14}
                                        value={numDays}
                                        onChange={e => handleNumDaysChange(parseInt(e.target.value))}
                                        style={{ flex: 1, accentColor: "#6366f1" }}
                                    />
                                    <span style={{
                                        minWidth: 42, textAlign: "center", fontWeight: 700,
                                        fontSize: "0.88rem", color: "#6366f1",
                                        background: "#eff6ff", borderRadius: 6, padding: "3px 8px",
                                    }}>
                                        {numDays}
                                    </span>
                                </div>
                                <div style={{ fontSize: "0.73rem", color: "#94a3b8", marginTop: 3 }}>
                                    {endDate} · {numPages > 1 ? `${numPages} ${t.pages}` : "1 PDF"}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* ── Time range */}
                    <div>
                        <SectionLabel>{t.timeRange}</SectionLabel>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                            <div>
                                <FieldLabel>{t.fromHour}</FieldLabel>
                                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                    <input
                                        type="range"
                                        min={0}
                                        max={22}
                                        value={startHour}
                                        onChange={e => handleStartHourChange(parseInt(e.target.value))}
                                        style={{ flex: 1, accentColor: "#6366f1" }}
                                    />
                                    <HourBadge>{String(startHour).padStart(2, "0")}:00</HourBadge>
                                </div>
                            </div>
                            <div>
                                <FieldLabel>{t.toHour}</FieldLabel>
                                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                    <input
                                        type="range"
                                        min={1}
                                        max={24}
                                        value={endHour}
                                        onChange={e => handleEndHourChange(parseInt(e.target.value))}
                                        style={{ flex: 1, accentColor: "#6366f1" }}
                                    />
                                    <HourBadge>{endHour < 24 ? `${String(endHour).padStart(2, "0")}:00` : "24:00"}</HourBadge>
                                </div>
                            </div>
                        </div>
                        <div style={{ fontSize: "0.73rem", color: "#94a3b8", marginTop: 4 }}>
                            {numHours} {t.hours} · {String(startHour).padStart(2, "0")}:00 – {endHour < 24 ? String(endHour).padStart(2, "0") : "24"}:00
                        </div>
                    </div>

                    {/* ── Display toggles */}
                    <div>
                        <SectionLabel>{t.display}</SectionLabel>
                        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                            <ToggleRow
                                label={t.showAllDay}
                                checked={showAllDay}
                                onChange={setShowAllDay}
                            />
                            <div>
                                <ToggleRow
                                    label={t.showNoTime}
                                    checked={showNoTime}
                                    onChange={setShowNoTime}
                                />
                                {/* Tab filter — shown when the someday section is enabled and there are multiple tabs */}
                                {showNoTime && somedayTabs.length > 1 && (
                                    <div style={{ paddingLeft: 46, marginTop: 8 }}>
                                        <div style={{ fontSize: "0.73rem", fontWeight: 600, color: "#6b7280", marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.05em" }}>
                                            {de ? "Tabs einschließen" : "Include tabs"}
                                        </div>
                                        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                                            {somedayTabs.map(({ key, label }) => {
                                                const checked = selectedTabs.has(key);
                                                return (
                                                    <label
                                                        key={key}
                                                        style={{
                                                            display: "flex", alignItems: "center", gap: 5,
                                                            cursor: "pointer", fontSize: "0.82rem",
                                                            padding: "3px 10px 3px 8px",
                                                            borderRadius: 6,
                                                            border: `1px solid ${checked ? "#6366f1" : "#d1d5db"}`,
                                                            background: checked ? "#eff6ff" : "#f9fafb",
                                                            color: checked ? "#4f46e5" : "#6b7280",
                                                            fontWeight: checked ? 600 : 400,
                                                            transition: "all 0.15s",
                                                            userSelect: "none",
                                                        }}
                                                    >
                                                        <input
                                                            type="checkbox"
                                                            checked={checked}
                                                            onChange={e => {
                                                                const next = new Set(selectedTabs);
                                                                if (e.target.checked) next.add(key);
                                                                else if (next.size > 1) next.delete(key); // keep at least 1 selected
                                                                setSelectedTabs(next);
                                                            }}
                                                            style={{ accentColor: "#6366f1", width: 13, height: 13, flexShrink: 0 }}
                                                        />
                                                        {label}
                                                    </label>
                                                );
                                            })}
                                        </div>
                                    </div>
                                )}
                            </div>
                            <div>
                                <ToggleRow
                                    label={t.showWeather}
                                    checked={showWeather}
                                    onChange={setShowWeather}
                                    disabled={!weatherEnabled}
                                />
                                {!weatherEnabled && (
                                    <div style={{ fontSize: "0.72rem", color: "#94a3b8", marginTop: 3, paddingLeft: 44 }}>
                                        {t.weatherNote}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* ── Language */}
                    <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                        <span style={{ fontSize: "0.82rem", fontWeight: 600, color: "#374151" }}>{t.language}</span>
                        {["de", "en"].map(l => (
                            <label key={l} style={{ display: "flex", alignItems: "center", gap: 5, cursor: "pointer", fontSize: "0.85rem" }}>
                                <input
                                    type="radio"
                                    name="lang"
                                    value={l}
                                    checked={lang === l}
                                    onChange={() => setLang(l)}
                                    style={{ accentColor: "#6366f1" }}
                                />
                                {l === "de" ? "Deutsch" : "English"}
                            </label>
                        ))}
                    </div>

                    {/* ── Preview */}
                    <div>
                        <SectionLabel>
                            <Eye size={13} style={{ marginRight: 5, verticalAlign: "middle" }} />
                            {t.previewTitle}
                        </SectionLabel>
                        <CalendarPreview
                            days={previewDays}
                            hours={previewHours}
                            startHour={startHour}
                            showAllDay={showAllDay}
                            lang={lang}
                            numDays={numDays}
                        />
                        {numDays > 7 && (
                            <div style={{ fontSize: "0.72rem", color: "#94a3b8", marginTop: 6, textAlign: "center" }}>
                                {de ? `${numDays} Tage → ${numPages} PDF-Seiten (je 7 Tage)` : `${numDays} days → ${numPages} PDF pages (7 days each)`}
                            </div>
                        )}
                    </div>
                </div>

                {/* Footer */}
                <div style={{
                    padding: "14px 24px",
                    borderTop: "1px solid #e5e7eb",
                    display: "flex",
                    gap: 10,
                    justifyContent: "flex-end",
                    flexShrink: 0,
                }}>
                    <button
                        onClick={onClose}
                        style={{
                            padding: "9px 18px", borderRadius: 8, border: "1px solid #e5e7eb",
                            background: "#fff", cursor: "pointer", fontWeight: 500, fontSize: "0.88rem", color: "#374151",
                        }}
                    >
                        {t.cancel}
                    </button>
                    <button
                        onClick={() => window.open(printUrl, "_blank")}
                        style={{
                            padding: "9px 20px", borderRadius: 8, border: "none",
                            background: "#1e293b", color: "#fff", fontWeight: 600,
                            fontSize: "0.88rem",
                            display: "flex", alignItems: "center", gap: 7, cursor: "pointer",
                        }}
                    >
                        <Printer size={15} />
                        {t.print}
                    </button>
                    <a
                        href={pdfUrl}
                        target="_blank"
                        rel="noreferrer"
                        style={{
                            padding: "9px 20px", borderRadius: 8, border: "none",
                            background: "#6366f1", color: "#fff", fontWeight: 600,
                            fontSize: "0.88rem", textDecoration: "none",
                            display: "flex", alignItems: "center", gap: 7, cursor: "pointer",
                        }}
                    >
                        <Download size={15} />
                        {t.download}
                    </a>
                </div>
            </div>
        </div>
    );
}

// ── Sub-components ───────────────────────────────────────────────────────────

function SectionLabel({ children }: { children: React.ReactNode }) {
    return (
        <div style={{
            fontSize: "0.75rem", fontWeight: 700, textTransform: "uppercase",
            letterSpacing: "0.06em", color: "#6b7280", marginBottom: 10,
            display: "flex", alignItems: "center",
        }}>
            {children}
        </div>
    );
}

function FieldLabel({ children }: { children: React.ReactNode }) {
    return (
        <div style={{ fontSize: "0.78rem", fontWeight: 600, color: "#374151", marginBottom: 5 }}>
            {children}
        </div>
    );
}

function HourBadge({ children }: { children: React.ReactNode }) {
    return (
        <span style={{
            minWidth: 48, textAlign: "center", fontWeight: 700,
            fontSize: "0.82rem", color: "#6366f1",
            background: "#eff6ff", borderRadius: 6, padding: "3px 6px",
            fontVariantNumeric: "tabular-nums", flexShrink: 0,
        }}>
            {children}
        </span>
    );
}

function ToggleRow({
    label, checked, onChange, disabled,
}: { label: string; checked: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Toggle checked={checked} onChange={onChange} disabled={disabled} />
            <span style={{ fontSize: "0.85rem", color: disabled ? "#94a3b8" : "#374151" }}>{label}</span>
        </div>
    );
}

// ── Calendar preview ─────────────────────────────────────────────────────────

function CalendarPreview({
    days, hours, startHour, showAllDay, lang, numDays,
}: {
    days: Date[];
    hours: number[];
    startHour: number;
    showAllDay: boolean;
    lang: string;
    numDays: number;
}) {
    const PREVIEW_H = 180;
    const PREVIEW_TIME_W = 28;
    const today = toDateInput(new Date());

    return (
        <div style={{
            border: "1px solid #e2e8f0",
            borderRadius: 8,
            overflow: "hidden",
            background: "#fff",
            fontSize: 9,
            userSelect: "none",
            height: PREVIEW_H,
            display: "flex",
            flexDirection: "column",
        }}>
            {/* Aspect ratio indicator + day headers */}
            <div style={{
                display: "flex", flexShrink: 0,
                background: "#f1f5f9", borderBottom: "1px solid #e2e8f0",
            }}>
                {/* time spacer */}
                <div style={{ width: PREVIEW_TIME_W, borderRight: "1px solid #e2e8f0", flexShrink: 0 }} />
                {days.map((d, i) => {
                    const dk = toDateInput(d);
                    const isToday = dk === today;
                    return (
                        <div key={i} style={{
                            flex: 1, textAlign: "center", padding: "4px 2px",
                            borderRight: "1px solid #e2e8f0",
                            background: isToday ? "#dbeafe" : undefined,
                        }}>
                            <div style={{ fontWeight: 700, fontSize: 8, color: "#6b7280", lineHeight: 1 }}>
                                {getDayName(d, lang).toUpperCase()}
                            </div>
                            <div style={{ fontWeight: 700, fontSize: 9, color: isToday ? "#6366f1" : "#1e293b", marginTop: 1, lineHeight: 1 }}>
                                {getDateLabel(d, lang)}
                            </div>
                        </div>
                    );
                })}
                {/* placeholder if numDays > 7 */}
                {numDays > 7 && (
                    <div style={{ width: 18, flexShrink: 0, background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center" }}>
                        <span style={{ color: "#94a3b8", fontSize: 9 }}>…</span>
                    </div>
                )}
            </div>

            {/* All-day row */}
            {showAllDay && (
                <div style={{
                    display: "flex", flexShrink: 0,
                    background: "#f0f4ff", borderBottom: "1px solid #e2e8f0",
                    height: 16,
                }}>
                    <div style={{
                        width: PREVIEW_TIME_W, borderRight: "1px solid #e2e8f0",
                        display: "flex", alignItems: "center", justifyContent: "flex-end",
                        paddingRight: 3, flexShrink: 0,
                    }}>
                        <span style={{ fontSize: 6, color: "#94a3b8", fontWeight: 700 }}>
                            {lang === "de" ? "GT" : "AD"}
                        </span>
                    </div>
                    {days.map((_, i) => (
                        <div key={i} style={{
                            flex: 1, borderRight: "1px solid #e2e8f0",
                            display: "flex", alignItems: "center", padding: "1px 2px",
                        }}>
                            {SAMPLE_TASKS.filter(t => t.dayIdx === i && t.hourOffset === 0).slice(0, 1).map((t, j) => (
                                <div key={j} style={{
                                    borderLeft: `2px solid ${t.color}`,
                                    backgroundColor: `${t.color}28`,
                                    borderRadius: 2, height: 8,
                                    width: `${t.w * 80}%`,
                                    paddingLeft: 2, display: "flex", alignItems: "center",
                                }}>
                                    <div style={{ height: 3, flex: 1, backgroundColor: `${t.color}66`, borderRadius: 1 }} />
                                </div>
                            ))}
                        </div>
                    ))}
                </div>
            )}

            {/* Hour rows */}
            <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
                {hours.map((h, hi) => (
                    <div key={h} style={{
                        flex: 1, display: "flex",
                        borderBottom: hi < hours.length - 1 ? "1px solid #e2e8f0" : undefined,
                        background: hi % 2 === 1 ? "#f8fafc" : "#fff",
                        minHeight: 0,
                    }}>
                        {/* Time label */}
                        <div style={{
                            width: PREVIEW_TIME_W, borderRight: "1px solid #e2e8f0",
                            display: "flex", alignItems: "flex-start", justifyContent: "flex-end",
                            paddingRight: 3, paddingTop: 2, flexShrink: 0,
                        }}>
                            <span style={{ fontSize: 7, color: "#94a3b8", fontWeight: 700 }}>
                                {String(h).padStart(2, "0")}
                            </span>
                        </div>
                        {/* Day cells */}
                        {days.map((_, di) => {
                            // Show sample tasks: map hourOffset to preview rows
                            const tasks = SAMPLE_TASKS.filter(
                                t => t.dayIdx === di && t.hourOffset === hi
                            );
                            const dk = toDateInput(days[di] ?? new Date());
                            const isToday = dk === today;
                            return (
                                <div key={di} style={{
                                    flex: 1, borderRight: "1px solid #e2e8f0",
                                    padding: "2px 2px 1px",
                                    background: isToday ? "#eff6ff" : undefined,
                                    overflow: "hidden",
                                }}>
                                    {tasks.slice(0, 2).map((t, j) => (
                                        <div key={j} style={{
                                            borderLeft: `2px solid ${t.color}`,
                                            height: 9, width: `${t.w * 90}%`,
                                            marginBottom: 1, paddingLeft: 2,
                                            display: "flex", alignItems: "center",
                                            overflow: "hidden",
                                        }}>
                                            <div style={{ height: 4, flex: 1, backgroundColor: "#d1d5db", borderRadius: 1 }} />
                                        </div>
                                    ))}
                                </div>
                            );
                        })}
                    </div>
                ))}
            </div>
        </div>
    );
}
