// Products Management JavaScript

let productsData = [];
let productModal;
let quillEditor;
let imageVariants = [];
let productImages = []; // Stores general product images
let currentMediaPicker = null; // Tracks which field is selecting media

// Initialize on page load
document.addEventListener("DOMContentLoaded", function () {
  // Initialize Bootstrap modal
  const productModalElement = document.getElementById("productModal");
  productModal = new bootstrap.Modal(productModalElement);

  // Fix aria-hidden accessibility issue: move focus before modal hides
  productModalElement.addEventListener("hide.bs.modal", function () {
    // Move focus to a safe element outside the modal before it gets aria-hidden
    document.getElementById("btnAddProduct")?.focus();
  });

  // Initialize Quill editor
  initializeQuillEditor();

  // Add event listeners for buttons
  const btnAddProduct = document.getElementById("btnAddProduct");
  if (btnAddProduct) {
    btnAddProduct.addEventListener("click", showCreateProduct);
  }

  // Add event listener for search input
  const searchInput = document.getElementById("searchInput");
  if (searchInput) {
    searchInput.addEventListener("input", filterProducts);
  }

  // Add event listener for save product button
  const btnSaveProduct = document.getElementById("btnSaveProduct");
  if (btnSaveProduct) {
    btnSaveProduct.addEventListener("click", saveProduct);
  }

  // Add event listener for logout button
  const btnLogout = document.getElementById("btnLogout");
  if (btnLogout) {
    btnLogout.addEventListener("click", logout);
  }

  // Add event listener for add image variant button
  const btnAddImageVariant = document.getElementById("btnAddImageVariant");
  if (btnAddImageVariant) {
    btnAddImageVariant.addEventListener("click", addImageVariantField);
  }

  // Check authentication (from auth.js)
  checkAuth().then((authenticated) => {
    if (authenticated) {
      loadProducts();
    }
  });

  // Check if we should open create modal
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.get("action") === "create") {
    showCreateProduct();
  }
});

// Initialize Quill Editor
function initializeQuillEditor() {
  quillEditor = new Quill("#productDescriptionEditor", {
    theme: "snow",
    placeholder: "Write your product description here...",
    modules: {
      toolbar: [
        [{ header: [1, 2, 3, false] }],
        ["bold", "italic", "underline", "strike"],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ color: [] }, { background: [] }],
        ["link", "image"],
        ["clean"],
      ],
    },
  });
}

// Load all products
async function loadProducts() {
  try {
    // Add cache-busting to ensure fresh data
    const response = await fetch(`/api/admin/products?_t=${Date.now()}`, {
      credentials: "include",
      cache: "no-store",
    });

    const data = await response.json();
    if (data.success) {
      productsData = data.products;
      renderProducts(productsData);
    }
  } catch (error) {
    console.error("Failed to load products:", error);
    showError("Failed to load products");
  }
}

// Render products table
function renderProducts(products) {
  const tbody = document.getElementById("productsTableBody");

  if (products.length === 0) {
    tbody.innerHTML = `
      <tr>
        <td colspan="8" class="text-center p-4">
          <i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i>
          <p class="mt-3 text-muted">No products found</p>
          <button class="btn btn-primary" id="btnAddFirstProduct">
            <i class="bi bi-plus-circle"></i> Add Your First Product
          </button>
        </td>
      </tr>
    `;
    // Add event listener to the "Add First Product" button
    setTimeout(() => {
      const btn = document.getElementById("btnAddFirstProduct");
      if (btn) {
        btn.addEventListener("click", showCreateProduct);
      }
    }, 0);
    return;
  }

  tbody.innerHTML = products
    .map(
      (product) => `
    <tr>
      <td>${product.id}</td>
      <td><strong>${escapeHtml(product.name)}</strong></td>
      <td>$${parseFloat(product.price).toFixed(2)}</td>
      <td>${product.stockquantity || 0}</td>
      <td>
        <span class="badge ${
          product.isactive ? "badge-success" : "badge-danger"
        }">
          ${product.isactive ? "Active" : "Inactive"}
        </span>
      </td>
      <td>
        ${
          product.isbestseller
            ? '<span class="badge badge-warning">⭐ Best Seller</span>'
            : "-"
        }
      </td>
      <td>${formatDate(product.createdat)}</td>
      <td>
        <button class="btn btn-sm btn-info" data-action="edit" data-id="${
          product.id
        }">
          <i class="bi bi-pencil"></i>
        </button>
        <button class="btn btn-sm btn-danger" data-action="delete" data-id="${
          product.id
        }" data-name="${escapeHtml(product.name)}">
          <i class="bi bi-trash"></i>
        </button>
      </td>
    </tr>
  `
    )
    .join("");

  // Add event listeners to edit and delete buttons
  tbody.querySelectorAll('button[data-action="edit"]').forEach((btn) => {
    btn.addEventListener("click", () => editProduct(btn.dataset.id));
  });

  tbody.querySelectorAll('button[data-action="delete"]').forEach((btn) => {
    btn.addEventListener("click", () =>
      deleteProduct(btn.dataset.id, btn.dataset.name)
    );
  });
}

// Filter products
function filterProducts() {
  const searchTerm = document.getElementById("searchInput").value.toLowerCase();
  const filtered = productsData.filter((product) =>
    product.name.toLowerCase().includes(searchTerm)
  );
  renderProducts(filtered);
}

// Show create product modal
function showCreateProduct() {
  document.getElementById("modalTitle").textContent = "Add New Product";
  document.getElementById("productForm").reset();
  document.getElementById("productId").value = "";
  document.getElementById("productActive").checked = true;

  // Clear Quill editor
  if (quillEditor) {
    quillEditor.setContents([]);
  }

  // Clear arrays
  productImages = [];
  imageVariants = [];
  renderProductImages();
  renderImageVariants();

  productModal.show();
}

// Add image variant field
function addImageVariantField() {
  const variant = {
    id: Date.now().toString(),
    image_url: "",
    color_variant: "",
    color_code: "#000000",
    alt_text: "",
    variant_price: null,
    variant_stock: 0,
    is_primary: imageVariants.length === 0,
  };
  imageVariants.push(variant);
  renderImageVariants();
}

// Render product images gallery
function renderProductImages() {
  const gallery = document.getElementById("productImagesGallery");

  if (!gallery) return;

  if (productImages.length === 0) {
    gallery.innerHTML = `
      <div class="text-muted small">
        No images added yet. Click above to add images.
      </div>
    `;
    return;
  }

  gallery.innerHTML = productImages
    .map(
      (img, index) => `
      <div class="position-relative" style="width: 100px; height: 100px;">
        <img 
          src="${img.url}" 
          alt="${img.filename}" 
          class="img-thumbnail w-100 h-100 object-fit-cover"
          title="${img.filename}"
        />
        <button 
          type="button" 
          class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 p-1"
          onclick="removeProductImage(${index})"
          style="line-height: 1; width: 24px; height: 24px; font-size: 12px;"
        >
          <i class="bi bi-x"></i>
        </button>
      </div>
    `
    )
    .join("");
}

// Remove product image
function removeProductImage(index) {
  productImages.splice(index, 1);
  renderProductImages();
}

// Render image variant fields
function renderImageVariants() {
  const container = document.getElementById("imageVariantsContainer");

  if (imageVariants.length === 0) {
    container.innerHTML = `
      <div class="text-center text-muted p-3">
        <i class="bi bi-palette" style="font-size: 2rem;"></i>
        <p class="mb-0 mt-2">No color variants added yet. Add product images above first, then create color variants here.</p>
      </div>
    `;
    return;
  }

  container.innerHTML = imageVariants
    .map((variant, index) => {
      // Generate image picker HTML with thumbnails
      const imagePickerHTML =
        productImages.length > 0
          ? `
        <div class="image-picker-grid" data-variant-id="${variant.id}">
          ${productImages
            .map((img, idx) => {
              const isSelected = img.url === variant.image_url;
              return `
              <div class="image-picker-item ${isSelected ? "selected" : ""}" 
                   data-image-url="${img.url}" 
                   data-variant-id="${variant.id}"
                   title="${img.filename || "Image " + (idx + 1)}">
                <img src="${img.url}" alt="${
                img.filename || "Image " + (idx + 1)
              }">
                <div class="image-picker-overlay">
                  <i class="bi bi-check-circle-fill"></i>
                </div>
                <small class="image-picker-label">${
                  img.filename || "Image " + (idx + 1)
                }</small>
              </div>
            `;
            })
            .join("")}
        </div>
      `
          : '<small class="text-danger">Add product images first</small>';

      return `
    <div class="image-variant-item mb-3 p-3 border rounded" data-variant-id="${
      variant.id
    }" style="background: #f8f9fa;">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h6 class="mb-0">
          <i class="bi bi-palette"></i> Color Variant ${index + 1}
          ${
            variant.is_primary
              ? '<span class="badge bg-primary ms-2">Primary</span>'
              : ""
          }
        </h6>
        <button type="button" class="btn btn-sm btn-danger" data-action="remove" data-variant-id="${
          variant.id
        }">
          <i class="bi bi-trash"></i> Remove
        </button>
      </div>
      
      <div class="row">
        <!-- Image Selector with Visual Preview -->
        <div class="col-md-12 mb-3">
          <label class="form-label small fw-bold">Select Image *</label>
          ${imagePickerHTML}
        </div>
        
        <!-- Color Name -->
        <div class="col-md-6 mb-3">
          <label class="form-label small fw-bold">Color Name *</label>
          <input
            type="text"
            class="form-control form-control-sm"
            placeholder="e.g., Ruby Red, Ocean Blue"
            value="${variant.color_variant || ""}"
            data-field="color_variant"
            data-variant-id="${variant.id}"
          />
        </div>
      </div>
      
      <div class="row">
        <!-- Color Picker -->
        <div class="col-md-3 mb-3">
          <label class="form-label small fw-bold">Color Code</label>
          <div class="d-flex gap-2 align-items-center">
            <input
              type="color"
              class="form-control form-control-color"
              value="${variant.color_code || "#000000"}"
              data-field="color_code"
              data-variant-id="${variant.id}"
              style="width: 60px; height: 38px;"
            />
            <input
              type="text"
              class="form-control form-control-sm"
              placeholder="#000000"
              value="${variant.color_code || ""}"
              data-field="color_code_text"
              data-variant-id="${variant.id}"
              maxlength="7"
              style="font-family: monospace;"
            />
          </div>
        </div>
        
        <!-- Variant Price -->
        <div class="col-md-3 mb-3">
          <label class="form-label small fw-bold">Variant Price</label>
          <div class="input-group input-group-sm">
            <span class="input-group-text">$</span>
            <input
              type="number"
              class="form-control form-control-sm"
              placeholder="Optional"
              value="${variant.variant_price || ""}"
              data-field="variant_price"
              data-variant-id="${variant.id}"
              step="0.01"
              min="0"
            />
          </div>
          <small class="text-muted">Leave empty to use base price</small>
        </div>
        
        <!-- Variant Stock -->
        <div class="col-md-3 mb-3">
          <label class="form-label small fw-bold">Stock Quantity *</label>
          <input
            type="number"
            class="form-control form-control-sm"
            placeholder="0"
            value="${variant.variant_stock || 0}"
            data-field="variant_stock"
            data-variant-id="${variant.id}"
            min="0"
          />
        </div>
        
        <!-- Primary Checkbox -->
        <div class="col-md-3 mb-3">
          <label class="form-label small fw-bold">Primary Image</label>
          <div class="form-check">
            <input
              type="radio"
              class="form-check-input"
              name="primaryVariant"
              ${variant.is_primary ? "checked" : ""}
              data-field="is_primary"
              data-variant-id="${variant.id}"
            />
            <label class="form-check-label small">
              Set as primary
            </label>
          </div>
        </div>
      </div>
      
      <!-- Alt Text -->
      <div class="row">
        <div class="col-12 mb-2">
          <label class="form-label small">Alt Text (for accessibility)</label>
          <input
            type="text"
            class="form-control form-control-sm"
            placeholder="Description of the image"
            value="${variant.alt_text || ""}"
            data-field="alt_text"
            data-variant-id="${variant.id}"
          />
        </div>
      </div>
    </div>
  `;
    })
    .join("");

  // Add event listeners for remove buttons
  container.querySelectorAll('[data-action="remove"]').forEach((btn) => {
    btn.addEventListener("click", (e) => {
      const id = e.currentTarget.dataset.variantId;
      imageVariants = imageVariants.filter((v) => String(v.id) !== String(id));
      renderImageVariants();
    });
  });

  // Add event listeners for image picker items
  container.querySelectorAll(".image-picker-item").forEach((item) => {
    item.addEventListener("click", (e) => {
      const variantId = e.currentTarget.dataset.variantId;
      const imageUrl = e.currentTarget.dataset.imageUrl;
      const variant = imageVariants.find(
        (v) => String(v.id) === String(variantId)
      );

      console.log("Image picker clicked:", { variantId, imageUrl, variant });

      if (variant) {
        variant.image_url = imageUrl;

        // Update visual selection
        const pickerGrid = e.currentTarget.closest(".image-picker-grid");
        pickerGrid
          .querySelectorAll(".image-picker-item")
          .forEach((i) => i.classList.remove("selected"));
        e.currentTarget.classList.add("selected");

        console.log("Updated variant with new image:", variant);
      }
    });
  });

  // Add event listeners for input changes
  container.querySelectorAll("[data-variant-id]").forEach((input) => {
    // Use 'input' for text/number fields, 'change' for radio/checkbox
    const eventType =
      input.type === "radio" || input.type === "checkbox" ? "change" : "input";
    input.addEventListener(eventType, (e) => {
      const id = e.target.dataset.variantId;
      const field = e.target.dataset.field;
      const variant = imageVariants.find((v) => String(v.id) === String(id));

      console.log("Input change:", {
        id,
        field,
        value: e.target.value,
        variant,
      });

      if (variant) {
        if (field === "color_code_text") {
          // Update both color picker and text
          variant.color_code = e.target.value;
          const colorPicker = container.querySelector(
            `input[type="color"][data-variant-id="${id}"]`
          );
          if (colorPicker && /^#[0-9A-F]{6}$/i.test(e.target.value)) {
            colorPicker.value = e.target.value;
          }
        } else if (field === "color_code") {
          // Update both color picker and text
          variant.color_code = e.target.value;
          const colorText = container.querySelector(
            `input[data-field="color_code_text"][data-variant-id="${id}"]`
          );
          if (colorText) {
            colorText.value = e.target.value;
          }
        } else if (field === "is_primary") {
          // Set all to false, then this one to true
          imageVariants.forEach((v) => (v.is_primary = false));
          variant.is_primary = true;
        } else {
          variant[field] = e.target.value;
        }
        console.log("Updated variant:", variant);
      }
    });
  });
}

// Edit product
async function editProduct(id) {
  try {
    console.log("Loading product for edit, ID:", id);

    const response = await fetch(`/api/admin/products/${id}`, {
      credentials: "include",
    });

    const data = await response.json();
    console.log("Product data loaded:", data);

    if (data.success) {
      const product = data.product;

      document.getElementById("modalTitle").textContent = "Edit Product";
      document.getElementById("productId").value = product.id;
      document.getElementById("productName").value = product.name;
      document.getElementById("productShortDescription").value =
        product.shortdescription || "";

      // Set Quill editor content
      if (quillEditor && product.description) {
        quillEditor.root.innerHTML = product.description;
      }

      document.getElementById("productPrice").value = product.price;
      document.getElementById("productStock").value =
        product.stockquantity || 0;
      document.getElementById("productSKU").value = product.sku || "";
      document.getElementById("productCategory").value = product.category || "";
      document.getElementById("productMaterial").value = product.material || "";
      document.getElementById("productDimensions").value =
        product.dimensions || "";
      document.getElementById("productWeight").value = product.weight || "";
      document.getElementById("productActive").checked = product.isactive;
      document.getElementById("productFeatured").checked =
        product.isfeatured || false;
      document.getElementById("productBestSeller").checked =
        product.isbestseller || false;

      // Load image variants and extract unique product images
      // Convert numeric IDs to strings for consistency with newly created variants
      imageVariants = (product.images || []).map((img) => ({
        ...img,
        id: String(img.id),
      }));
      console.log("Loaded image variants:", imageVariants);

      // Build productImages array from unique image URLs in variants
      const uniqueImages = {};
      imageVariants.forEach((variant) => {
        if (variant.image_url && !uniqueImages[variant.image_url]) {
          uniqueImages[variant.image_url] = {
            url: variant.image_url,
            filename: variant.image_url.split("/").pop(),
            alt_text: variant.alt_text || "",
          };
        }
      });
      productImages = Object.values(uniqueImages);

      renderProductImages();
      renderImageVariants();

      productModal.show();
    } else {
      showError(data.message || "Failed to load product");
    }
  } catch (error) {
    console.error("Failed to load product:", error);
    showError("Failed to load product details: " + error.message);
  }
}

// Save product
async function saveProduct() {
  const id = document.getElementById("productId").value;
  const saveButton = document.getElementById("btnSaveProduct");

  // Disable button and show loading state
  saveButton.disabled = true;
  const originalButtonHTML = saveButton.innerHTML;
  saveButton.innerHTML = '<i class="bi bi-hourglass-split"></i> Saving...';
  saveButton.style.opacity = "0.7";

  // Get description from Quill editor
  const description = quillEditor.root.innerHTML;

  console.log("=== SAVE PRODUCT DEBUG ===");
  console.log("Product ID:", id);
  console.log("Image Variants:", imageVariants);
  console.log("Product Images:", productImages);

  // Prepare images array - include BOTH product images AND color variants
  const images = [];

  // First, add all color variants (they have color_variant/color_code)
  imageVariants.forEach((variant, index) => {
    images.push({
      image_url: variant.image_url,
      color_variant: variant.color_variant || null,
      color_code: variant.color_code || null,
      alt_text:
        variant.alt_text || document.getElementById("productName").value,
      display_order: index,
      is_primary:
        variant.is_primary || (index === 0 && imageVariants.length > 0),
      variant_price: variant.variant_price
        ? parseFloat(variant.variant_price)
        : null,
      variant_stock: parseInt(variant.variant_stock) || 0,
    });
  });

  // Then add regular product images (without color variants)
  // Skip images that are already in imageVariants
  const variantUrls = imageVariants.map((v) => v.image_url);
  productImages.forEach((img, index) => {
    if (!variantUrls.includes(img.url)) {
      images.push({
        image_url: img.url,
        color_variant: null,
        color_code: null,
        alt_text:
          img.alt_text ||
          img.filename ||
          document.getElementById("productName").value,
        display_order: imageVariants.length + index,
        is_primary: images.length === 0, // First image overall is primary
        variant_price: null,
        variant_stock: 0,
      });
    }
  });

  console.log("Prepared images array (variants + regular):", images);

  const formData = {
    name: document.getElementById("productName").value,
    shortdescription: document.getElementById("productShortDescription").value,
    description: description,
    price: parseFloat(document.getElementById("productPrice").value),
    stockquantity: parseInt(document.getElementById("productStock").value) || 0,
    sku: document.getElementById("productSKU").value,
    category: document.getElementById("productCategory").value,
    material: document.getElementById("productMaterial").value,
    dimensions: document.getElementById("productDimensions").value,
    weight: parseFloat(document.getElementById("productWeight").value) || null,
    isactive: document.getElementById("productActive").checked,
    isfeatured: document.getElementById("productFeatured").checked,
    isbestseller: document.getElementById("productBestSeller").checked,
    images: images,
  };

  console.log("Form Data:", formData);

  // Validation
  if (!formData.name || !formData.price) {
    saveButton.disabled = false;
    saveButton.innerHTML = originalButtonHTML;
    saveButton.style.opacity = "1";
    showError("Please fill in all required fields (Name and Price)");
    return;
  }

  // Validate that we have at least one image (either variant or regular)
  if (images.length === 0) {
    saveButton.disabled = false;
    saveButton.innerHTML = originalButtonHTML;
    saveButton.style.opacity = "1";
    showError("Please add at least one product image");
    return;
  }

  // Only validate image URLs exist
  if (images.some((img) => !img.image_url)) {
    saveButton.disabled = false;
    saveButton.innerHTML = originalButtonHTML;
    saveButton.style.opacity = "1";
    showError("All images must have a valid image URL");
    return;
  }

  // If a color_variant name is provided, require color_code
  if (images.some((img) => img.color_variant && !img.color_code)) {
    saveButton.disabled = false;
    saveButton.innerHTML = originalButtonHTML;
    saveButton.style.opacity = "1";
    showError("All color variants must have both a color name and color code");
    return;
  }

  try {
    const url = id ? `/api/admin/products/${id}` : "/api/admin/products";
    const method = id ? "PUT" : "POST";

    console.log("Saving product:", method, url, formData);

    const response = await fetch(url, {
      method: method,
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include",
      body: JSON.stringify(formData),
    });

    console.log("Response status:", response.status);

    if (!response.ok) {
      const errorText = await response.text();
      console.error("Response error:", errorText);
      throw new Error(`Server error: ${response.status} - ${errorText}`);
    }

    const data = await response.json();
    console.log("Response data:", data);

    if (data.success) {
      // Change button to success state briefly
      saveButton.innerHTML = '<i class="bi bi-check-circle-fill"></i> Saved!';
      saveButton.style.background = "#10b981";

      // Show success toast
      showSuccess(
        id
          ? "✅ Product Updated Successfully! Changes are now live on your website."
          : "✅ Product Created Successfully! Now visible on your shop page."
      );

      // Notify frontend of product changes
      notifyFrontendChange("products");

      // Wait a moment then close modal
      setTimeout(async () => {
        productModal.hide();

        // Reload products to show updated data
        await loadProducts();

        // Clear form for next use
        imageVariants = [];
        productImages = [];

        // Reset button
        saveButton.disabled = false;
        saveButton.innerHTML = originalButtonHTML;
        saveButton.style.opacity = "1";
        saveButton.style.background = "";
      }, 1000);
    } else {
      saveButton.disabled = false;
      saveButton.innerHTML = originalButtonHTML;
      saveButton.style.opacity = "1";
      showError(data.message || "Failed to save product");
    }
  } catch (error) {
    console.error("Failed to save product:", error);
    saveButton.disabled = false;
    saveButton.innerHTML = originalButtonHTML;
    saveButton.style.opacity = "1";
    showError(`Failed to save product: ${error.message}`);
  }
}

// Delete product
async function deleteProduct(id, name) {
  showDeleteConfirm(
    `Are you sure you want to delete "${name}"? This action cannot be undone.`,
    async () => {
      try {
        // Immediately remove from UI for instant feedback
        const row = document
          .querySelector(`tr button[data-id="${id}"]`)
          ?.closest("tr");
        if (row) {
          row.style.opacity = "0.5";
          row.style.pointerEvents = "none";
        }

        const response = await fetch(`/api/admin/products/${id}`, {
          method: "DELETE",
          credentials: "include",
        });

        const data = await response.json();

        if (data.success) {
          // Remove from local array immediately
          productsData = productsData.filter((p) => p.id !== id);
          // Re-render without waiting for server
          renderProducts(productsData);
          showSuccess("Product deleted successfully");
          // Also trigger frontend cache invalidation
          notifyFrontendChange("products");
        } else {
          // Restore row if delete failed
          if (row) {
            row.style.opacity = "1";
            row.style.pointerEvents = "auto";
          }
          showError(data.message || "Failed to delete product");
        }
      } catch (error) {
        console.error("Delete error:", error);
        showError("Failed to delete product");
        // Reload to restore state
        loadProducts();
      }
    },
    { title: "Delete Product", confirmText: "Delete Product" }
  );
}

// ===== MEDIA LIBRARY INTEGRATION =====

let productMediaLibrary = null;

function initProductMediaLibrary() {
  productMediaLibrary = new MediaLibrary({
    selectMode: true,
    multiple: true,
    onSelect: handleMediaSelection,
  });
}

// Open media library modal
function openMediaLibrary(purpose) {
  currentMediaPicker = { purpose }; // purpose: 'productImage' or 'variantImage'

  if (!productMediaLibrary) {
    initProductMediaLibrary();
  }

  productMediaLibrary.open();
}

function handleMediaSelection(media) {
  if (!currentMediaPicker) return;

  if (currentMediaPicker.purpose === "productImage") {
    // Handle multiple images - media is array in multi-select mode
    const mediaArray = Array.isArray(media) ? media : [media];

    // Add all selected images to product images array
    mediaArray.forEach((item) => {
      // Check if image already exists - use path instead of url
      if (!productImages.find((img) => img.url === item.path)) {
        productImages.push({
          url: item.path,
          alt_text: item.name || "",
          filename: item.name,
        });
      }
    });

    renderProductImages();
    showSuccess(`${mediaArray.length} image(s) added to product gallery`);
  }

  currentMediaPicker = null;
}

// ===== UTILITY FUNCTIONS =====

// Utility functions
function escapeHtml(text) {
  const map = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#039;",
  };
  return text.replace(/[&<>"']/g, (m) => map[m]);
}

function formatDate(dateString) {
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

function showSuccess(message) {
  console.log("✅ SUCCESS:", message);
  showToast(message, "success");
}

function showError(message) {
  console.error("❌ ERROR:", message);
  showToast(message, "error");
}

function showToast(message, type = "info") {
  console.log("📢 Showing toast:", type, message);

  // Create toast container if it doesn't exist
  let container = document.getElementById("toastContainer");
  if (!container) {
    container = document.createElement("div");
    container.id = "toastContainer";
    container.className = "toast-container";
    document.body.appendChild(container);
    console.log("Created toast container");
  }

  // Create toast element
  const toast = document.createElement("div");
  toast.className = `toast toast-${type} toast-show`;

  // Set icon based on type
  let icon = "";
  if (type === "success") {
    icon = '<i class="bi bi-check-circle-fill"></i>';
  } else if (type === "error") {
    icon = '<i class="bi bi-exclamation-circle-fill"></i>';
  } else if (type === "info") {
    icon = '<i class="bi bi-info-circle-fill"></i>';
  } else if (type === "warning") {
    icon = '<i class="bi bi-exclamation-triangle-fill"></i>';
  }

  toast.innerHTML = `
    <div class="toast-icon">${icon}</div>
    <div class="toast-message">${escapeHtml(message)}</div>
    <button class="toast-close" onclick="this.parentElement.remove()">
      <i class="bi bi-x"></i>
    </button>
  `;

  container.appendChild(toast);
  console.log("Toast appended to container");

  // Auto remove after 4 seconds
  setTimeout(() => {
    toast.classList.remove("toast-show");
    toast.classList.add("toast-hide");
    setTimeout(() => {
      if (toast.parentElement) {
        toast.remove();
      }
    }, 300);
  }, 4000);
}
