<!DOCTYPE html>
<html lang="en">
<head>
  <title><%= title %></title>
  <%- include('partials/head') %>
</head>
<body class="bg-surface text-on-surface selection:bg-primary-fixed">
<%- include('partials/sidebar') %>
<%- include('partials/flash') %>

<div class="ml-64 min-h-screen pb-24 flex flex-col">

  <!-- Sticky Header -->
  <header class="sticky top-0 z-30 bg-white/80 backdrop-blur-md px-12 h-20 flex items-center justify-between border-b border-outline-variant/10">
    <div class="flex items-center gap-4">
      <a class="text-slate-400 hover:text-on-surface transition-colors" href="/products">
        <span class="material-symbols-outlined">arrow_back</span>
      </a>
      <div>
        <h1 class="text-2xl font-headline font-extrabold tracking-tight text-on-surface">
          <%= product && product.id ? 'Edit Product' : 'Add Product' %>
        </h1>
        <p class="text-xs text-on-surface-variant font-medium"><%= product && product.id ? 'Editing • ' + product.title : 'New Listing • Draft' %></p>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <a href="/products" class="px-6 py-2.5 rounded-xl border border-outline-variant/20 text-on-surface font-semibold text-sm hover:bg-surface-container-high transition-all">Discard</a>
      <button type="submit" form="product-form" class="px-8 py-2.5 rounded-xl bg-gradient-to-r from-primary to-primary-container text-on-primary font-bold text-sm shadow-lg shadow-primary/10 hover:opacity-90 transition-all active:scale-95">
        Save Product
      </button>
    </div>
  </header>

  <% if (error) { %>
  <div class="mx-12 mt-4 p-4 bg-error-container text-on-error-container rounded-lg text-sm flex items-center gap-2">
    <span class="material-symbols-outlined text-sm">error</span> <%= error %>
  </div>
  <% } %>

  <form id="product-form"
    action="<%= product && product.id ? '/products/'+product.id : '/products' %>"
    method="POST"
    enctype="multipart/form-data">

    <!-- Hidden fields -->
    <input type="hidden" name="variants" id="variants-hidden" value="<%= product && product.variants ? (typeof product.variants === 'string' ? product.variants : JSON.stringify(product.variants)) : '[]' %>"/>
    <input type="hidden" name="existing_images" id="existing-images-input" value="<%= product && product.images ? (typeof product.images === 'string' ? product.images : JSON.stringify(product.images)) : '[]' %>"/>
    <input type="hidden" name="description" id="description-hidden" value=""/>

    <div class="max-w-6xl mx-auto px-12 mt-8 grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- Main Column -->
      <div class="lg:col-span-2 space-y-8">

        <!-- Product Info -->
        <section class="bg-surface-container-lowest p-8 rounded-xl ring-1 ring-on-surface/[0.02]">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-headline font-bold text-on-surface">Product Information</h2>
          </div>
          <div class="space-y-6">
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Title *</label>
              <input id="product-title" name="title" type="text" required
                value="<%= product && product.title ? product.title : '' %>"
                class="w-full bg-surface-container-low border-none rounded-lg p-4 text-on-surface focus:ring-2 focus:ring-primary focus:bg-surface-container-lowest transition-all placeholder:text-slate-400"
                placeholder="e.g. Minimalist Ceramic Vase"/>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Description</label>
              <div class="rounded-lg overflow-hidden bg-surface-container-low ring-1 ring-outline-variant/10">
                <div class="flex items-center gap-1 p-2 bg-surface-container border-b border-outline-variant/5" id="editor-toolbar">
                  <button type="button" data-cmd="bold" title="Bold"
                    class="toolbar-btn p-2 hover:bg-surface-container-high rounded font-bold text-xs">
                    <span class="material-symbols-outlined text-sm">format_bold</span>
                  </button>
                  <button type="button" data-cmd="italic" title="Italic"
                    class="toolbar-btn p-2 hover:bg-surface-container-high rounded">
                    <span class="material-symbols-outlined text-sm">format_italic</span>
                  </button>
                  <button type="button" data-cmd="insertUnorderedList" title="Bullet List"
                    class="toolbar-btn p-2 hover:bg-surface-container-high rounded">
                    <span class="material-symbols-outlined text-sm">format_list_bulleted</span>
                  </button>
                  <button type="button" data-cmd="createLink" title="Insert Link"
                    class="toolbar-btn p-2 hover:bg-surface-container-high rounded">
                    <span class="material-symbols-outlined text-sm">link</span>
                  </button>
                </div>
                <div id="description-editor"
                  contenteditable="true"
                  class="w-full bg-transparent border-none p-4 text-on-surface focus:ring-0 focus:outline-none min-h-[140px] placeholder:text-slate-400"
                  style="min-height:140px"
                  data-placeholder="Describe your product's unique story and features..."><%- product && product.description ? product.description : '' %></div>
              </div>
            </div>
          </div>
        </section>

        <!-- Media Upload -->
        <section class="bg-surface-container-lowest p-8 rounded-xl ring-1 ring-on-surface/[0.02]">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-headline font-bold text-on-surface">Media</h2>
            <span class="text-xs text-on-surface-variant">JPG, PNG, WebP — max 5MB each</span>
          </div>
          <input type="file" id="image-input" name="images" accept="image/*" multiple class="hidden"/>
          <div id="images-grid" class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <!-- Upload slot -->
            <div id="upload-slot"
              class="aspect-square relative group overflow-hidden rounded-xl bg-surface-container-low flex flex-col items-center justify-center border-2 border-dashed border-outline-variant/30 hover:border-primary/50 transition-colors cursor-pointer"
              onclick="document.getElementById('image-input').click()">
              <span class="material-symbols-outlined text-3xl text-primary/40 mb-2">add_photo_alternate</span>
              <span class="text-[10px] font-bold text-slate-400 uppercase">Upload Image</span>
            </div>
          </div>
        </section>

        <!-- Variants -->
        <section class="bg-surface-container-lowest p-8 rounded-xl ring-1 ring-on-surface/[0.02]">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-headline font-bold text-on-surface">Variants</h2>
            <button type="button" id="add-variant-btn"
              class="flex items-center gap-2 px-4 py-2 bg-secondary-container text-on-secondary-container rounded-lg font-bold text-xs transition-transform active:scale-95 hover:opacity-80">
              <span class="material-symbols-outlined text-sm">add</span>
              Add Option
            </button>
          </div>
          <div id="variants-list" class="space-y-4"></div>
          <p id="variants-empty" class="text-sm text-on-surface-variant text-center py-4 hidden">No variants added. Click "Add Option" to create size, color, or other options.</p>
        </section>
      </div>

      <!-- Right Column -->
      <div class="space-y-8">
        <!-- Pricing & Inventory -->
        <section class="bg-surface-container-lowest p-8 rounded-xl ring-1 ring-on-surface/[0.02]">
          <h2 class="text-lg font-headline font-bold text-on-surface mb-6">Pricing &amp; Inventory</h2>
          <div class="space-y-6">
            <div class="grid grid-cols-2 gap-4">
              <div class="space-y-2">
                <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Price *</label>
                <div class="relative">
                  <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">$</span>
                  <input name="price" type="number" step="0.01" min="0" required
                    value="<%= product && product.price ? product.price : '' %>"
                    class="w-full bg-surface-container-low border-none rounded-lg p-3 pl-8 text-on-surface font-bold focus:ring-2 focus:ring-primary transition-all"
                    placeholder="0.00"/>
                </div>
              </div>
              <div class="space-y-2">
                <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Cost</label>
                <div class="relative">
                  <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">$</span>
                  <input name="cost" type="number" step="0.01" min="0"
                    value="<%= product && product.cost ? product.cost : '' %>"
                    class="w-full bg-surface-container-low border-none rounded-lg p-3 pl-8 text-on-surface font-medium focus:ring-2 focus:ring-primary transition-all"
                    placeholder="0.00"/>
                </div>
              </div>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">SKU</label>
              <input name="sku" type="text"
                value="<%= product && product.sku ? product.sku : '' %>"
                class="w-full bg-surface-container-low border-none rounded-lg p-3 text-on-surface font-mono text-sm focus:ring-2 focus:ring-primary transition-all"
                placeholder="PROD-001"/>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Available Stock</label>
              <input name="stock" type="number" min="0"
                value="<%= product && product.stock !== undefined ? product.stock : 0 %>"
                class="w-full bg-surface-container-low border-none rounded-lg p-3 text-on-surface font-bold focus:ring-2 focus:ring-primary transition-all"
                placeholder="0"/>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Status</label>
              <select name="status" class="w-full bg-surface-container-low border-none rounded-lg p-3 text-on-surface focus:ring-2 focus:ring-primary transition-all">
                <option value="draft" <%= (!product || product.status === 'draft') ? 'selected' : '' %>>Draft</option>
                <option value="active" <%= (product && product.status === 'active') ? 'selected' : '' %>>Active</option>
                <option value="archived" <%= (product && product.status === 'archived') ? 'selected' : '' %>>Archived</option>
              </select>
            </div>
            <label class="flex items-center gap-3 cursor-pointer">
              <div class="relative inline-flex items-center">
                <input type="checkbox" name="continue_selling" class="sr-only peer" value="1"
                  <%= (product && product.continue_selling_when_out) ? 'checked' : '' %>/>
                <div class="w-10 h-5 bg-slate-200 peer-focus:ring-2 peer-focus:ring-primary/20 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-primary"></div>
              </div>
              <span class="text-sm text-on-surface font-medium">Continue selling when out of stock</span>
            </label>
          </div>
        </section>

        <!-- SEO Settings -->
        <section class="bg-surface-container-lowest p-8 rounded-xl ring-1 ring-on-surface/[0.02]">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-headline font-bold text-on-surface">SEO Settings</h2>
            <span class="material-symbols-outlined text-slate-400">search</span>
          </div>
          <div class="space-y-6">
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Page Title</label>
              <input id="seo-title" name="seo_title" type="text"
                value="<%= product && product.seo_title ? product.seo_title : '' %>"
                class="w-full bg-surface-container-low border-none rounded-lg p-3 text-sm focus:ring-2 focus:ring-primary transition-all"
                placeholder="Product name for Google"/>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">Meta Description</label>
              <textarea name="seo_description" rows="3"
                class="w-full bg-surface-container-low border-none rounded-lg p-3 text-sm focus:ring-2 focus:ring-primary transition-all"
                placeholder="Briefly summarize for search results..."><%= product && product.seo_description ? product.seo_description : '' %></textarea>
            </div>
            <div class="space-y-2">
              <label class="text-xs font-label font-bold text-on-surface-variant uppercase tracking-wider">URL Handle</label>
              <div class="flex items-center gap-1 bg-surface-container-low rounded-lg px-3 py-2 text-slate-400 text-xs font-medium">
                <span class="shrink-0">store/products/</span>
                <input id="url-handle" name="url_handle" type="text"
                  value="<%= product && product.url_handle ? product.url_handle : '' %>"
                  class="bg-transparent border-none p-0 text-on-surface focus:ring-0 text-xs font-bold w-full"
                  placeholder="product-url"/>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </form>
</div>

<script>
// ─── Description Editor ──────────────────────────────────────────────────────
const editor = document.getElementById('description-editor');
const descHidden = document.getElementById('description-hidden');

// Placeholder behaviour
editor.addEventListener('focus', () => {
  if (editor.innerHTML === '') editor.classList.remove('empty');
});
editor.addEventListener('blur', () => {
  if (editor.innerHTML === '' || editor.innerHTML === '<br>') {
    editor.innerHTML = '';
  }
});

// Toolbar buttons use execCommand
document.querySelectorAll('.toolbar-btn').forEach(btn => {
  btn.addEventListener('mousedown', e => {
    e.preventDefault(); // keep editor focus
    const cmd = btn.dataset.cmd;
    if (cmd === 'createLink') {
      const url = prompt('Enter URL:', 'https://');
      if (url) document.execCommand('createLink', false, url);
    } else {
      document.execCommand(cmd, false, null);
    }
    // Highlight active state
    btn.classList.toggle('bg-surface-container-high', document.queryCommandState(cmd));
  });
});

// Sync to hidden field on submit
document.getElementById('product-form').addEventListener('submit', () => {
  descHidden.value = editor.innerHTML === '<br>' ? '' : editor.innerHTML;
});

// Sync toolbar active state on selection change
editor.addEventListener('keyup', updateToolbarState);
editor.addEventListener('mouseup', updateToolbarState);
function updateToolbarState() {
  document.querySelectorAll('.toolbar-btn').forEach(btn => {
    const cmd = btn.dataset.cmd;
    if (cmd !== 'createLink') {
      btn.classList.toggle('bg-surface-container-high', document.queryCommandState(cmd));
    }
  });
}

// ─── Title → URL Handle + SEO Title ─────────────────────────────────────────
const titleInput = document.getElementById('product-title');
const urlHandleInput = document.getElementById('url-handle');
const seoTitleInput = document.getElementById('seo-title');

titleInput.addEventListener('input', () => {
  const slug = titleInput.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  if (!urlHandleInput.dataset.edited) urlHandleInput.value = slug;
  if (!seoTitleInput.dataset.edited) seoTitleInput.value = titleInput.value;
});
urlHandleInput.addEventListener('input', () => { urlHandleInput.dataset.edited = '1'; });
seoTitleInput.addEventListener('input', () => { seoTitleInput.dataset.edited = '1'; });

// ─── Image Upload ────────────────────────────────────────────────────────────
let existingImages = [];
try {
  existingImages = JSON.parse(document.getElementById('existing-images-input').value || '[]');
} catch(e) { existingImages = []; }

let pendingFiles = []; // { file, url }

function renderImages() {
  const grid = document.getElementById('images-grid');
  const uploadSlot = document.getElementById('upload-slot');
  grid.innerHTML = '';
  grid.appendChild(uploadSlot);

  existingImages.forEach((src, i) => {
    const div = document.createElement('div');
    div.className = 'aspect-square relative group rounded-xl overflow-hidden bg-surface-container-low';
    div.innerHTML = `
      <img src="${src}" class="w-full h-full object-cover"/>
      <button type="button"
        class="absolute top-1 right-1 w-6 h-6 bg-black/60 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
        onclick="removeExistingImage(${i})">
        <span class="material-symbols-outlined" style="font-size:14px">close</span>
      </button>`;
    grid.appendChild(div);
  });

  pendingFiles.forEach(({ url }, i) => {
    const div = document.createElement('div');
    div.className = 'aspect-square relative group rounded-xl overflow-hidden bg-surface-container-low ring-2 ring-primary/30';
    div.innerHTML = `
      <img src="${url}" class="w-full h-full object-cover"/>
      <div class="absolute bottom-0 left-0 right-0 bg-black/40 text-white text-[9px] font-bold text-center py-0.5">NEW</div>
      <button type="button"
        class="absolute top-1 right-1 w-6 h-6 bg-black/60 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
        onclick="removePendingFile(${i})">
        <span class="material-symbols-outlined" style="font-size:14px">close</span>
      </button>`;
    grid.appendChild(div);
  });

  document.getElementById('existing-images-input').value = JSON.stringify(existingImages);
}

function removeExistingImage(index) {
  existingImages.splice(index, 1);
  renderImages();
}

function removePendingFile(index) {
  URL.revokeObjectURL(pendingFiles[index].url);
  pendingFiles.splice(index, 1);
  syncFileInput();
  renderImages();
}

function syncFileInput() {
  const dt = new DataTransfer();
  pendingFiles.forEach(pf => dt.items.add(pf.file));
  document.getElementById('image-input').files = dt.files;
}

document.getElementById('image-input').addEventListener('change', function(e) {
  Array.from(e.target.files).forEach(file => {
    pendingFiles.push({ file, url: URL.createObjectURL(file) });
  });
  syncFileInput();
  renderImages();
});

// Drag-and-drop on upload slot
const uploadSlot = document.getElementById('upload-slot');
uploadSlot.addEventListener('dragover', e => { e.preventDefault(); uploadSlot.classList.add('border-primary'); });
uploadSlot.addEventListener('dragleave', () => { uploadSlot.classList.remove('border-primary'); });
uploadSlot.addEventListener('drop', e => {
  e.preventDefault();
  uploadSlot.classList.remove('border-primary');
  Array.from(e.dataTransfer.files).filter(f => f.type.startsWith('image/')).forEach(file => {
    pendingFiles.push({ file, url: URL.createObjectURL(file) });
  });
  syncFileInput();
  renderImages();
});

// ─── Variants ────────────────────────────────────────────────────────────────
let variants = [];
try {
  const raw = document.getElementById('variants-hidden').value;
  variants = JSON.parse(raw || '[]');
  if (!Array.isArray(variants)) variants = [];
} catch(e) { variants = []; }

function renderVariants() {
  const list = document.getElementById('variants-list');
  const empty = document.getElementById('variants-empty');
  list.innerHTML = '';

  if (variants.length === 0) {
    empty.classList.remove('hidden');
    return;
  }
  empty.classList.add('hidden');

  variants.forEach((v, i) => {
    const div = document.createElement('div');
    div.className = 'p-4 rounded-xl bg-surface-container-low';
    div.innerHTML = `
      <div class="flex items-center justify-between mb-3">
        <input type="text" value="${escHtml(v.name)}"
          class="bg-transparent border-none p-0 font-bold text-sm text-on-surface focus:ring-0 focus:outline-none focus:border-b focus:border-primary"
          placeholder="Option name (e.g. Size)"
          onchange="updateVariantName(${i}, this.value)"/>
        <button type="button" onclick="removeVariant(${i})"
          class="p-1 text-slate-400 hover:text-error transition-colors">
          <span class="material-symbols-outlined text-sm">delete</span>
        </button>
      </div>
      <div class="flex flex-wrap gap-2 items-center" id="values-${i}">
        ${v.values.map((val, j) => `
          <span class="flex items-center gap-1 px-2.5 py-1 bg-white rounded-lg text-xs font-semibold text-on-surface border border-outline-variant/20 group">
            ${escHtml(val)}
            <button type="button" onclick="removeVariantValue(${i},${j})"
              class="text-slate-300 hover:text-error transition-colors ml-0.5">
              <span class="material-symbols-outlined" style="font-size:12px">close</span>
            </button>
          </span>`).join('')}
        <input type="text"
          class="border border-dashed border-outline-variant/40 rounded-lg px-2.5 py-1 text-xs text-on-surface focus:ring-1 focus:ring-primary focus:outline-none bg-transparent min-w-[120px]"
          placeholder="Add value, press Enter"
          onkeydown="handleValueInput(event, ${i})"
          onblur="handleValueBlur(event, ${i})"/>
      </div>`;
    list.appendChild(div);
  });

  updateVariantsHidden();
}

function updateVariantsHidden() {
  document.getElementById('variants-hidden').value = JSON.stringify(variants);
}

function updateVariantName(i, name) {
  variants[i].name = name;
  updateVariantsHidden();
}

function removeVariant(i) {
  variants.splice(i, 1);
  renderVariants();
}

function addVariantValue(i, rawValue) {
  const value = rawValue.trim();
  if (value && !variants[i].values.includes(value)) {
    variants[i].values.push(value);
    renderVariants();
    // Refocus the input for this variant
    const input = document.querySelector(`#values-${i} input`);
    if (input) input.focus();
  }
}

function removeVariantValue(i, j) {
  variants[i].values.splice(j, 1);
  renderVariants();
}

function handleValueInput(e, i) {
  if (e.key === 'Enter' || e.key === ',') {
    e.preventDefault();
    const val = e.target.value.replace(/,/g, '').trim();
    if (val) { e.target.value = ''; addVariantValue(i, val); }
  }
}

function handleValueBlur(e, i) {
  const val = e.target.value.trim();
  if (val) { e.target.value = ''; addVariantValue(i, val); }
}

document.getElementById('add-variant-btn').addEventListener('click', () => {
  variants.push({ name: '', values: [] });
  renderVariants();
  // Focus the new option name input
  const inputs = document.querySelectorAll('#variants-list input[type="text"]');
  if (inputs.length > 0) inputs[inputs.length - 2]?.focus();
});

function escHtml(str) {
  return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ─── Init ─────────────────────────────────────────────────────────────────────
renderImages();
renderVariants();

// Mark SEO title / url handle as edited if they had existing values (don't overwrite on title change)
if (seoTitleInput.value) seoTitleInput.dataset.edited = '1';
if (urlHandleInput.value) urlHandleInput.dataset.edited = '1';
</script>

<style>
#description-editor:empty:before {
  content: attr(data-placeholder);
  color: #94a3b8;
  pointer-events: none;
}
</style>
</body>
</html>
