{% extends "base.html" %}

{% block title %}{% if menu %}Edit{% else %}New{% endif %} BBS Menu{% endblock %}

{% block content %}
<div class="bbs-header">
  <h1><i class="bi bi-list-nested"></i> {% if menu %}Edit menu: <code>{{ menu.name }}</code>{% else %}New menu{% endif %}</h1>
</div>

<form method="post">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

  {% if not menu %}
  <div class="mb-3">
    <label class="form-label">Name (key)</label>
    <input name="name" class="form-control" placeholder="e.g. main, sysop, doors" required>
    <small class="text-muted">Lowercase, used as the lookup key in goto actions.</small>
  </div>
  {% endif %}

  <div class="mb-3">
    <label class="form-label">Title</label>
    <input name="title" class="form-control" value="{{ menu.title if menu else '' }}" required>
  </div>

  <div class="mb-3">
    <label class="form-label">Prompt</label>
    <input name="prompt" class="form-control" value="{{ menu.prompt if menu else 'Choice: ' }}">
  </div>

  <div class="mb-3">
    <label class="form-label">ANSI screen (optional — raw CP437 / ANSI escape codes; if blank an auto box-menu is rendered)</label>
    <div class="row g-2">
      <div class="col-md-6">
        <textarea id="ansi-source" name="ansi_screen" class="form-control font-monospace"
                  rows="14" style="white-space: pre; overflow: auto;"
                  oninput="updateAnsiPreview()">{{ menu.ansi_screen if menu else '' }}</textarea>
        <small class="text-muted">
          Tip: paste any .ans file content, or use codes like
          <code>\x1b[1;32m</code> (bright green), <code>\x1b[2J\x1b[H</code> (clear screen).
        </small>
      </div>
      <div class="col-md-6">
        <label class="form-label small">Live preview:</label>
        <pre id="ansi-preview" class="font-monospace"
             style="background:#000; color:#ccc; padding:10px; min-height:280px;
                    border:1px solid var(--theme-border); border-radius:4px;
                    white-space: pre; overflow:auto;"></pre>
      </div>
    </div>
  </div>
  <script>
    // Minimal ANSI-to-HTML renderer for the live preview.
    // Handles \x1b[<n>;<n>m sequences for color + bold/reset, and \x1b[2J / \x1b[H.
    function ansiToHtml(text) {
      // Treat literal "\x1b" and "\033" in the source as escapes too
      text = text.replace(/\\x1b/g, '\x1b').replace(/\\033/g, '\x1b').replace(/\\e/g, '\x1b');
      const fg = {30:'#000',31:'#a00',32:'#0a0',33:'#a50',34:'#00a',35:'#a0a',36:'#0aa',37:'#aaa',
                  90:'#555',91:'#f55',92:'#5f5',93:'#ff5',94:'#55f',95:'#f5f',96:'#5ff',97:'#fff'};
      const bg = {40:'#000',41:'#a00',42:'#0a0',43:'#a50',44:'#00a',45:'#a0a',46:'#0aa',47:'#aaa'};
      let out = '', cur = {fg:'#ccc', bg:null, bold:false}, openSpan = false;
      function reopen() {
        if (openSpan) { out += '</span>'; openSpan = false; }
        let style = 'color:' + (cur.fg || '#ccc');
        if (cur.bg) style += ';background:' + cur.bg;
        if (cur.bold) style += ';font-weight:bold';
        out += '<span style="' + style + '">';
        openSpan = true;
      }
      reopen();
      let i = 0;
      while (i < text.length) {
        if (text[i] === '\x1b' && text[i+1] === '[') {
          let j = text.indexOf('m', i + 2);
          let cmd = text.indexOf('J', i + 2); if (cmd > 0 && (j < 0 || cmd < j)) {
            // Clear-screen / similar — just inject a visual divider in preview
            i = cmd + 1; continue;
          }
          let H = text.indexOf('H', i + 2); if (H > 0 && (j < 0 || H < j)) { i = H + 1; continue; }
          if (j < 0) { i++; continue; }
          const codes = text.substring(i+2, j).split(';').map(s => parseInt(s,10) || 0);
          for (const c of codes) {
            if (c === 0) { cur = {fg:'#ccc', bg:null, bold:false}; }
            else if (c === 1) { cur.bold = true; }
            else if (c === 22) { cur.bold = false; }
            else if (fg[c]) { cur.fg = fg[c]; }
            else if (bg[c]) { cur.bg = bg[c]; }
          }
          reopen();
          i = j + 1;
          continue;
        }
        // Escape HTML special chars
        const ch = text[i];
        if (ch === '<') out += '&lt;';
        else if (ch === '>') out += '&gt;';
        else if (ch === '&') out += '&amp;';
        else out += ch;
        i++;
      }
      if (openSpan) out += '</span>';
      return out;
    }
    function updateAnsiPreview() {
      const src = document.getElementById('ansi-source').value;
      document.getElementById('ansi-preview').innerHTML = ansiToHtml(src);
    }
    document.addEventListener('DOMContentLoaded', updateAnsiPreview);
  </script>

  <div class="row">
    <div class="col-md-4 mb-3">
      <label class="form-label">Min access</label>
      <input name="min_access" type="number" class="form-control" value="{{ menu.min_access if menu else 0 }}">
      <small class="text-muted">0 = anyone, 100 = sysop</small>
    </div>
    <div class="col-md-4 mb-3 form-check pt-4">
      <input class="form-check-input" name="is_default" type="checkbox" id="isdef"
             {% if menu and menu.is_default %}checked{% endif %}>
      <label class="form-check-label" for="isdef">Default menu (entry point)</label>
    </div>
  </div>

  <button class="btn btn-primary"><i class="bi bi-save"></i> Save menu</button>
  <a href="{{ url_for('menu_admin.list_menus') }}" class="btn btn-outline-secondary">Cancel</a>
</form>

{% if menu %}
<hr>
<h3>Menu Items</h3>

<table class="table table-dark table-sm align-middle">
  <thead><tr><th>Hotkey</th><th>Label</th><th>Action</th><th>Args</th><th>Min</th><th>Ord</th><th>Vis</th><th></th></tr></thead>
  <tbody>
    {% for it in items %}
    <tr>
      <td colspan="8" class="p-1">
        <form method="post" action="{{ url_for('menu_admin.edit_item', item_id=it.id) }}" class="row g-1 align-items-center">
          <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
          <div class="col-1"><input name="hotkey" class="form-control form-control-sm" value="{{ it.hotkey }}"></div>
          <div class="col-3"><input name="label" class="form-control form-control-sm" value="{{ it.label }}"></div>
          <div class="col-2">
            <select name="action_type" class="form-select form-select-sm">
              {% for v, desc in action_types %}
                <option value="{{ v }}" {% if it.action_type == v %}selected{% endif %}>{{ v }}</option>
              {% endfor %}
            </select>
          </div>
          <div class="col-2"><input name="action_args" class="form-control form-control-sm" placeholder="args" value="{{ it.action_args or '' }}"></div>
          <div class="col-1"><input name="min_access" type="number" class="form-control form-control-sm" value="{{ it.min_access }}"></div>
          <div class="col-1"><input name="sort_order" type="number" class="form-control form-control-sm" value="{{ it.sort_order }}"></div>
          <div class="col-1"><input name="is_visible" type="checkbox" class="form-check-input" {% if it.is_visible %}checked{% endif %}></div>
          <div class="col-1 d-flex gap-1">
            <button class="btn btn-sm btn-success" title="Save"><i class="bi bi-check"></i></button>
        </form>
        <form method="post" action="{{ url_for('menu_admin.delete_item', item_id=it.id) }}" class="d-inline" onsubmit="return confirm('Delete this item?')">
          <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
          <button class="btn btn-sm btn-danger"><i class="bi bi-trash"></i></button>
        </form>
          </div>
      </td>
    </tr>
    {% else %}
    <tr><td colspan="8" class="text-muted">No items yet — add one below.</td></tr>
    {% endfor %}
  </tbody>
</table>

<h4>Add new item</h4>
<form method="post" action="{{ url_for('menu_admin.add_item', menu_id=menu.id) }}" class="row g-2">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <div class="col-md-1"><input name="hotkey" class="form-control" placeholder="M" required></div>
  <div class="col-md-3"><input name="label" class="form-control" placeholder="Label" required></div>
  <div class="col-md-2">
    <select name="action_type" class="form-select">
      {% for v, desc in action_types %}<option value="{{ v }}">{{ v }} — {{ desc }}</option>{% endfor %}
    </select>
  </div>
  <div class="col-md-3"><input name="action_args" class="form-control" placeholder="action args"></div>
  <div class="col-md-1"><input name="min_access" type="number" class="form-control" value="0"></div>
  <div class="col-md-1"><input name="sort_order" type="number" class="form-control" value="0"></div>
  <div class="col-md-1"><button class="btn btn-primary"><i class="bi bi-plus"></i></button></div>
</form>

<hr>

<div class="row g-3">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header"><i class="bi bi-diagram-3"></i> Add a sub-menu (one click)</div>
      <div class="card-body">
        <p class="small text-muted mb-2">
          Creates a new menu and adds a <code>goto</code> hotkey on this menu
          that jumps to it. The new menu auto-includes a <code>Q</code> key to
          come back here.
        </p>
        <form method="post" action="{{ url_for('menu_admin.spawn_submenu', menu_id=menu.id) }}" class="row g-2">
          <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
          <div class="col-md-3"><label class="form-label small">Menu key</label>
            <input name="name" class="form-control form-control-sm" placeholder="games_sub" required></div>
          <div class="col-md-5"><label class="form-label small">Title</label>
            <input name="title" class="form-control form-control-sm" placeholder="Game Center" required></div>
          <div class="col-md-1"><label class="form-label small">Hotkey</label>
            <input name="hotkey" class="form-control form-control-sm" placeholder="G" required></div>
          <div class="col-md-3"><label class="form-label small">Item label</label>
            <input name="label" class="form-control form-control-sm" placeholder="Games"></div>
          <div class="col-md-12"><button class="btn btn-success btn-sm"><i class="bi bi-plus-circle"></i> Create sub-menu</button></div>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header"><i class="bi bi-info-circle"></i> Action args cheatsheet</div>
      <ul class="list-group list-group-flush small">
        <li class="list-group-item bg-transparent"><code>goto</code> &mdash; another menu's name (e.g. <code>games_sub</code>)</li>
        <li class="list-group-item bg-transparent"><code>door</code> &mdash; the Game id from <em>Door Games</em> admin</li>
        <li class="list-group-item bg-transparent"><code>ansi</code> &mdash; an ANSI screen slot name (e.g. <code>weather_intro</code>)</li>
        <li class="list-group-item bg-transparent">
          <code>exec</code> &mdash; either a plain command line, or JSON with
          <code>{"cmd":"...","name":"...","dropfile":"door.sys"}</code>.<br>
          You can use <code>{user}</code>, <code>{userid}</code>, <code>{dropdir}</code> in the command.
        </li>
        <li class="list-group-item bg-transparent">All other actions ignore args.</li>
      </ul>
    </div>
  </div>
</div>
{% endif %}
{% endblock %}
