/**
 * Jalpi Page Builder — Theme Builder Admin UI
 *
 * Communicates with the REST API at jalpiTB.apiUrl.
 * All state lives in a simple plain object; functions re-render DOM as needed.
 */
/* global jalpiTB */
(function () {
  'use strict';

  const api       = jalpiTB.apiUrl;
  const nonce     = jalpiTB.nonce;
  const editorUrl = jalpiTB.editorUrl;
  const locations = jalpiTB.locations; // { header:{label,description,...}, ... }
  const i18n      = jalpiTB.i18n || {}; // Localized strings

  // ── State ─────────────────────────────────────────────────────────────────

  const state = {
    activeLocation: document.querySelector('.jalpi-tb-nav__item.is-active')?.dataset?.location || 'header',
    templates: {},          // { location: [template,...] }
    conditionOptions: null, // loaded lazily
    editingTpl: null,       // template being edited in condition modal
    workingConditions: [],  // live copy while modal is open
  };

  // ── Fetch helpers ─────────────────────────────────────────────────────────

  function apiFetch(path, opts = {}) {
    return fetch(api + path, {
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce':   nonce,
        ...( opts.headers || {} ),
      },
      ...opts,
    }).then(r => {
      if (!r.ok) return r.json().then(e => { throw new Error(e.message || 'API error'); });
      return r.json();
    });
  }

  // ── Bootstrap ─────────────────────────────────────────────────────────────

  document.addEventListener('DOMContentLoaded', () => {
    bindNav();
    bindAddNew();
    bindCreateModal();
    bindConditionModal();
    loadAllTemplates();
  });

  // ── Navigation ────────────────────────────────────────────────────────────

  function bindNav() {
    document.querySelectorAll('.jalpi-tb-nav__item').forEach(a => {
      a.addEventListener('click', e => {
        e.preventDefault();
        const loc = a.dataset.location;
        if (loc === state.activeLocation) return;
        state.activeLocation = loc;
        document.querySelectorAll('.jalpi-tb-nav__item').forEach(x => x.classList.toggle('is-active', x.dataset.location === loc));
        document.getElementById('jalpi-tb-section-title').textContent = locations[loc].label;
        document.getElementById('jalpi-tb-section-desc').textContent  = locations[loc].description;
        renderTemplateList();
      });
    });
  }

  // ── Load all templates ────────────────────────────────────────────────────

  function loadAllTemplates() {
    apiFetch('/theme-templates').then(list => {
      // Group by location
      state.templates = {};
      list.forEach(t => {
        if (!state.templates[t.location]) state.templates[t.location] = [];
        state.templates[t.location].push(t);
      });
      // Sort each group by priority
      Object.keys(state.templates).forEach(loc => {
        state.templates[loc].sort((a, b) => a.priority - b.priority);
      });
      updateCounts();
      renderTemplateList();
    }).catch(err => {
      document.getElementById('jalpi-tb-templates-list').innerHTML =
        `<div class="jalpi-tb-empty"><p style="color:#dc2626">${escHtml(err.message)}</p></div>`;
    });
  }

  function updateCounts() {
    document.querySelectorAll('[data-loc-count]').forEach(el => {
      const loc   = el.dataset.locCount;
      const count = (state.templates[loc] || []).length;
      el.textContent = count;
    });
  }

  // ── Render template list ──────────────────────────────────────────────────

  function renderTemplateList() {
    const loc       = state.activeLocation;
    const container = document.getElementById('jalpi-tb-templates-list');
    const list      = state.templates[loc] || [];

    if (list.length === 0) {
      container.innerHTML = renderEmpty(loc);
      return;
    }

    container.innerHTML = list.map(tpl => renderCard(tpl)).join('');
    bindCardActions(container);
  }

  function renderEmpty(loc) {
    return `<div class="jalpi-tb-empty">
      <div class="jalpi-tb-empty__icon">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/></svg>
      </div>
      <h3>No ${escHtml(locations[loc].label)} templates yet</h3>
      <p>${escHtml(locations[loc].description)}</p>
      <button class="jalpi-tb-btn jalpi-tb-btn--primary" id="jalpi-tb-empty-add">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        ${i18n.createFirstTemplate || 'Create First Template'}
      </button>
    </div>`;
  }

  function renderCard(tpl) {
    const isActive    = tpl.status === 'active';
    const condCount   = tpl.conditions ? tpl.conditions.length : 0;
    const condSummary = condCount === 0
      ? `<span style="color:#dc2626">${i18n.condNoDisplay || 'No conditions — template won\'t display'}</span>`
      : condCount === 1
        ? `<strong>1</strong> ${i18n.condition || 'condition'}`
        : `<strong>${condCount}</strong> ${i18n.conditions_plural || 'conditions'}`;

    return `<div class="jalpi-tb-card ${isActive ? 'is-active' : 'is-inactive'}" data-id="${tpl.id}">

      <div class="jalpi-tb-card__main">
        <h3 class="jalpi-tb-card__title">${escHtml(tpl.title)}</h3>
        <div class="jalpi-tb-card__meta">
          <span class="jalpi-tb-badge ${isActive ? 'jalpi-tb-badge--active' : 'jalpi-tb-badge--inactive'}">
            ${isActive ? i18n.active : i18n.inactive}
          </span>
          <span class="jalpi-tb-priority-badge">${i18n.priority ? i18n.priority.replace('%d', tpl.priority) : 'Priority ' + tpl.priority}</span>
          <span class="jalpi-tb-conditions-summary">${condSummary}</span>
        </div>
      </div>

      <div class="jalpi-tb-card__actions">

        <!-- Status toggle -->
        <label class="jalpi-tb-toggle" title="${isActive ? i18n.deactivate : i18n.activate}">
          <input type="checkbox" ${isActive ? 'checked' : ''} data-action="toggle-status" data-id="${tpl.id}">
          <span class="jalpi-tb-toggle__track"></span>
        </label>

        <!-- Priority -->
        <div class="jalpi-tb-priority-wrap" title="Priority (lower = higher priority)">
          <input type="number" min="1" max="999" value="${tpl.priority}" data-action="set-priority" data-id="${tpl.id}" style="width:54px">
        </div>

        <!-- Conditions -->
        <button class="jalpi-tb-btn jalpi-tb-btn--ghost jalpi-tb-btn--sm" data-action="edit-conditions" data-id="${tpl.id}" title="${i18n.conditions ? 'Edit ' + i18n.conditions : 'Edit display conditions'}">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
          ${i18n.conditions || 'Conditions'}
        </button>

        <!-- Edit in Jalpi Page Builder -->
        <a class="jalpi-tb-btn jalpi-tb-btn--primary jalpi-tb-btn--sm" href="${escHtml(tpl.editUrl)}" title="Open in Jalpi Page Builder editor">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          ${i18n.edit || 'Edit'}
        </a>

        <!-- Preview -->
        <a class="jalpi-tb-btn jalpi-tb-btn--ghost jalpi-tb-btn--icon" href="${escHtml(tpl.previewUrl)}" target="_blank" title="Preview template">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
        </a>

        <!-- Delete -->
        <button class="jalpi-tb-btn jalpi-tb-btn--danger jalpi-tb-btn--icon" data-action="delete" data-id="${tpl.id}" data-title="${escHtml(tpl.title)}" title="Delete template">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/></svg>
        </button>

      </div>
    </div>`;
  }

  function bindCardActions(container) {
    // Empty-state add button
    const emptyAdd = container.querySelector('#jalpi-tb-empty-add');
    if (emptyAdd) emptyAdd.addEventListener('click', openCreateModal);

    // Status toggle
    container.querySelectorAll('[data-action="toggle-status"]').forEach(el => {
      el.addEventListener('change', () => {
        const id  = parseInt(el.dataset.id, 10);
        const tpl = findTemplate(id);
        if (!tpl) return;
        const newStatus = el.checked ? 'active' : 'inactive';
        apiFetch('/theme-templates/' + id, {
          method: 'POST',
          body: JSON.stringify({ status: newStatus }),
        }).then(updated => {
          updateTemplate(updated);
          renderTemplateList();
        }).catch(showError);
      });
    });

    // Priority change (on blur)
    container.querySelectorAll('[data-action="set-priority"]').forEach(el => {
      el.addEventListener('change', () => {
        const id       = parseInt(el.dataset.id, 10);
        const priority = Math.max(1, parseInt(el.value, 10) || 10);
        el.value = priority;
        apiFetch('/theme-templates/' + id, {
          method: 'POST',
          body: JSON.stringify({ priority }),
        }).then(updated => {
          updateTemplate(updated);
          state.templates[state.activeLocation].sort((a, b) => a.priority - b.priority);
          renderTemplateList();
        }).catch(showError);
      });
    });

    // Edit conditions
    container.querySelectorAll('[data-action="edit-conditions"]').forEach(el => {
      el.addEventListener('click', () => {
        const id  = parseInt(el.dataset.id, 10);
        const tpl = findTemplate(id);
        if (tpl) openConditionModal(tpl);
      });
    });

    // Delete
    container.querySelectorAll('[data-action="delete"]').forEach(el => {
      el.addEventListener('click', () => {
        const id    = parseInt(el.dataset.id, 10);
        const title = el.dataset.title;
        const msg = i18n.deleteConfirm
          ? i18n.deleteConfirm.replace('%s', title)
          : `Delete "${title}"? This cannot be undone.`;
        if (!confirm(msg)) return;
        apiFetch('/theme-templates/' + id, { method: 'DELETE' }).then(() => {
          removeTemplate(id);
          updateCounts();
          renderTemplateList();
        }).catch(showError);
      });
    });
  }

  // ── Create Modal ──────────────────────────────────────────────────────────

  function bindAddNew() {
    document.getElementById('jalpi-tb-add-new').addEventListener('click', openCreateModal);
  }

  function openCreateModal() {
    const overlay = document.getElementById('jalpi-tb-create-overlay');
    const input   = document.getElementById('jalpi-create-title');
    const loc     = state.activeLocation;
    input.value   = locations[loc].label + ' Template';
    overlay.classList.add('is-visible');
    overlay.removeAttribute('aria-hidden');
    requestAnimationFrame(() => input.focus());
  }

  function closeCreateModal() {
    const overlay = document.getElementById('jalpi-tb-create-overlay');
    overlay.classList.remove('is-visible');
    overlay.setAttribute('aria-hidden', 'true');
  }

  function bindCreateModal() {
    document.getElementById('jalpi-create-close').addEventListener('click',   closeCreateModal);
    document.getElementById('jalpi-create-cancel').addEventListener('click',  closeCreateModal);
    document.getElementById('jalpi-create-confirm').addEventListener('click', () => {
      const title = document.getElementById('jalpi-create-title').value.trim();
      if (!title) return;
      const btn = document.getElementById('jalpi-create-confirm');
      btn.textContent = i18n.creating || 'Creating…';
      btn.disabled    = true;
      apiFetch('/theme-templates', {
        method: 'POST',
        body: JSON.stringify({ location: state.activeLocation, title }),
      }).then(tpl => {
        closeCreateModal();
        btn.textContent = i18n.createEdit || 'Create & Edit';
        btn.disabled    = false;
        addTemplate(tpl);
        updateCounts();
        // Redirect straight to the editor
        window.location.href = tpl.editUrl;
      }).catch(err => {
        btn.textContent = i18n.createEdit || 'Create & Edit';
        btn.disabled    = false;
        showError(err);
      });
    });

    // Close on overlay click
    document.getElementById('jalpi-tb-create-overlay').addEventListener('click', e => {
      if (e.target === e.currentTarget) closeCreateModal();
    });
  }

  // ── Condition Modal ───────────────────────────────────────────────────────

  function bindConditionModal() {
    document.getElementById('jalpi-tb-modal-close').addEventListener('click',   closeConditionModal);
    document.getElementById('jalpi-conditions-cancel').addEventListener('click', closeConditionModal);
    document.getElementById('jalpi-condition-add').addEventListener('click',     addConditionRow);
    document.getElementById('jalpi-conditions-save').addEventListener('click',   saveConditions);

    document.getElementById('jalpi-tb-modal-overlay').addEventListener('click', e => {
      if (e.target === e.currentTarget) closeConditionModal();
    });
  }

  function openConditionModal(tpl) {
    state.editingTpl        = tpl;
    state.workingConditions = JSON.parse(JSON.stringify(tpl.conditions || []));

    document.getElementById('jalpi-tb-modal-tpl-name').textContent =
      tpl.title + ' — ' + (locations[tpl.location] ? locations[tpl.location].label : tpl.location);

    renderConditionRows();

    const overlay = document.getElementById('jalpi-tb-modal-overlay');
    overlay.classList.add('is-visible');
    overlay.removeAttribute('aria-hidden');

    // Lazy-load condition options
    if (!state.conditionOptions) {
      fetch(api + '/theme-conditions/options', { headers: { 'X-WP-Nonce': nonce } })
        .then(r => r.json())
        .then(opts => {
          state.conditionOptions = opts;
          renderConditionRows(); // re-render with real options
        });
    }
  }

  function closeConditionModal() {
    const overlay = document.getElementById('jalpi-tb-modal-overlay');
    overlay.classList.remove('is-visible');
    overlay.setAttribute('aria-hidden', 'true');
    state.editingTpl = null;
  }

  function renderConditionRows() {
    const list = document.getElementById('jalpi-conditions-list');
    if (state.workingConditions.length === 0) {
      const msg = i18n.noConditions || 'No conditions added yet. Click "+ Add Condition" to start.';
      list.innerHTML = '<p style="font-size:12px;color:#6b7280;margin:0">' + escHtml(msg) + '</p>';
      return;
    }
    list.innerHTML = state.workingConditions.map((c, i) => renderConditionRow(c, i)).join('');
    bindConditionRowEvents(list);
  }

  function renderConditionRow(c, index) {
    const opts    = state.conditionOptions;
    const typeVal = c.type     || 'entire_site';
    const opVal   = c.operator || 'is';

    const typeOptions = `
      <option value="entire_site"  ${typeVal === 'entire_site'  ? 'selected' : ''}>${i18n.entireSite || 'Entire Site'}</option>
      <option value="singular"     ${typeVal === 'singular'     ? 'selected' : ''}>${i18n.allSingular || 'All Singular'}</option>
      <option value="all_archives" ${typeVal === 'all_archives' ? 'selected' : ''}>${i18n.allArchives || 'All Archives'}</option>
      <optgroup label="Post Type">
        <option value="post_type"  ${typeVal === 'post_type'    ? 'selected' : ''}>${i18n.postType || 'Post Type…'}</option>
      </optgroup>
      <optgroup label="Taxonomy">
        <option value="category"   ${typeVal === 'category'     ? 'selected' : ''}>${i18n.category || 'Category…'}</option>
        <option value="tag"        ${typeVal === 'tag'          ? 'selected' : ''}>${i18n.tag || 'Tag…'}</option>
      </optgroup>
      <optgroup label="Specific">
        <option value="post_id"    ${typeVal === 'post_id'      ? 'selected' : ''}>${i18n.postId || 'Post ID…'}</option>
        <option value="author"     ${typeVal === 'author'       ? 'selected' : ''}>${i18n.author || 'Author…'}</option>
      </optgroup>
      <option value="search"       ${typeVal === 'search'       ? 'selected' : ''}>${i18n.searchResults || 'Search Results'}</option>
      <option value="404"          ${typeVal === '404'          ? 'selected' : ''}>${i18n.notFoundPage || '404 Page'}</option>`;

    const opOptions = `
      <option value="is"     ${opVal === 'is'     ? 'selected' : ''}>${i18n.is || 'Is'}</option>
      <option value="is_not" ${opVal === 'is_not' ? 'selected' : ''}>${i18n.isNot || 'Is Not'}</option>`;

    const valueField = buildValueField(typeVal, c.value || '', c.label || '', opts);

    return `<div class="jalpi-condition-row" data-index="${index}">
      <select class="jalpi-condition-row__type" data-role="type">${typeOptions}</select>
      <select class="jalpi-condition-row__operator" data-role="operator">${opOptions}</select>
      <div class="jalpi-condition-row__value">${valueField}</div>
      <button class="jalpi-condition-row__remove" data-role="remove" aria-label="Remove">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>`;
  }

  function buildValueField(type, value, label, opts) {
    if (['entire_site','singular','all_archives','search','404'].includes(type)) {
      return '<span style="font-size:11px;color:#6b7280;padding:0 4px">— applies everywhere —</span>';
    }
    if (type === 'post_type' && opts) {
      const options = opts.post_types.map(o =>
        `<option value="${escHtml(o.value)}" ${o.value === value ? 'selected' : ''}>${escHtml(o.label)}</option>`
      ).join('');
      return `<select data-role="value">${options}</select>`;
    }
    if (type === 'category' && opts) {
      const options = opts.categories.map(o =>
        `<option value="${escHtml(o.value)}" ${o.value === value ? 'selected' : ''}>${escHtml(o.label)}</option>`
      ).join('');
      const noMsg = i18n.noCategoriesFound || 'No categories found';
      return `<select data-role="value">${options || '<option value="">' + escHtml(noMsg) + '</option>'}</select>`;
    }
    if (type === 'tag' && opts) {
      const options = opts.tags.map(o =>
        `<option value="${escHtml(o.value)}" ${o.value === value ? 'selected' : ''}>${escHtml(o.label)}</option>`
      ).join('');
      const noMsg = i18n.noTagsFound || 'No tags found';
      return `<select data-role="value">${options || '<option value="">' + escHtml(noMsg) + '</option>'}</select>`;
    }
    // Default: text input for post_id, author
    const placeholder = type === 'post_id'
      ? (i18n.postIdPlaceholder || 'Post ID')
      : type === 'author'
        ? (i18n.authorPlaceholder || 'Author login or ID')
        : (i18n.valuePlaceholder || 'Value');
    return `<input type="text" data-role="value" value="${escHtml(value)}" placeholder="${placeholder}">`;
  }

  function bindConditionRowEvents(list) {
    list.querySelectorAll('.jalpi-condition-row').forEach(row => {
      const index = parseInt(row.dataset.index, 10);

      row.querySelector('[data-role="type"]').addEventListener('change', e => {
        state.workingConditions[index].type  = e.target.value;
        state.workingConditions[index].value = '';
        state.workingConditions[index].label = '';
        renderConditionRows();
      });

      row.querySelector('[data-role="operator"]').addEventListener('change', e => {
        state.workingConditions[index].operator = e.target.value;
      });

      const valueEl = row.querySelector('[data-role="value"]');
      if (valueEl) {
        valueEl.addEventListener('change', e => {
          state.workingConditions[index].value = e.target.value;
          state.workingConditions[index].label = e.target.options
            ? e.target.options[e.target.selectedIndex]?.text || ''
            : e.target.value;
        });
      }

      row.querySelector('[data-role="remove"]').addEventListener('click', () => {
        state.workingConditions.splice(index, 1);
        renderConditionRows();
      });
    });
  }

  function addConditionRow() {
    state.workingConditions.push({ type: 'entire_site', operator: 'is', value: '', label: '' });
    renderConditionRows();
  }

  function saveConditions() {
    const tpl = state.editingTpl;
    if (!tpl) return;

    const saveBtn   = document.getElementById('jalpi-conditions-save');
    saveBtn.textContent = i18n.saving || 'Saving…';
    saveBtn.disabled    = true;

    apiFetch('/theme-templates/' + tpl.id, {
      method: 'POST',
      body:   JSON.stringify({ conditions: state.workingConditions }),
    }).then(updated => {
      saveBtn.textContent = i18n.saveConditions || 'Save Conditions';
      saveBtn.disabled    = false;
      updateTemplate(updated);
      renderTemplateList();
      closeConditionModal();
    }).catch(err => {
      saveBtn.textContent = i18n.saveConditions || 'Save Conditions';
      saveBtn.disabled    = false;
      showError(err);
    });
  }

  // ── Template state helpers ────────────────────────────────────────────────

  function findTemplate(id) {
    for (const loc of Object.keys(state.templates)) {
      const t = state.templates[loc].find(x => x.id === id);
      if (t) return t;
    }
    return null;
  }

  function updateTemplate(updated) {
    const loc  = updated.location;
    if (!state.templates[loc]) state.templates[loc] = [];
    const idx = state.templates[loc].findIndex(x => x.id === updated.id);
    if (idx >= 0) state.templates[loc][idx] = updated;
    else           state.templates[loc].push(updated);
  }

  function addTemplate(tpl) {
    if (!state.templates[tpl.location]) state.templates[tpl.location] = [];
    state.templates[tpl.location].push(tpl);
  }

  function removeTemplate(id) {
    for (const loc of Object.keys(state.templates)) {
      state.templates[loc] = state.templates[loc].filter(x => x.id !== id);
    }
  }

  // ── Utilities ─────────────────────────────────────────────────────────────

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

  function showError(err) {
    const prefix = i18n.error || 'Error: ';
    alert(prefix + (err.message || String(err)));
  }

}());
