$(document).ready(function () {

    // ===============================
    // TOASTR CONFIG
    // ===============================
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000"
    };

    const modal = new bootstrap.Modal(document.getElementById("portfolioModal"));

    // Destroy old table
    if ($.fn.DataTable.isDataTable("#portfolio_config")) {
        $("#portfolio_config").DataTable().clear().destroy();
    }

    const table = $("#portfolio_config").DataTable({
        responsive: true,
        autoWidth: false,
        searching: false,
        ajax: { url: "/portfoliojson", dataSrc: "data" },
        columns: [
            { data: "title", render: t => t || "<span class='text-muted'>N/A</span>" },
            {
                data: "description",
                render: desc => {
                    if (!desc) return "<span class='text-muted'>N/A</span>";
                    const shortDesc = desc.length > 50 ? desc.substring(0, 50) + "..." : desc;
                    return `<span title="${desc}">${shortDesc}</span>`;
                }
            },
            {
                data: "image",
                render: img =>
                    img
                        ? `<img src="${img}" width="80" height="50" class="rounded border" style="object-fit: cover;">`
                        : "<span class='text-muted'>No Image</span>"
            },
            {
                data: null,
                className: "text-center",
                render: row => `
                    <div class="dropdown dropstart">
                        <button class="btn btn-sm btn-light rounded-circle" data-bs-toggle="dropdown">
                            <i class="fa-solid fa-ellipsis-vertical"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow">
                            <li>
                                <button class="dropdown-item edit-btn" data-id="${row._id}">
                                    <i class="fa-solid fa-pen-to-square me-2 text-primary"></i>Edit
                                </button>
                            </li>
                            <li>
                                <button class="dropdown-item delete-btn" data-id="${row._id}">
                                    <i class="fa-solid fa-trash me-2 text-danger"></i>Delete
                                </button>
                            </li>
                        </ul>
                    </div>`
            }
        ],
        order: []
    });

    // ===============================
    // ADD BUTTON
    // ===============================
    $("#addPortfolioBtn").click(() => {
        $("#portfolioForm")[0].reset();
        $("#portfolioId").val("");
        $("#previewImage").hide();
        $("#portfolioModalLabel").text("Add Portfolio Item");
        modal.show();
    });

    // ===============================
    // IMAGE PREVIEW
    // ===============================
    $("#portfolioImage").change(function () {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = e => $("#previewImage").attr("src", e.target.result).show();
            reader.readAsDataURL(file);
        } else {
            $("#previewImage").hide();
        }
    });

    // ===============================
    // AI DESCRIPTION (TOASTR ONLY)
    // ===============================
    $("#generatePortfolioAI").click(function () {
        const title = $("#portfolioTitle").val().trim();
        if (!title) {
            toastr.error("Enter Title first");
            return;
        }

    const loadingToast = toastr.info(
        "AI is writing description...",
        "Please wait",
        { timeOut: 0, extendedTimeOut: 0 }
    );

        $.ajax({
            url: "/generateDescription",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ name: title ,prompt:'Write a concise, engaging, and professional description for a portfolio project in simple English. Highlight key skills, technologies, and benefits. Maximum 20 words.'}),
            success: res => {
            toastr.clear(loadingToast);

                if (!res.success) {
                    toastr.error(res.message || "AI failed");
                    return;
                }
                $("#portfolioDescription").val(res.description);
                toastr.success("Description generated by AI");
            },
            error: () =>{
                 toastr.clear(loadingToast);
                toastr.error("AI generation failed")
            }
        });
    });


    // ===============================
    // SAVE / UPDATE
    // ===============================
    $("#portfolioForm").submit(function (e) {
        e.preventDefault();

        const formData = new FormData();
        const id = $("#portfolioId").val();

        formData.append("title", $("#portfolioTitle").val());
        formData.append("description", $("#portfolioDescription").val());
        if (id) formData.append("id", id);

        const imageFile = $("#portfolioImage")[0].files[0];
        if (imageFile) formData.append("image", imageFile);

        const $submitBtn = $("#portfolioForm button[type='submit']");
        const originalBtnContent = $submitBtn.html();
        $submitBtn.prop("disabled", true);
        $submitBtn.html(`<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`);

        $.ajax({
            url: "/portfoliosave",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: res => {
                $submitBtn.prop("disabled", false).html(originalBtnContent);
                if (res.success) {
                    toastr.success(res.message);
                    modal.hide();
                    $("#portfolioForm")[0].reset();
                    $("#previewImage").hide();
                    table.ajax.reload(null, false);
                } else {
                    toastr.error(res.message);
                }
            },
            error: xhr => {
                  $submitBtn.prop("disabled", false).html(originalBtnContent);
                toastr.error(xhr.responseJSON?.message || "Something went wrong!")
            }
        });
    });

    // ===============================
    // EDIT BUTTON
    // ===============================
    $("#portfolio_config").on("click", ".edit-btn", function () {
        const row = table.row($(this).closest("tr")).data();
        if (!row) {
            toastr.error("Data not found");
            return;
        }

        $("#portfolioForm")[0].reset();
        $("#portfolioId").val(row._id);
        $("#portfolioTitle").val(row.title);
        $("#portfolioDescription").val(row.description);
        if (row.image) $("#previewImage").attr("src", row.image).show();
        $("#portfolioModalLabel").text("Edit Portfolio Item");
        modal.show();
    });

    // ===============================
    // DELETE BUTTON (NO CONFIRM POPUP)
    // ===============================
    $("#portfolio_config").on("click", ".delete-btn", function () {
        const id = $(this).data("id");

      Swal.fire({
    title: "Are you sure?",
    text: "This Portfolio Item will be deleted permanently!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, Delete",
    cancelButtonText: "Cancel"
  }).then((result) => {

    if (!result.isConfirmed) return;

        $.ajax({
            url: `/portfoliodelete/${id}`,
            type: "DELETE",
            success: res => {
                if (res.success) {
                    toastr.success(res.message);
                    table.ajax.reload(null, false);
                } else {
                    toastr.error(res.message);
                }
            },
            error: () => toastr.error("Failed to delete")
        });
    });
      });

});
