<?php
/**
 * @var \App\View\AppView $this
 * @var iterable<\App\Model\Entity\ContactMessage> $contactMessages
 * @var iterable<\App\Model\Entity\ContactMessage> $allMessages
 */
?>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<style>
    .email-item {
        overflow: hidden;
    }
    .email-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .email-item .text-xs {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    #mailMessages {
        overflow: hidden;
    }
    #mailMessages .leading-relaxed {
        word-break: break-word;
        overflow-wrap: break-word;
    }
    #profileInfo {
        overflow: hidden;
    }
    #profileInfo p {
        word-break: break-word;
        overflow-wrap: break-word;
    }
    @media (max-width: 768px) {
        .grid {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        aside.col-span-3:first-of-type {
            width: 100%;
            height: 35%;
            border-right: none;
            border-bottom: 1px solid #e5e7eb;
        }

        main.col-span-6 {
            width: 100%;
            height: 35%;
        }

        aside.col-span-3:last-of-type {
            width: 100%;
            height: 30%;
            border-left: none;
            border-top: 1px solid #e5e7eb;
        }

        #emailList {
            padding: 8px;
        }

        .email-item {
            padding: 10px;
        }

        #mailMessages {
            padding: 10px;
        }

        #profileInfo {
            padding: 10px;
        }
    }
</style>
<input type="hidden" id="csrfToken" value="<?= h($this->request->getAttribute('csrfToken')) ?>">
<div class="w-full h-[85vh] grid grid-cols-12 bg-gray-100 rounded-xl overflow-hidden shadow">
    <aside class="col-span-3 bg-white border-r border-gray-200 flex flex-col overflow-hidden">
        <div class="p-4 border-b">
            <h2 class="text-lg font-semibold">Mailbox</h2>
        </div>

        <div id="emailList" class="flex-1 overflow-y-auto p-2 space-y-3">
            <?php foreach ($allMessages as $msg): ?>
                <?php
                    $fullName = trim(($msg->first_name ?? '') . ' ' . ($msg->last_name ?? ''));
                    $email = $msg->email ?? '';
                    $phone = $msg->phone ?? '';
                    $message = $msg->message ?? '';
                    $createdRaw = !empty($msg->created) ? $msg->created->format('Y-m-d H:i') : '';
                    $isRead = !empty($msg->is_read);

                    $displayTime = '';
                    if (!empty($msg->created)) {
                        $created = $msg->created;
                        $now = new \DateTime();

                        if ($created->format('Y-m-d') === $now->format('Y-m-d')) {
                            $displayTime = $created->format('H:i');
                        } elseif ($created->format('Y') === $now->format('Y')) {
                            $displayTime = $created->format('d M');
                        } else {
                            $displayTime = $created->format('d/m/Y');
                        }
                    }
                ?>

                <div class="mail-row relative overflow-hidden rounded-lg" data-row-id="<?= h((string)$msg->id) ?>" data-open="0">
                    <div class="absolute inset-y-0 right-0 flex items-stretch">
                        <button
                            type="button"
                            class="mark-read-btn w-14 flex items-center justify-center bg-blue-600 text-white"
                            data-id="<?= h((string)$msg->id) ?>"
                            title="<?= $isRead ? 'Mark as unread' : 'Mark as read' ?>"
                        >
                            <i class="bi bi-<?= $isRead ? 'envelope' : 'envelope-open' ?> text-[20px] pointer-events-none"></i>
                        </button>

                        <button
                            type="button"
                            class="delete-btn w-14 flex items-center justify-center bg-red-600 text-white"
                            data-id="<?= h((string)$msg->id) ?>"
                            title="Delete"
                        >
                            <i class="bi bi-trash text-[20px] pointer-events-none"></i>
                        </button>
                    </div>

                    <div
                        class="email-item relative z-10 cursor-pointer p-3 rounded-lg bg-white border transition-all duration-200 ease-out hover:bg-[#dbeafe] hover:border-[#93c5fd] hover:shadow-md <?= $isRead ? 'border-gray-200' : 'border-[#0f172a] border-2' ?>"
                        data-id="<?= h((string)$msg->id) ?>"
                        data-name="<?= h($fullName) ?>"
                        data-email="<?= h($email) ?>"
                        data-subject="Inquiries"
                        data-message="<?= h($message) ?>"
                        data-phone="<?= h($phone) ?>"
                        data-created="<?= h($createdRaw) ?>"
                        data-is-read="<?= $isRead ? '1' : '0' ?>"
                        style="transform: translateX(0px);"
                    >
                        <div class="email-name <?= $isRead ? 'font-normal text-gray-500' : 'font-bold text-gray-900' ?>">
                            <?= h($fullName) ?>
                        </div>

                        <div class="text-xs <?= $isRead ? 'text-gray-500' : 'text-gray-700 font-semibold' ?>">
                            <?= h($email) ?><?= $displayTime ? ' · ' . h($displayTime) : '' ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </aside>

   <main class="col-span-6 bg-gray-50 flex flex-col overflow-hidden">
        <div class="p-4 border-b">
            <h2 id="mailSubject" class="text-xl font-semibold text-gray-800">Inquiries</h2>
            <p id="mailSubtitle" class="text-sm text-gray-500 mt-1">Select a message from the left.</p>
        </div>

        <div id="mailMessages" class="flex-1 p-4 space-y-4 overflow-y-auto">
            <div class="bg-white p-4 rounded-lg shadow border border-gray-200 text-gray-400">
                No message selected.
            </div>
        </div>
    </main>

    <aside class="col-span-3 bg-white border-l border-gray-200 flex flex-col overflow-hidden">
        <div class="p-4 border-b">
            <h2 class="text-lg font-semibold">Details</h2>
        </div>

        <div id="profileInfo" class="flex-1 p-4 text-gray-700 space-y-3 overflow-y-auto">
            <p class="text-gray-400 text-sm">Please select an email for details</p>
        </div>
    </aside>
</div>
<input type="hidden" id="csrfToken" value="<?= h($this->request->getAttribute('csrfToken')) ?>">
<input type="hidden" id="markReadUrl" value="<?= $this->Url->build(['controller' => 'Contact', 'action' => 'markAsRead']) ?>">
<input type="hidden" id="deleteUrl" value="<?= $this->Url->build(['controller' => 'Contact', 'action' => 'deleteMessage']) ?>">
<script>
document.addEventListener("DOMContentLoaded", () => {
    const csrfToken = document.getElementById("csrfToken").value;
    const markReadBaseUrl = document.getElementById("markReadUrl").value;
    const deleteBaseUrl = document.getElementById("deleteUrl").value;
    const ACTION_WIDTH = 112;
    const OPEN_THRESHOLD = 56;
    const items = document.querySelectorAll(".email-item");
    const rows = document.querySelectorAll(".mail-row");
    const mailSubject = document.getElementById("mailSubject");
    const mailSubtitle = document.getElementById("mailSubtitle");
    const mailMessages = document.getElementById("mailMessages");
    const profileInfo = document.getElementById("profileInfo");

    function closeRow(row) {
        const item = row.querySelector(".email-item");
        if (!item) return;
        item.style.transition = "transform 0.2s ease";
        item.style.transform = "translateX(0px)";
        row.dataset.open = "0";
    }

    function openRow(row) {
        const item = row.querySelector(".email-item");
        if (!item) return;
        item.style.transition = "transform 0.2s ease";
        item.style.transform = `translateX(-${ACTION_WIDTH}px)`;
        row.dataset.open = "1";
    }

    function closeAllSwipeRows(exceptRow = null) {
        rows.forEach(row => {
            if (row !== exceptRow) {
                closeRow(row);
            }
        });
    }

    function setReadStyle(item, isRead = true) {
        const nameEl = item.querySelector(".email-name");
        const subEl = item.querySelector(".text-xs");

        item.dataset.isRead = isRead ? "1" : "0";

        if (isRead) {
            item.classList.remove("border-[#0f172a]", "border-2");
            item.classList.add("border-gray-200");

            if (nameEl) {
                nameEl.classList.remove("font-bold", "text-gray-900");
                nameEl.classList.add("font-normal", "text-gray-500");
            }

            if (subEl) {
                subEl.classList.remove("text-gray-700", "font-semibold");
                subEl.classList.add("text-gray-500");
            }
        } else {
            item.classList.remove("border-gray-200");
            item.classList.add("border-[#0f172a]", "border-2");

            if (nameEl) {
                nameEl.classList.remove("font-normal", "text-gray-500");
                nameEl.classList.add("font-bold", "text-gray-900");
            }

            if (subEl) {
                subEl.classList.remove("text-gray-500");
                subEl.classList.add("text-gray-700", "font-semibold");
            }
        }
    }
    async function toggleReadStatus(item, forceStatus = null) {
        const id = item.dataset.id;
        if (!id) return;
        if (forceStatus === 1 && item.dataset.isRead === "1") return;
        const currentIsRead = item.dataset.isRead === "1";
        const nextStatus = (forceStatus !== null) ? forceStatus : (currentIsRead ? 0 : 1);
        try {
            const response = await fetch(`${markReadBaseUrl}/${id}`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': csrfToken,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ is_read: nextStatus })
            });
            const data = await response.json();
            if (data.success) {
                const isReadNow = data.is_read === 1 || data.is_read === true;
                setReadStyle(item, isReadNow);
                const row = item.closest(".mail-row");
                const btn = row.querySelector(".mark-read-btn");
                if (btn) {
                    btn.title = isReadNow ? "Mark as unread" : "Mark as read";
                    const icon = btn.querySelector("i");
                    if (isReadNow) {
                        icon.classList.replace("bi-envelope-open", "bi-envelope");
                    } else {
                        icon.classList.replace("bi-envelope", "bi-envelope-open");
                    }
                }
            }
        } catch (error) {
            console.error('Toggle read status failed:', error);
        }
    }

    async function deleteMessage(row, item) {
        const id = item.dataset.id;

        if (!id) {
            return;
        }

        const confirmed = confirm('Delete this inquiry?');
        if (!confirmed) {
            return;
        }

        try {
            const response = await fetch('/contact/delete-message/' + id, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': csrfToken,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({})
            });

            const data = await response.json();

            if (data.success) {
                row.remove();

                mailSubject.textContent = 'Inquiries';
                mailSubtitle.textContent = 'Select a message from the left.';
                mailMessages.innerHTML = `
                    <div class="bg-white p-4 rounded-lg shadow border border-gray-200 text-gray-400">
                        No message selected.
                    </div>
                `;
                profileInfo.innerHTML = `<p class="text-gray-400 text-sm">Please select an email for details</p>`;
            }
        } catch (error) {
            console.error('Delete failed:', error);
        }
    }

    items.forEach(item => {
        item.addEventListener("click", async () => {
            const row = item.closest(".mail-row");

            if (row && row.dataset.open === "1") {
                return;
            }

            closeAllSwipeRows();

            const name = item.dataset.name || '';
            const email = item.dataset.email || '';
            const subject = item.dataset.subject || 'Inquiries';
            const message = item.dataset.message || '';
            const created = item.dataset.created || '';
            const phone = item.dataset.phone || '';

            mailSubject.textContent = subject;
            mailSubtitle.textContent = `${name} <${email}>`;

            mailMessages.innerHTML = `
                <div class="bg-white p-4 rounded-lg shadow border border-gray-200">
                    <div class="flex justify-between text-sm text-gray-500 mb-3">
                        <span>From: ${name} &lt;${email}&gt;</span>
                        <span>${created}</span>
                    </div>
                    <div class="text-gray-800 leading-relaxed whitespace-pre-line">${message}</div>
                </div>
            `;

            profileInfo.innerHTML = `
                <div>
                    <p class="text-xs text-gray-500">Name</p>
                    <p class="font-medium">${name}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Email</p>
                    <p class="font-medium">${email || '-'}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Phone</p>
                    <p class="font-medium">${phone || '-'}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Time sent</p>
                    <p class="font-medium">${created || '-'}</p>
                </div>
            `;

            await toggleReadStatus(item, 1);
        });
    });

    document.querySelectorAll(".mark-read-btn").forEach(btn => {
        btn.addEventListener("click", async (e) => {
            e.stopPropagation();
            const row = btn.closest(".mail-row");
            const item = row.querySelector(".email-item");
            await toggleReadStatus(item);
            closeRow(row);
        });
    });

    document.querySelectorAll(".delete-btn").forEach(btn => {
        btn.addEventListener("click", async (e) => {
            e.stopPropagation();

            const row = btn.closest(".mail-row");
            const item = row.querySelector(".email-item");

            await deleteMessage(row, item);
        });
    });

    rows.forEach(row => {
        const item = row.querySelector(".email-item");

        let startX = 0;
        let startTranslate = 0;
        let currentX = 0;
        let isDragging = false;

        function getClientX(event) {
            if (event.touches && event.touches.length > 0) {
                return event.touches[0].clientX;
            }
            return event.clientX;
        }

        function startDrag(event) {
            if (event.target.closest(".mark-read-btn") || event.target.closest(".delete-btn")) {
                return;
            }

            isDragging = true;
            startX = getClientX(event);
            startTranslate = row.dataset.open === "1" ? -ACTION_WIDTH : 0;
            currentX = startTranslate;
            item.style.transition = "none";
        }

        function onDrag(event) {
            if (!isDragging) {
                return;
            }

            const clientX = getClientX(event);
            const deltaX = clientX - startX;
            let nextX = startTranslate + deltaX;

            if (nextX < -ACTION_WIDTH) {
                nextX = -ACTION_WIDTH;
            }

            if (nextX > 0) {
                nextX = 0;
            }

            currentX = nextX;
            item.style.transform = `translateX(${currentX}px)`;
        }

        function endDrag() {
            if (!isDragging) {
                return;
            }

            isDragging = false;
            item.style.transition = "transform 0.2s ease";

            if (startTranslate === 0) {
                if (currentX <= -OPEN_THRESHOLD) {
                    closeAllSwipeRows(row);
                    openRow(row);
                } else {
                    closeRow(row);
                }
            } else {
                if (currentX > -OPEN_THRESHOLD) {
                    closeRow(row);
                } else {
                    openRow(row);
                }
            }
        }

        item.addEventListener("mousedown", startDrag);
        window.addEventListener("mousemove", onDrag);
        window.addEventListener("mouseup", endDrag);

        item.addEventListener("touchstart", startDrag, { passive: true });
        item.addEventListener("touchmove", onDrag, { passive: true });
        item.addEventListener("touchend", endDrag);
    });

    document.addEventListener("click", (e) => {
        const clickedRow = e.target.closest(".mail-row");
        const clickedAction = e.target.closest(".mark-read-btn, .delete-btn");

        if (!clickedRow && !clickedAction) {
            closeAllSwipeRows();
        }
    });
});
</script>
