import { getJson } from './api.js';
import { esc } from './sanitize.js';

export function createWebdavController(deps) {
  var currentPath = '/';
  var selectedPath = '';
  var selectedName = '';

  function browse(path) {
    currentPath = path || '/';
    var list = document.getElementById('lh-ai-webdav-list');
    var pathLabel = document.getElementById('lh-ai-webdav-path-label');
    if (list) list.innerHTML = '<div style="padding:12px;text-align:center;color:var(--g400);font-size:13px;"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
    if (pathLabel) pathLabel.textContent = currentPath;

    getJson('/api/admin/learning/webdav-browse?path=' + encodeURIComponent(currentPath))
      .then(function(data) {
        if (!data.success) {
          if (list) list.innerHTML = '<div style="padding:12px;color:var(--red);font-size:13px;">' + esc(data.error) + '</div>';
          return;
        }
        if (pathLabel) pathLabel.textContent = data.path;
        renderList(data);
      })
      .catch(function(err) {
        if (list) list.innerHTML = '<div style="padding:12px;color:var(--red);font-size:13px;">' + esc(err.message) + '</div>';
      });
  }

  function renderList(data) {
    var list = document.getElementById('lh-ai-webdav-list');
    if (!list) return;
    list.innerHTML = renderWebdavListHtml(data);
  }

  function openItem(el) {
    if (!el) return;
    if (el.dataset.isdir === '1') browse(el.dataset.path);
    else selectFile(el.dataset.path, el.dataset.name);
  }

  function selectFile(path, name) {
    selectedPath = path;
    selectedName = name;
    var browser = document.getElementById('lh-ai-webdav-browser');
    var selDiv = document.getElementById('lh-ai-webdav-selected');
    var selName = document.getElementById('lh-ai-webdav-selected-name');
    if (browser) browser.style.display = 'none';
    if (selDiv) selDiv.style.display = 'flex';
    if (selName) selName.textContent = name;
  }

  function deselectFile() {
    selectedPath = '';
    selectedName = '';
    var browser = document.getElementById('lh-ai-webdav-browser');
    var selDiv = document.getElementById('lh-ai-webdav-selected');
    if (selDiv) selDiv.style.display = 'none';
    if (browser) browser.style.display = '';
  }

  return {
    browse: browse,
    deselectFile: deselectFile,
    getCurrentPath: function() { return currentPath; },
    getSelectedName: function() { return selectedName; },
    getSelectedPath: function() { return selectedPath; },
    openItem: openItem,
    selectFile: selectFile,
    setCurrentPath: function(path) { currentPath = path || '/'; }
  };
}

export function renderWebdavListHtml(data) {
  var html = '';

  if (data.path !== '/' && data.path !== data.parentPath) {
    html += '<div class="lh-webdav-item lh-webdav-dir" data-path="' + esc(data.parentPath) + '" data-isdir="1">' +
      '<i class="fas fa-arrow-left" style="color:var(--g400);"></i> <span>..</span></div>';
  }

  if (data.items.length === 0 && html === '') {
    return '<div style="padding:12px;text-align:center;color:var(--g400);font-size:13px;">Empty folder</div>';
  }

  data.items.forEach(function(item) {
    var icon = item.isDir ? 'fa-folder' : getFileIcon(item.contentType, item.name);
    var iconColor = item.isDir ? 'var(--amber)' : 'var(--blue)';
    var sizeStr = (!item.isDir && item.size)
      ? ' <span style="color:var(--g400);font-size:11px;">(' + formatBytes(item.size) + ')</span>'
      : '';
    html += '<div class="lh-webdav-item' + (item.isDir ? ' lh-webdav-dir' : ' lh-webdav-file') + '"' +
      ' data-path="' + esc(item.path) + '" data-name="' + esc(item.name) + '" data-isdir="' + (item.isDir ? '1' : '0') + '">' +
      '<i class="fas ' + icon + '" style="color:' + iconColor + ';width:16px;flex-shrink:0;"></i>' +
      '<span class="lh-webdav-name">' + esc(item.name) + '</span>' + sizeStr +
    '</div>';
  });

  return html;
}

export function getFileIcon(mime, name) {
  if (!name) name = '';
  var ext = name.split('.').pop().toLowerCase();
  if (mime && mime.includes('pdf') || ext === 'pdf') return 'fa-file-pdf';
  if (['doc', 'docx'].includes(ext)) return 'fa-file-word';
  if (['txt', 'md'].includes(ext)) return 'fa-file-lines';
  if (['html', 'htm'].includes(ext)) return 'fa-file-code';
  return 'fa-file';
}

export function formatBytes(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + ' KB';
  return (bytes / 1024 / 1024).toFixed(1) + ' MB';
}
