<?php $events = isset($project_calendar_events) && is_array($project_calendar_events) ? $project_calendar_events : array(); ?>

<style type="text/css">
    .cal-chip {
        border: 1px solid rgba(15, 23, 42, 0.08);
    }

    .dark .cal-chip {
        border: 1px solid rgba(255, 255, 255, 0.12);
    }

    .cal-chip span {
        border-radius: 9999px;
    }

    .cal-cell-muted {
        background: repeating-linear-gradient(135deg, rgba(148, 163, 184, 0.2), rgba(148, 163, 184, 0.2) 6px, transparent 6px, transparent 12px);
    }

    .dark .cal-cell-muted {
        background: repeating-linear-gradient(135deg, rgba(148, 163, 184, 0.18), rgba(148, 163, 184, 0.18) 6px, transparent 6px, transparent 12px);
    }

    .cal-pill {
        color: #ffffff;
        font-weight: 600;
    }

    .cal-view-active {
        background: #ffffff;
        color: #4f46e5;
        box-shadow: 0 1px 2px rgba(15, 23, 42, 0.12);
    }

    .dark .cal-view-active {
        background: rgba(255, 255, 255, 0.12);
        color: #ffffff;
        box-shadow: none;
    }
</style>

<div class="project-overview-shell space-y-6">
    <div class="project-section-card overflow-hidden rounded-[26px] border border-border bg-card shadow-sm">
        <div class="border-b border-border px-6 py-6 text-slate-900 dark:text-white">
            <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                <div>
                    <div class="text-2xl font-semibold" data-cal-title></div>
                    <p class="text-sm text-muted-foreground dark:text-slate-300">Project schedule, delivery dates, and linked records.</p>
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <button type="button" class="project-action-btn inline-flex items-center px-2.5 py-2 text-xs font-semibold text-foreground hover:bg-muted dark:text-white dark:hover:bg-white/10" data-cal-prev>
                        <i data-lucide="chevron-left" class="h-4 w-4"></i>
                    </button>
                    <button type="button" class="project-action-btn inline-flex items-center px-2.5 py-2 text-xs font-semibold text-foreground hover:bg-muted dark:text-white dark:hover:bg-white/10" data-cal-next>
                        <i data-lucide="chevron-right" class="h-4 w-4"></i>
                    </button>
                    <button type="button" class="project-action-btn inline-flex items-center px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted dark:text-white dark:hover:bg-white/10" data-cal-today>
                        <?= lang('today') ?>
                    </button>
                </div>
            </div>

            <div class="mt-5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground dark:text-slate-300">
                <?php if (config_item('project_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('project_color'); ?>"></span><?= lang('project') ?></span>
                <?php } ?>
                <?php if (config_item('milestone_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('milestone_color'); ?>"></span><?= lang('milestone') ?></span>
                <?php } ?>
                <?php if (config_item('tasks_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('tasks_color'); ?>"></span><?= lang('tasks') ?></span>
                <?php } ?>
                <?php if (config_item('bugs_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('bugs_color'); ?>"></span><?= lang('bugs') ?></span>
                <?php } ?>
                <?php if (config_item('invoice_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('invoice_color'); ?>"></span><?= lang('invoice') ?></span>
                <?php } ?>
                <?php if (config_item('estimate_on_calendar') == 'on') { ?>
                    <span class="project-summary-chip cal-chip inline-flex items-center gap-2 px-3 py-1 dark:bg-white/5"><span class="h-2 w-2" style="background: <?= config_item('estimate_color'); ?>"></span><?= lang('estimate') ?></span>
                <?php } ?>
            </div>
        </div>

        <div class="border-b border-border px-6 py-3">
            <div class="flex flex-wrap items-center justify-between gap-3">
                <div class="project-summary-chip inline-flex items-center p-1 text-xs font-semibold shadow-sm dark:bg-white/5">
                    <button type="button" class="rounded-md px-3 py-1 text-foreground transition hover:bg-muted dark:text-slate-200 dark:hover:bg-white/10" data-cal-view="month">Month</button>
                    <button type="button" class="rounded-md px-3 py-1 text-foreground transition hover:bg-muted dark:text-slate-200 dark:hover:bg-white/10" data-cal-view="week">Week</button>
                    <button type="button" class="rounded-md px-3 py-1 text-foreground transition hover:bg-muted dark:text-slate-200 dark:hover:bg-white/10" data-cal-view="day">Day</button>
                </div>
            </div>
        </div>

        <div class="p-6">
            <div class="project-inline-card overflow-hidden rounded-2xl border border-border bg-white shadow-sm dark:bg-slate-900">
                <div data-cal-weekdays class="grid grid-cols-7 border-b border-slate-200/80 bg-slate-50 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:border-white/10 dark:bg-slate-950/60 dark:text-slate-300">
                    <div class="px-3 py-2">Sunday</div>
                    <div class="px-3 py-2">Monday</div>
                    <div class="px-3 py-2">Tuesday</div>
                    <div class="px-3 py-2">Wednesday</div>
                    <div class="px-3 py-2">Thursday</div>
                    <div class="px-3 py-2">Friday</div>
                    <div class="px-3 py-2">Saturday</div>
                </div>
                <div id="calendar_grid" class="grid grid-cols-7 gap-px bg-slate-200/70 min-h-[700px] dark:bg-white/5"></div>
            </div>
        </div>
    </div>
</div>

<div id="calendar_event_modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/40 p-4">
    <div class="w-full max-w-xl rounded-2xl border border-border bg-card shadow-xl">
        <div class="flex items-center justify-between border-b border-border px-5 py-3">
            <div>
                <h4 class="text-base font-semibold text-foreground" id="calendar_event_title"><?= lang('events') ?></h4>
                <p class="text-xs text-muted-foreground" id="calendar_event_subtitle"></p>
            </div>
            <button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-border bg-background text-lg leading-none text-muted-foreground transition hover:border-primary hover:text-primary" data-cal-modal-close aria-label="<?= lang('close') ?>">&times;</button>
        </div>
        <div class="p-5">
            <div id="calendar_event_list" class="space-y-3"></div>
            <div id="calendar_event_empty" class="text-sm text-muted-foreground hidden"><?= lang('no_data') ?></div>
        </div>
        <div class="flex items-center justify-end gap-2 border-t border-border px-5 py-3">
            <button type="button" class="inline-flex items-center justify-center rounded-lg border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground transition hover:border-primary hover:text-primary" data-cal-modal-close>
                <?= lang('close') ?>
            </button>
        </div>
    </div>
</div>

<script id="calendar_events" type="application/json"><?= json_encode($events); ?></script>
<script>
(() => {
    const parseDate = (value) => {
        if (!value) return null;
        if (value instanceof Date) return value;
        const s = String(value).trim();
        if (/^\d{4}-\d{2}-\d{2}/.test(s)) {
            const d = new Date(`${s.slice(0, 10)}T00:00:00`);
            return isNaN(d) ? null : d;
        }
        if (/^\d{2}\.\d{2}\.\d{4}$/.test(s)) {
            const [m, d, y] = s.split(".");
            const dt = new Date(`${y}-${m}-${d}T00:00:00`);
            return isNaN(dt) ? null : dt;
        }
        const dt = new Date(s);
        return isNaN(dt) ? null : dt;
    };

    const events = JSON.parse(document.getElementById("calendar_events").textContent || "[]").map((e) => {
        const startDate = parseDate(e.start);
        const endDate = parseDate(e.end) || startDate;
        if (startDate && endDate && endDate < startDate) {
            return { ...e, startDate, endDate: startDate };
        }
        return { ...e, startDate, endDate };
    }).filter((e) => e.startDate);

    const state = {
        view: "month",
        current: new Date(),
        selected: new Date(),
    };

    const grid = document.getElementById("calendar_grid");
    const titleEl = document.querySelector("[data-cal-title]");
    const weekdayHeader = document.querySelector("[data-cal-weekdays]");
    const modal = document.getElementById("calendar_event_modal");
    const modalTitle = document.getElementById("calendar_event_title");
    const modalSubtitle = document.getElementById("calendar_event_subtitle");
    const modalList = document.getElementById("calendar_event_list");
    const modalEmpty = document.getElementById("calendar_event_empty");
    let lastModalDate = null;

    const fmtMonth = new Intl.DateTimeFormat(undefined, { month: "long", year: "numeric" });
    const fmtDay = new Intl.DateTimeFormat(undefined, { weekday: "long", month: "long", day: "numeric", year: "numeric" });
    const fmtShort = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" });

    const sameDay = (a, b) =>
        a.getFullYear() === b.getFullYear() &&
        a.getMonth() === b.getMonth() &&
        a.getDate() === b.getDate();

    const dayKey = (date) => date.getFullYear() * 10000 + (date.getMonth() + 1) * 100 + date.getDate();
    const inRange = (date, start, end) => {
        if (!start) return false;
        const d = dayKey(date);
        const s = dayKey(start);
        const e = dayKey(end || start);
        return d >= s && d <= e;
    };

    const eventsForDate = (date) => events.filter((e) => inRange(date, e.startDate, e.endDate));

    const qsa = (sel, root = document) => Array.from(root.querySelectorAll(sel));
    const setGridColumns = (count) => {
        if (grid) {
            grid.style.gridTemplateColumns = `repeat(${count}, minmax(0, 1fr))`;
        }
        if (weekdayHeader) {
            weekdayHeader.style.gridTemplateColumns = `repeat(${count}, minmax(0, 1fr))`;
        }
    };

    const renderEventCard = (event) => {
        const color = event.color || "#6366f1";
        return `
            <a href="${event.url || "#"}" class="flex items-start gap-3 rounded-lg border border-slate-200 bg-white p-3 text-slate-900 shadow-sm transition hover:-translate-y-px hover:border-indigo-200 hover:shadow-md dark:border-white/10 dark:bg-slate-900/80 dark:text-white dark:hover:border-indigo-400/30 dark:hover:bg-slate-800/80">
                <span class="mt-1 h-2.5 w-2.5 rounded-full" style="background:${color}"></span>
                <div class="min-w-0">
                    <div class="text-sm font-semibold truncate">${event.title}</div>
                    <div class="text-xs text-slate-500 dark:text-slate-300">${fmtShort.format(event.startDate)}</div>
                </div>
            </a>`;
    };

    const renderModal = (date) => {
        if (!modal) return;
        const dayEvents = eventsForDate(date);
        modalTitle.textContent = "<?= lang('events') ?>";
        modalSubtitle.textContent = fmtDay.format(date);
        modalList.innerHTML = dayEvents.map(renderEventCard).join("");
        modalEmpty.classList.toggle("hidden", dayEvents.length > 0);
        modal.classList.remove("hidden");
        modal.classList.add("flex");
        lastModalDate = date;
    };

    const renderMonth = () => {
        grid.innerHTML = "";
        const first = new Date(state.current.getFullYear(), state.current.getMonth(), 1);
        const start = new Date(first);
        start.setDate(first.getDate() - first.getDay());
        const last = new Date(state.current.getFullYear(), state.current.getMonth() + 1, 0);
        const end = new Date(last);
        end.setDate(last.getDate() + (6 - last.getDay()));

        if (titleEl) {
            titleEl.textContent = fmtMonth.format(state.current);
        }

        weekdayHeader?.classList.remove("hidden");
        setGridColumns(7);

        let cursor = new Date(start);
        while (cursor <= end) {
            const dayEvents = eventsForDate(cursor);
            const isCurrentMonth = cursor.getMonth() === state.current.getMonth();
            const isSelected = sameDay(cursor, state.selected);
            const isToday = sameDay(cursor, new Date());
            const muted = isCurrentMonth ? "" : "cal-cell-muted";
            grid.insertAdjacentHTML(
                "beforeend",
                `<button type="button" data-date="${cursor.toISOString()}"
                    class="group min-h-[120px] bg-white px-2 py-2 text-left text-xs border border-slate-200/70 transition hover:border-indigo-300/70 hover:shadow-[0_10px_24px_-18px_rgba(30,64,175,0.45)] focus-visible:outline-none dark:bg-slate-900 dark:border-white/5 dark:hover:bg-slate-800/90 dark:hover:border-indigo-400/30 ${muted} ${isSelected ? "ring-2 ring-indigo-500/70" : ""}">
                    <div class="flex items-center justify-between">
                        <span class="inline-flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-semibold ${isToday ? "bg-indigo-600 text-white" : isCurrentMonth ? "text-slate-700 dark:text-slate-100" : "text-slate-400 dark:text-slate-400"}">${cursor.getDate()}</span>
                        ${dayEvents.length ? `<span class="text-[10px] text-slate-400 dark:text-slate-400">${dayEvents.length}</span>` : ""}
                    </div>
                    <div class="mt-2 space-y-1">
                        ${dayEvents.slice(0, 2).map((e) => `<div class="truncate rounded-md px-2 py-1 text-[10px] cal-pill shadow-sm" style="background:${e.color || "#6366f1"}">${e.title}</div>`).join("")}
                        ${dayEvents.length > 2 ? `<div class="text-[10px] text-slate-400 dark:text-slate-400">+${dayEvents.length - 2} more</div>` : ""}
                    </div>
                </button>`
            );
            cursor.setDate(cursor.getDate() + 1);
        }
    };

    const renderWeek = () => {
        grid.innerHTML = "";
        const start = new Date(state.current);
        start.setDate(start.getDate() - start.getDay());
        const end = new Date(start);
        end.setDate(start.getDate() + 6);

        if (titleEl) {
            titleEl.textContent = `${fmtDay.format(start)} - ${fmtDay.format(end)}`;
        }

        weekdayHeader?.classList.remove("hidden");
        setGridColumns(7);

        let cursor = new Date(start);
        for (let i = 0; i < 7; i += 1) {
            const dayEvents = eventsForDate(cursor);
            const isSelected = sameDay(cursor, state.selected);
            const isToday = sameDay(cursor, new Date());
            grid.insertAdjacentHTML(
                "beforeend",
                `<button type="button" data-date="${cursor.toISOString()}"
                    class="group min-h-[220px] bg-white px-3 py-3 text-left text-xs border border-slate-200/70 transition hover:border-indigo-300/70 hover:shadow-[0_10px_24px_-18px_rgba(30,64,175,0.45)] focus-visible:outline-none dark:bg-slate-900 dark:border-white/5 dark:hover:bg-slate-800/90 dark:hover:border-indigo-400/30 ${isSelected ? "ring-2 ring-indigo-500/70" : ""}">
                    <div class="flex items-center justify-between">
                        <span class="text-sm font-semibold ${isToday ? "text-indigo-600 dark:text-indigo-300" : "text-slate-700 dark:text-slate-100"}">${fmtShort.format(cursor)}</span>
                        ${dayEvents.length ? `<span class="text-[10px] text-slate-400 dark:text-slate-400">${dayEvents.length}</span>` : ""}
                    </div>
                    <div class="mt-3 space-y-2">
                        ${dayEvents.slice(0, 4).map((e) => `
                            <div class="flex items-start gap-2 rounded-md border border-slate-200 bg-white/90 px-2 py-1 text-[11px] text-slate-800 shadow-sm dark:border-white/10 dark:bg-slate-900/80 dark:text-slate-100">
                                <span class="mt-1 h-2 w-2 rounded-full" style="background:${e.color || "#6366f1"}"></span>
                                <span class="truncate">${e.title}</span>
                            </div>`).join("")}
                        ${dayEvents.length > 4 ? `<div class="text-[10px] text-slate-400 dark:text-slate-400">+${dayEvents.length - 4} more</div>` : ""}
                    </div>
                </button>`
            );
            cursor.setDate(cursor.getDate() + 1);
        }
    };

    const renderDay = () => {
        grid.innerHTML = "";
        const dayEvents = eventsForDate(state.current);
        if (titleEl) {
            titleEl.textContent = fmtDay.format(state.current);
        }
        weekdayHeader?.classList.add("hidden");
        setGridColumns(1);

        grid.insertAdjacentHTML(
            "beforeend",
            `<div class="bg-white px-5 py-5 text-sm dark:bg-slate-900">
                <div class="flex items-center justify-between">
                    <div class="text-base font-semibold text-slate-800 dark:text-white">${fmtDay.format(state.current)}</div>
                    <button type="button" data-date="${state.current.toISOString()}" class="text-xs font-semibold text-indigo-600 hover:text-indigo-500 dark:text-indigo-300"><?= lang('view') ?></button>
                </div>
                <div class="mt-4 space-y-3">
                    ${dayEvents.map(renderEventCard).join("")}
                </div>
            </div>`
        );
    };

    const render = () => {
        qsa("[data-cal-view]").forEach((btn) => {
            btn.classList.toggle("cal-view-active", btn.dataset.calView === state.view);
        });
        if (state.view === "week") {
            renderWeek();
        } else if (state.view === "day") {
            renderDay();
        } else {
            renderMonth();
        }
    };

    document.addEventListener("click", (e) => {
        const btn = e.target.closest("[data-date]");
        if (btn) {
            state.selected = new Date(btn.dataset.date);
            state.current = new Date(btn.dataset.date);
            render();
            renderModal(state.selected);
        }
        const viewBtn = e.target.closest("[data-cal-view]");
        if (viewBtn) {
            state.view = viewBtn.dataset.calView;
            state.current = new Date(state.selected);
            render();
        }
    });

    document.querySelector("[data-cal-prev]")?.addEventListener("click", () => {
        if (state.view === "week") {
            state.current.setDate(state.current.getDate() - 7);
        } else if (state.view === "day") {
            state.current.setDate(state.current.getDate() - 1);
        } else {
            state.current.setMonth(state.current.getMonth() - 1);
        }
        state.selected = new Date(state.current);
        render();
    });
    document.querySelector("[data-cal-next]")?.addEventListener("click", () => {
        if (state.view === "week") {
            state.current.setDate(state.current.getDate() + 7);
        } else if (state.view === "day") {
            state.current.setDate(state.current.getDate() + 1);
        } else {
            state.current.setMonth(state.current.getMonth() + 1);
        }
        state.selected = new Date(state.current);
        render();
    });
    document.querySelector("[data-cal-today]")?.addEventListener("click", () => {
        state.current = new Date();
        state.selected = new Date();
        render();
    });

    qsa("[data-cal-modal-close]").forEach((btn) => {
        btn.addEventListener("click", () => {
            modal?.classList.add("hidden");
            modal?.classList.remove("flex");
        });
    });
    modal?.addEventListener("click", (e) => {
        if (e.target === modal) {
            modal.classList.add("hidden");
            modal.classList.remove("flex");
        }
    });

    render();
})();
</script>
