{include file="_partials/head.tpl"}

<link rel="stylesheet" href="/public/assets/admin/codemirror.min.css">
<link rel="stylesheet" href="/public/assets/admin/codemirror-dracula.css">
<link rel="stylesheet" href="/public/assets/admin/codemirror-material.css">
<script src="/public/assets/admin/codemirror.min.js"></script>
<script src="/public/assets/admin/codemirror-xml.min.js"></script>
<script src="/public/assets/admin/codemirror-css.min.js"></script>
<script src="/public/assets/admin/codemirror-js.min.js"></script>
<script src="/public/assets/admin/codemirror-htmlmixed.min.js"></script>
<script src="/public/assets/admin/codemirror-active-line.js"></script>
<script src="/public/assets/admin/codemirror-matchbrackets.js"></script>

<div class="page-head">
  <div>
    <h1>Редактор шаблонов: {theme}</h1>
    <p class="muted"><a href="/admin/templates">← К списку тем</a></p>
  </div>
</div>

<div class="tpl-editor" data-tpl-theme="{theme}" data-tpl-file="{selected}">
  <aside class="tpl-files">
    <div class="tpl-files-head">
      <span class="muted">Файлы темы</span>
      <input type="search" class="tpl-files-search" placeholder="фильтр…" data-tpl-files-filter>
    </div>
    <ul class="tpl-files-list">
      [foreach var="files" as="f"]
        <li>
          <a href="?file={f}" class="tpl-file-item [if {selected}={f}]is-active[/if]" data-tpl-file-name="{f}">
            {icon name="pages" size="14"}
            <span class="tpl-file-name">{f}</span>
          </a>
        </li>
      [/foreach]
    </ul>
  </aside>

  <main class="tpl-main">
    <form method="post" action="/admin/templates/{theme}/save" id="saveForm">
      {csrf}
      <input type="hidden" name="file" value="{selected}">
      <textarea id="editor" name="content" spellcheck="false">{content}</textarea>
      <div class="tpl-actions">
        <button type="submit" class="btn btn-primary">Сохранить</button>
        <button type="button" class="btn btn-secondary" onclick="runPreview()">👁 Предпросмотр</button>
      </div>
    </form>
    <iframe id="preview" style="display:none"></iframe>
  </main>

  <aside class="tpl-palette">
    <button type="button" class="btn btn-secondary" data-tag-docs-open style="width:100%;margin-bottom:10px;justify-content:center">
      {icon name="news" size="14"} Справочник тегов
    </button>
    <h4>Inline-теги</h4>
    <ul>
      [foreach var="inline_tags" as="t"]
        <li><code onclick="insert('{'+'{t}'+'}')">&#123;{t}&#125;</code></li>
      [/foreach]
    </ul>
    <h4>Block-теги</h4>
    <ul>
      [foreach var="block_tags" as="t"]
        <li><code onclick="insertBlock('{t}')">&#91;{t}&#93;…&#91;/{t}&#93;</code></li>
      [/foreach]
    </ul>
    <h4>Сниппеты</h4>
    <ul class="snippets">
      <li><code data-snippet="ifcond">&#91;if …&#93;&#91;/if&#93;</code></li>
      <li><code data-snippet="foreach">&#91;foreach&#93;</code></li>
      <li><code data-snippet="include">&#123;include&#125;</code></li>
      <li><code data-snippet="async">&#123;async&#125;</code></li>
      <li><code data-snippet="csrf">&#123;csrf&#125;</code></li>
    </ul>
  </aside>
</div>

<script>
var ed = document.getElementById('editor');
var form = document.getElementById('saveForm');

// Определяем тему CodeMirror по активной теме админки
var adminTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dracula' : 'material';
var cm = CodeMirror.fromTextArea(ed, {
  mode: 'htmlmixed',
  theme: adminTheme,
  lineNumbers: true,
  lineWrapping: true,
  indentUnit: 2,
  tabSize: 2,
  matchBrackets: true,
  styleActiveLine: true,
  autofocus: true
});
window.tplEditorCM = cm;

// При отправке формы — копируем значение обратно в textarea
form.addEventListener('submit', function () { cm.save(); });

// Реагируем на смену темы админки
new MutationObserver(function (muts) {
  for (var i = 0; i < muts.length; i++) {
    if (muts[i].attributeName === 'data-theme') {
      var t = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dracula' : 'material';
      cm.setOption('theme', t);
    }
  }
}).observe(document.documentElement, { attributes: true });

function ins(text) {
  var doc = cm.getDoc();
  doc.replaceSelection(text);
  cm.focus();
}
function insert(tag) { ins(tag); }
function insertBlock(name) { ins('[' + name + ']\n  \n[/' + name + ']'); }

// Значения-примеры собираем из частей, чтобы шаблонизатор не исполнил {include}/{csrf}/{async}
// как настоящие inline-теги при компиляции этого <script> (он парсит {...} даже внутри script).
var B = '{';
var SNIPPETS = {
  ifcond:  '[if ' + B + 'var}="x"]\n  \n[/if]',
  foreach: '[foreach var="items" as="i"]\n  \n[/foreach]',
  include: B + 'include file="_partials/head.tpl"}',
  async:   B + 'async block="name"}',
  csrf:    B + 'csrf}'
};
document.querySelectorAll('[data-snippet]').forEach(function (el) {
  el.addEventListener('click', function () {
    var key = el.getAttribute('data-snippet');
    if (SNIPPETS[key]) ins(SNIPPETS[key]);
  });
});

// Фильтр файлов
var filter = document.querySelector('[data-tpl-files-filter]');
if (filter) {
  filter.addEventListener('input', function () {
    var q = filter.value.trim().toLowerCase();
    document.querySelectorAll('.tpl-files-list li').forEach(function (li) {
      var name = li.querySelector('.tpl-file-name').textContent.toLowerCase();
      li.classList.toggle('is-hidden', q !== '' && name.indexOf(q) === -1);
    });
  });
}

// Ctrl+S
cm.setOption('extraKeys', {
  'Ctrl-S': function () { form.submit(); },
  'Cmd-S':  function () { form.submit(); },
  'Tab':    function (cm) { cm.replaceSelection('  '); }
});

function runPreview() {
  var iframe = document.getElementById('preview');
  var wrap = document.querySelector('[data-tpl-theme]');
  var theme = wrap.getAttribute('data-tpl-theme');
  var selected = wrap.getAttribute('data-tpl-file');
  var token = (document.querySelector('meta[name=csrf-token]') || {}).content || '';
  var fd = new FormData();
  fd.append('file', selected);
  fd.append('content', (window.tplEditorCM ? window.tplEditorCM.getValue() : ed.value));
  fd.append('_csrf', token);
  fetch('/admin/templates/' + encodeURIComponent(theme) + '/preview', {
    method: 'POST', body: fd, credentials: 'same-origin',
    headers: { 'X-CSRF-Token': token }
  })
    .then(function (r) {
      if (r.headers.get('content-type').indexOf('application/json') !== -1) {
        return r.json().then(function (j) { throw new Error(j.error || 'Ошибка'); });
      }
      return r.text();
    })
    .then(function (html) {
      iframe.style.display = 'block';
      iframe.srcdoc = html;
    })
    .catch(function (e) {
      var msg = 'Предпросмотр: ' + e.message;
      if (window.Celena && window.Celena.alert) window.Celena.alert(msg, { type: 'error' });
      else alert(msg);
    });
}
</script>

<style>
.tpl-editor { display: grid; grid-template-columns: 260px 1fr 260px; gap: 16px; align-items: start; }
.tpl-files, .tpl-palette { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px; font-size: 13px; }
.tpl-files { padding: 12px 8px; max-height: 80vh; display: flex; flex-direction: column; overflow: hidden; }
.tpl-files-head { display: flex; flex-direction: column; gap: 6px; padding: 0 6px 8px; border-bottom: 1px solid var(--border-soft); }
.tpl-files-search { padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: 12px; font-family: inherit; }
.tpl-files-list { list-style: none; margin: 6px 0 0; padding: 0 4px; overflow-y: auto; flex: 1; }
.tpl-files-list li { margin: 1px 0; }
.tpl-file-item {
  display: flex; align-items: center; gap: 8px;
  padding: 6px 10px; border-radius: 6px;
  font-family: ui-monospace, Consolas, monospace; font-size: 12.5px;
  color: var(--text-muted); text-decoration: none;
  transition: background 0.12s ease, color 0.12s ease;
}
.tpl-file-item:hover { background: var(--surface-2); color: var(--text); }
.tpl-file-item.is-active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.tpl-file-item .icon { flex-shrink: 0; opacity: 0.7; }
.tpl-file-item.is-active .icon { opacity: 1; }
.tpl-file-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tpl-files-list li.is-hidden { display: none; }
.tpl-palette h4 { margin: 12px 0 6px; font-size: 12px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em; }
.tpl-palette h4:first-child { margin-top: 0; }
.tpl-palette ul { list-style: none; padding: 0; margin: 0; }
.tpl-palette li { margin: 4px 0; }
.tpl-palette code { background: var(--surface-2); padding: 3px 6px; border-radius: 4px; cursor: pointer; font-size: 12px; display: block; }
.tpl-palette code:hover { background: var(--accent); color: var(--accent-contrast); }
.tpl-main textarea { width: 100%; min-height: 520px; font-family: ui-monospace, Consolas, monospace; font-size: 13px; padding: 12px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg); color: var(--text); tab-size: 2; }
.tpl-main .CodeMirror {
  height: 540px; border-radius: var(--radius);
  border: 1px solid var(--border-soft);
  font-family: 'JetBrains Mono', ui-monospace, Consolas, monospace; font-size: 13.5px;
  box-shadow: var(--shadow-soft);
}
.tpl-main .CodeMirror-gutters { border-right: 1px solid rgba(255,255,255,0.06); }
.tpl-actions { margin-top: 12px; display: flex; gap: 8px; }
#preview { width: 100%; min-height: 500px; margin-top: 12px; border: 1px solid var(--border); border-radius: var(--radius); background: white; }
</style>

{include file="_partials/foot.tpl"}
