// ============================================================
// frontend/assets/js/image-picker.js
// Reusable image picker modal — drop-in for any admin form
// Usage:
//   ImagePicker.open((url) => { /* use the selected url */ });
// ============================================================

const ImagePicker = (() => {

  let _onSelect   = null;
  let _modal      = null;
  let _allImages  = [];

  // ---- Inject modal HTML once ----
  function _inject() {
    if (document.getElementById('imgPickerModal')) return;

    document.body.insertAdjacentHTML('beforeend', `
    <div class="modal fade" id="imgPickerModal" tabindex="-1" style="z-index:1060">
      <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <div>
              <h5 class="modal-title mb-0"><i class="bi bi-images me-2 text-primary-ha"></i>Image Library</h5>
              <p class="text-muted small mb-0" id="ip-count">Loading images...</p>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" style="background:var(--bg)">

            <!-- Upload strip -->
            <div class="ip-upload-strip mb-3 p-3 rounded" style="background:var(--white);border:1.5px dashed var(--border)">
              <div class="d-flex align-items-center gap-3 flex-wrap">
                <label class="btn-ha-primary mb-0" style="cursor:pointer;padding:.5rem 1.1rem;font-size:.85rem">
                  <i class="bi bi-upload me-2"></i>Upload New Image
                  <input type="file" id="ip-file-input" accept="image/*" multiple style="display:none" onchange="ImagePicker._handleUpload(this.files)" />
                </label>
                <span class="text-muted small">or pick from library below &bull; JPG, PNG, WebP, GIF &bull; Max 5MB</span>
                <div id="ip-upload-status" class="ms-auto"></div>
              </div>
              <div id="ip-upload-queue" class="mt-2"></div>
            </div>

            <!-- Search -->
            <div class="mb-3">
              <input type="text" id="ip-search" class="form-control" placeholder="Search images by filename..."
                     style="border-radius:50px;border:1.5px solid var(--border);max-width:320px"
                     oninput="ImagePicker._filter(this.value)" />
            </div>

            <!-- Grid -->
            <div class="row g-2" id="ip-grid">
              <div class="col-12 text-center py-5 text-muted">
                <div class="spinner-border spinner-border-sm me-2"></div>Loading library...
              </div>
            </div>

            <div id="ip-empty" class="empty-state d-none">
              <i class="bi bi-images"></i>
              <p>No images uploaded yet. Use the upload button above.</p>
            </div>

          </div>
          <div class="modal-footer justify-content-between align-items-center">
            <div id="ip-selected-preview" style="display:none">
              <div class="d-flex align-items-center gap-2">
                <img id="ip-sel-thumb" src="" style="width:40px;height:40px;border-radius:6px;object-fit:cover" />
                <span class="small text-muted" id="ip-sel-name"></span>
              </div>
            </div>
            <div class="d-flex gap-2 ms-auto">
              <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
              <button class="btn-ha-primary" id="ip-confirm-btn" onclick="ImagePicker._confirm()" disabled
                      style="padding:.5rem 1.4rem">
                <i class="bi bi-check-lg me-1"></i>Use This Image
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>`);

    _modal = new bootstrap.Modal(document.getElementById('imgPickerModal'));
  }

  // ---- Load images from API ----
  async function _load() {
    const grid  = document.getElementById('ip-grid');
    const empty = document.getElementById('ip-empty');
    const count = document.getElementById('ip-count');

    grid.innerHTML = `<div class="col-12 text-center py-5 text-muted">
      <div class="spinner-border spinner-border-sm me-2"></div>Loading library...</div>`;
    empty.classList.add('d-none');

    const res = await Uploads.list();
    if (!res.success || !res.data.length) {
      grid.innerHTML = '';
      empty.classList.remove('d-none');
      count.textContent = '0 images in library';
      _allImages = [];
      return;
    }
    _allImages = res.data;
    count.textContent = `${_allImages.length} image(s) in library`;
    _renderGrid(_allImages);
  }

  // ---- Render image grid ----
  let _selectedUrl = null;

  function _renderGrid(images) {
    const grid  = document.getElementById('ip-grid');
    const empty = document.getElementById('ip-empty');

    if (!images.length) {
      grid.innerHTML = '';
      empty.classList.remove('d-none');
      return;
    }
    empty.classList.add('d-none');

    grid.innerHTML = images.map(img => `
      <div class="col-md-2 col-4">
        <div class="ip-img-card" id="ipc-${_safe(img.filename)}"
             onclick="ImagePicker._select('${img.url}', '${img.filename}', this)"
             style="border:2px solid var(--border);border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s">
          <img src="${img.url}" alt="${img.filename}" loading="lazy"
               style="width:100%;aspect-ratio:1;object-fit:cover;display:block"
               onerror="this.style.background='var(--primary-light)'" />
          <div style="padding:.35rem .5rem;font-size:.68rem;color:var(--muted);background:var(--bg);
                      white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${img.filename}">
            ${img.filename.length > 18 ? img.filename.slice(0,15) + '…' : img.filename}
            <br/><span>${img.size_label}</span>
          </div>
        </div>
      </div>`).join('');
  }

  function _safe(str) {
    return str.replace(/[^a-zA-Z0-9]/g, '_');
  }

  // ---- Select an image ----
  function _select(url, filename, el) {
    // Deselect all
    document.querySelectorAll('.ip-img-card').forEach(c => {
      c.style.borderColor = 'var(--border)';
      c.style.boxShadow   = 'none';
    });
    // Highlight selected
    el.style.borderColor = 'var(--primary)';
    el.style.boxShadow   = '0 0 0 3px rgba(26,127,94,.2)';

    _selectedUrl = url;

    // Update footer preview
    const preview = document.getElementById('ip-selected-preview');
    preview.style.display = 'block';
    document.getElementById('ip-sel-thumb').src   = url;
    document.getElementById('ip-sel-name').textContent = filename;

    // Enable confirm button
    document.getElementById('ip-confirm-btn').disabled = false;
  }

  // ---- Confirm selection ----
  function _confirm() {
    if (!_selectedUrl) return;
    _modal.hide();
    if (typeof _onSelect === 'function') _onSelect(_selectedUrl);
    _selectedUrl = null;
  }

  // ---- Filter ----
  function _filter(q) {
    const filtered = q
      ? _allImages.filter(i => i.filename.toLowerCase().includes(q.toLowerCase()))
      : _allImages;
    _renderGrid(filtered);
  }

  // ---- Handle new upload from inside picker ----
  async function _handleUpload(files) {
    if (!files.length) return;
    const queue = document.getElementById('ip-upload-queue');
    const status= document.getElementById('ip-upload-status');

    const fileArr = Array.from(files);
    status.innerHTML = `<span class="text-muted small"><div class="spinner-border spinner-border-sm me-1"></div>Uploading ${fileArr.length} file(s)...</span>`;

    let successCount = 0;
    for (const file of fileArr) {
      // Show mini preview
      const prev = URL.createObjectURL(file);
      const itemId = 'ip-qi-' + Date.now();
      queue.insertAdjacentHTML('beforeend', `
        <div id="${itemId}" class="d-flex align-items-center gap-2 mb-1 p-2 rounded" style="background:var(--primary-light);font-size:.8rem">
          <img src="${prev}" style="width:32px;height:32px;border-radius:4px;object-fit:cover" />
          <span class="text-truncate flex-grow-1">${file.name}</span>
          <span id="${itemId}-st" class="text-muted">Uploading...</span>
        </div>`);

      const res = await Uploads.upload(file);
      const stEl = document.getElementById(itemId + '-st');
      if (res.success) {
        successCount++;
        stEl.textContent  = '✓ Done';
        stEl.style.color  = 'var(--success)';
      } else {
        stEl.textContent  = '✗ ' + (res.message || 'Failed');
        stEl.style.color  = 'var(--danger)';
      }
    }

    status.innerHTML = `<span class="small text-success fw-600">${successCount} of ${fileArr.length} uploaded</span>`;

    // Reload gallery
    setTimeout(() => {
      queue.innerHTML = '';
      status.innerHTML = '';
      _load();
    }, 1200);
  }

  // ---- Public API ----
  return {
    open(onSelect) {
      _onSelect    = onSelect;
      _selectedUrl = null;
      _inject();

      // Reset state
      document.getElementById('ip-confirm-btn').disabled = true;
      document.getElementById('ip-selected-preview').style.display = 'none';
      const searchEl = document.getElementById('ip-search');
      if (searchEl) searchEl.value = '';

      _modal.show();
      _load();
    },
    _select,
    _confirm,
    _filter,
    _handleUpload,
  };
})();
