<?php
\defined('_JEXEC') or die;

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Language\Text;
?>

<!-- Scan-Formular -->
<form action="<?php echo Route::_('index.php?option=com_eis&task=display.scan'); ?>" method="post" name="adminForm" id="adminForm">
  <div class="form-horizontal">
    <fieldset class="adminform">
      <legend><?php echo Text::_('COM_EIS_DOCUMENT_PATH'); ?></legend>
      <!-- Optional: Hier später Pfad aus Einstellungen anzeigen -->
    </fieldset>

    <div class="mt-2">
      <button class="btn btn-primary" type="submit">
        <?php echo Text::_('COM_EIS_SCAN_DOCUMENTS'); ?>
      </button>
    </div>
  </div>
  <?php echo HTMLHelper::_('form.token'); ?>
</form>

<hr>

<?php $hasTree = !empty($this->treeHtml); ?>

<?php if (!$hasTree): ?>
  <p class="text-muted">
    <?php echo Text::_('COM_EIS_NO_DOCUMENTS_FOUND') ?: 'Noch keine Dokumente in der Datenbank. Bitte zuerst „Dokumente einlesen“ ausführen.'; ?>
  </p>
<?php else: ?>

  <style>
    /* Layout */
    .eis-flex {
      display: flex;
      gap: 1rem;
      align-items: flex-start;
    }

    .eis-tree-wrap {
      flex: 1 1 auto;
      background: #f9f9f9;
      border: 1px solid #ddd;
      border-radius: 6px;
      padding: 1em;
    }

    .eis-edit {
      flex: 0 0 360px;
      background: #fff;
      border: 1px solid #ddd;
      border-radius: 6px;
      padding: 1em;
    }

    .eis-edit h4 {
      margin-top: 0;
    }

    /* Baum */
    .pdf-tree {
      list-style: none;
      margin: 0;
      padding: 0;
    }

    .pdf-tree ul {
      list-style: none;
      margin-left: 1.5em;
      padding: 0;
      display: none;
    }

    /* Unterebenen eingeklappt */
    .pdf-tree li {
      margin: .3em 0;
    }

    .folder>.toggle {
      cursor: pointer;
      width: 1em;
      display: inline-block;
      user-select: none;
    }

    .folder>.folder-label,
    .file>.file-label {
      cursor: pointer;
      user-select: none;
    }

    .pdf-tree .meta {
      color: #666;
    }

    .pdf-tree .count {
      color: #999;
    }

    /* Steuerleiste */
    .controls {
      margin-bottom: .75em;
    }

    .controls button {
      margin-right: .5em;
    }
  </style>

  <h3 class="mt-3"><?php echo Text::_('COM_EIS_PDF_TREE') ?: 'PDF-Baum'; ?></h3>

  <div class="eis-flex">

    <!-- Linke Seite: Baum -->
    <div class="eis-tree-wrap">
      <div class="controls">
        <button id="eis-expand-all" type="button" class="btn btn-sm btn-secondary">
          <?php echo Text::_('JGLOBAL_EXPAND_ALL') ?: 'Ausklappen'; ?>
        </button>
        <button id="eis-collapse-all" type="button" class="btn btn-sm btn-secondary">
          <?php echo Text::_('JGLOBAL_COLLAPSE_ALL') ?: 'Einklappen'; ?>
        </button>
      </div>

      <div class="tree">
        <?php echo $this->treeHtml; ?>
      </div>
    </div>

    <!-- Rechte Seite: Inline-Bearbeitungsformular -->
    <div class="eis-edit">
      <h4><?php echo Text::_('COM_EIS_EDIT_TITLE') ?: 'Anzeigename bearbeiten'; ?></h4>
      <form action="<?php echo Route::_('index.php?option=com_eis&task=display.rename'); ?>" method="post" id="eis-rename-form">
        <div class="control-group">
          <label for="eis-current-name"><?php echo Text::_('COM_EIS_FIELD_NAME') ?: 'Originalname'; ?></label>
          <input type="text" id="eis-current-name" class="form-control" value="" readonly>
        </div>

        <div class="control-group" style="margin-top:.5rem;">
          <label for="eis-title"><?php echo Text::_('COM_EIS_FIELD_TITLE') ?: 'Anzeigename (optional)'; ?></label>
          <input type="text" name="title" id="eis-title" class="form-control" value="" placeholder="<?php echo Text::_('COM_EIS_PLACEHOLDER_TITLE') ?: 'Leer lassen = automatisch aus Dateiname'; ?>">
        </div>

        <input type="hidden" name="id" id="eis-id" value="">

        <div style="margin-top:.75rem;">
          <button type="submit" class="btn btn-success">
            <?php echo Text::_('JSAVE') ?: 'Speichern'; ?>
          </button>
          <button type="button" id="eis-clear-title" class="btn btn-light">
            <?php echo Text::_('JDEFAULT') ?: 'Zurücksetzen'; ?>
          </button>
        </div>

        <?php echo HTMLHelper::_('form.token'); ?>
      </form>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const wrap = document.querySelector('.eis-tree-wrap');
      const form = document.getElementById('eis-rename-form');
      const idField = document.getElementById('eis-id');
      const nameField = document.getElementById('eis-current-name');
      const titleField = document.getElementById('eis-title');
      const clearBtn = document.getElementById('eis-clear-title');

      if (!wrap || !form) return;

      // Einzelnes Toggle: Caret ODER Label
      wrap.addEventListener('click', (e) => {
        const t = e.target;

        // Toggle (Caret oder Label für Ordner)
        if (t.classList.contains('toggle') || t.classList.contains('folder-label')) {
          const li = t.closest('li.folder');
          if (li) {
            // direkte Kind-UL finden
            let childUl = null;
            for (const el of li.children) {
              if (el.tagName === 'UL') {
                childUl = el;
                break;
              }
            }
            if (childUl) {
              const open = childUl.style.display === 'block';
              childUl.style.display = open ? 'none' : 'block';
              const caret = li.querySelector(':scope > .toggle') || li.querySelector('.toggle');
              if (caret) caret.textContent = open ? '▶' : '▼';
            }
          }
        }

        // Auswahl fürs Bearbeiten: Klick auf Ordner- oder Datei-Label
        if (t.classList.contains('folder-label') || t.classList.contains('file-label')) {
          const li = t.closest('li');
          if (!li) return;

          const id = li.getAttribute('data-id') || '';
          const title = li.getAttribute('data-title') || '';
          const name = li.getAttribute('data-name') || '';

          idField.value = id;
          nameField.value = name;
          titleField.value = title;
          titleField.focus();
        }
      });

      // "Zurücksetzen" = Anzeigename löschen (fällt auf Dateiname zurück)
      clearBtn?.addEventListener('click', () => {
        titleField.value = '';
        titleField.focus();
      });

      // Global: Alle aus-/einklappen
      document.getElementById('eis-expand-all')?.addEventListener('click', () => {
        document.querySelectorAll('.pdf-tree ul').forEach(ul => ul.style.display = 'block');
        document.querySelectorAll('.pdf-tree .toggle').forEach(t => t.textContent = '▼');
      });
      document.getElementById('eis-collapse-all')?.addEventListener('click', () => {
        document.querySelectorAll('.pdf-tree ul').forEach(ul => ul.style.display = 'none');
        document.querySelectorAll('.pdf-tree .toggle').forEach(t => t.textContent = '▶');
      });
    });
  </script>

<?php endif; ?>