<div class="w-full max-w-3xl mt-6 mx-auto bg-gray-800/50">
  <div class="backdrop-blur-md bg-white/6 rounded-xl p-6 glass-card">
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-xl font-semibold">Ajustes del servidor</h2>
    </div>
    <form id="guildSettingsForm" class="space-y-4">
      <div>
        <label class="block text-sm text-violet-300 mb-1">Prefix del bot</label>
        <input type="text" name="prefix" id="prefixInput" value="<%= (guildConfig && guildConfig.prefix) || '' %>" class="w-full rounded p-2 bg-transparent border-2 border-dashed" placeholder="!" />
      </div>
      <div>
        <label class="block text-sm text-violet-300 mb-1">AI Role Prompt (opcional)</label>
        <textarea name="aiRolePrompt" id="aiRoleInput" rows="4" class="w-full rounded p-2 bg-transparent border-2 border-dashed" placeholder="E.g. Actúa como un moderador amigable..."><%= (guildConfig && guildConfig.aiRolePrompt) || '' %></textarea>
      </div>

      <div>
        <label class="block text-sm text-violet-300 mb-1">Roles de staff</label>
          <% const selectedStaff = (guildConfig && Array.isArray(guildConfig.staff) ? guildConfig.staff.map(String) : (guildConfig && guildConfig.staff ? String(guildConfig.staff).split(',') : [])) || []; %>
          <% if (typeof guildRoles !== 'undefined' && guildRoles && guildRoles.length) { %>
            <div class="mb-2">
              <div id="staffTagsContainer" class="w-full rounded p-3 flex flex-col sm:flex-row items-start sm:items-center gap-2">
                <div id="staffChips" class="flex-1 min-w-0 flex items-center gap-2 flex-wrap"></div>
                <button id="openRolePicker" type="button" class="ml-0 sm:ml-2 inline-flex items-center justify-center px-3 py-1 rounded bg-white/6 hover:bg-white/10">
                  <!-- plus svg -->
                  <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v14m-7-7h14"/></svg>
                </button>
                <input type="hidden" id="staffHidden" name="staff" value="<%= selectedStaff.join(',') %>" />
              </div>


              <!-- Role picker modal (hidden by default) -->
              <div id="rolePickerModal" class="fixed inset-0 flex items-end sm:items-center justify-center z-50 hidden">
                <div class="absolute inset-0 bg-black/50" id="rolePickerBackdrop"></div>
                <div class="relative w-full sm:w-auto max-w-md bg-gray-800 rounded-t-lg sm:rounded p-4 shadow-lg glass-card mx-2 sm:mx-0" style="max-height:85vh; overflow:auto;">
                  <div class="flex items-center justify-between mb-2">
                    <strong class="text-sm">Seleccionar roles</strong>
                    <button id="closeRolePicker" type="button" class="text-slate-300">✕</button>
                  </div>
                  <input id="rolePickerSearch" class="w-full rounded p-2 bg-transparent border-2 border-dashed mb-2" placeholder="Filtrar roles..." />
                  <div id="rolePickerList" class="max-h-60 overflow-auto rounded bg-white/4 p-1"></div>
                </div>
              </div>
            </div>
          <% } else { %>
            <input type="text" name="staff" id="staffInput" value="<%= (guildConfig && (Array.isArray(guildConfig.staff) ? guildConfig.staff.join(',') : guildConfig.staff)) || '' %>" class="w-full rounded p-2 bg-transparent border border-white/6" placeholder="123... , 456..." />
            <div class="text-xs text-slate-300 mt-1">No se pudo obtener roles desde la API. Introduce IDs manualmente separadas por coma.</div>
          <% } %>
        </div>
      <div class="flex items-center gap-3">
        <button type="submit" class="pixel-btn">Guardar</button>
        <span id="saveStatus" class="text-sm text-slate-300"></span>
      </div>
    </form>
  </div>
</div>

<script>
  (function(){
    const form = document.getElementById('guildSettingsForm');
    const status = document.getElementById('saveStatus');
    const staffFilter = document.getElementById('staffFilter');
    if (staffFilter) {
      staffFilter.addEventListener('input', ()=>{
        const q = staffFilter.value.trim().toLowerCase();
        const sel = document.getElementById('staffSelect');
        if (!sel) return;
        for (const opt of Array.from(sel.options)) {
          const txt = (opt.textContent || '').toLowerCase();
          opt.style.display = (!q || txt.indexOf(q) !== -1) ? '' : 'none';
        }
      });
    }
    form.addEventListener('submit', async (e)=>{
      e.preventDefault();
      status.textContent = 'Guardando...';
      const prefix = document.getElementById('prefixInput').value.trim();
      const aiRolePrompt = document.getElementById('aiRoleInput').value.trim();
      let staffArr = [];
      const staffSelect = document.getElementById('staffSelect');
      if (staffSelect) {
        for (const o of staffSelect.selectedOptions) staffArr.push(o.value);
      } else {
        const staffRaw = (document.getElementById('staffInput') && document.getElementById('staffInput').value) ? document.getElementById('staffInput').value.trim() : '';
        staffArr = staffRaw ? staffRaw.split(',').map(s=>s.trim()).filter(Boolean) : [];
      }
      const payload = { prefix: prefix, aiRolePrompt: aiRolePrompt.length ? aiRolePrompt : null, staff: staffArr };
      try {
        const res = await fetch(`/api/dashboard/${encodeURIComponent('<%= selectedGuild %>')}/settings`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        const json = await res.json();
        if (res.ok && json.ok) {
          status.textContent = 'Guardado';
          setTimeout(()=> status.textContent = '', 2500);
        } else {
          status.textContent = json.error || 'Error';
        }
      } catch (err) {
        status.textContent = 'Error de red';
      }
    });
  })();
    (function(){
      const form = document.getElementById('guildSettingsForm');
      const status = document.getElementById('saveStatus');

      // Multi-select tag/autocomplete for roles
      const staffTagInput = document.getElementById('staffTagInput');
      const staffSuggestions = document.getElementById('staffSuggestions');
      const staffChips = document.getElementById('staffChips');
      const staffHidden = document.getElementById('staffHidden');

    // Prepare role options (id, name, color) from server-side `guildRoles`
    <% 
      // Build a simple roles array with normalized color (hex string)
      const _roles = (guildRoles||[]).map(r=>{
        let c = '#8b95a0';
        if (r && (typeof r.color !== 'undefined') && r.color !== null) {
          if (typeof r.color === 'number') {
            c = '#'+('000000'+(r.color).toString(16)).slice(-6);
          } else {
            c = String(r.color).replace(/^#?/, '#');
          }
        } else if (r && (r.colorHex || r.hex)) {
          c = String(r.colorHex || r.hex).replace(/^#?/, '#');
        }
        return { id: String(r.id), name: String(r.name || r.id), color: c };
      });
    %>
  let ROLE_OPTIONS = <%- JSON.stringify(_roles) %>;
    // Initial selected staff IDs (strings)
  const INITIAL_STAFF = <%- JSON.stringify(selectedStaff || []) %>;

      let selectedIds = Array.isArray(INITIAL_STAFF) ? INITIAL_STAFF.slice() : [];

        // Fallback: if server didn't provide ROLE_OPTIONS (empty), try to read from any
        // existing <select> on the page or request roles from server API at runtime.
        (async function ensureRoleOptions(){
          try {
            if (!Array.isArray(ROLE_OPTIONS) || ROLE_OPTIONS.length === 0) {
              // try to read an existing select element first
              const sel = document.getElementById('staffSelect') || document.querySelector('select[name="staff"]');
              if (sel && sel.options && sel.options.length) {
                ROLE_OPTIONS = Array.from(sel.options).map(o => ({ id: String(o.value), name: String(o.textContent || o.innerText || o.label || o.value).trim(), color: (o.dataset && o.dataset.color) ? o.dataset.color : '#8b95a0' }));
                renderChips();
                return;
              }
              // otherwise, try fetching roles from server at runtime
              try {
                const guildId = '<%= selectedGuild %>';
                if (guildId) {
                  const resp = await fetch(`/api/dashboard/${encodeURIComponent(guildId)}/roles`, { method: 'GET', headers: { 'Accept': 'application/json' } });
                  if (resp.ok) {
                    const j = await resp.json();
                    if (j && Array.isArray(j.roles) && j.roles.length) {
                      ROLE_OPTIONS = j.roles.map(r=>({ id: String(r.id), name: String(r.name||r.id), color: r.color || '#8b95a0' }));
                      renderChips();
                      return;
                    }
                  }
                }
              } catch (e){ /* ignore fetch errors */ }
            }
          } catch (e) {
            // ignore
          }
        })();

      function renderChips(){
        if (!staffChips) return;
        staffChips.innerHTML = '';
        for(const id of selectedIds){
          const role = ROLE_OPTIONS.find(r=>r.id===String(id));
          const label = role ? role.name : String(id);
          const chip = document.createElement('div');
          chip.className = 'px-2 py-1 bg-white/6 rounded-full text-sm flex items-center gap-2';
          const swatch = role && role.color ? `<span class="w-3 h-3 rounded-full inline-block" style="background:${role.color}"></span>` : '';
          chip.innerHTML = `${swatch}<span class="truncate">${label}</span><button type="button" class="ml-2 text-xs text-slate-300 remove-chip" data-id="${id}">✕</button>`;
          staffChips.appendChild(chip);
        }
        // update hidden input
        if(typeof staffHidden !== 'undefined' && staffHidden) staffHidden.value = selectedIds.join(',');
      }

      function showSuggestions(query){
        if(!staffSuggestions) return;
        const q = (query||'').trim().toLowerCase();
        const filtered = ROLE_OPTIONS.filter(r=> !selectedIds.includes(String(r.id)) && (!q || r.name.toLowerCase().includes(q) || String(r.id).includes(q)) ).slice(0,50);
        if(!filtered.length){ staffSuggestions.classList.add('hidden'); staffSuggestions.innerHTML=''; return; }
        staffSuggestions.classList.remove('hidden');
    staffSuggestions.innerHTML = filtered.map(r=>`<li class="p-2 hover:bg-white/10 cursor-pointer flex items-center gap-2" data-id="${r.id}"><span class="w-3 h-3 rounded-full inline-block" style="background:${r.color}"></span><span class="truncate">${r.name}</span></li>`).join('');
      }

      function addId(id){
        id = String(id);
        if(!id) return;
        if(selectedIds.includes(id)) return;
        selectedIds.push(id);
        renderChips();
      }

      function removeId(id){
        id = String(id);
        selectedIds = selectedIds.filter(i=>String(i)!==id);
        renderChips();
      }

    // initial render of chips
    renderChips();

    // Listen for runtime roles loaded events (from reload button in sidebar)
    window.addEventListener('roles:loaded', (ev)=>{
      try{
        const data = ev && ev.detail && ev.detail.roles ? ev.detail.roles : null;
        if(!data || !Array.isArray(data)) return;
        ROLE_OPTIONS = data.map(r=>({ id: String(r.id), name: String(r.name||r.id), color: r.color || '#8b95a0' }));
        renderChips();
        if(typeof populateRolePicker === 'function') populateRolePicker('');
      }catch(e){ /* ignore */ }
    });

    // Role picker modal logic
    const openRolePicker = document.getElementById('openRolePicker');
    const rolePickerModal = document.getElementById('rolePickerModal');
    const rolePickerBackdrop = document.getElementById('rolePickerBackdrop');
    const rolePickerList = document.getElementById('rolePickerList');
    const rolePickerSearch = document.getElementById('rolePickerSearch');
    const closeRolePicker = document.getElementById('closeRolePicker');
    const rolePickerDone = document.getElementById('rolePickerDone');

    function populateRolePicker(filter){
      if(!rolePickerList) return;
      const q = (filter||'').trim().toLowerCase();
      const items = ROLE_OPTIONS.filter(r=> !selectedIds.includes(String(r.id)) && (!q || r.name.toLowerCase().includes(q)) ).slice(0,200);
      rolePickerList.innerHTML = items.map(r=>`<div class="p-2 hover:bg-white/10 cursor-pointer flex items-center gap-3 role-item" data-id="${r.id}" data-name="${r.name}"><span class="w-3 h-3 rounded-full inline-block" style="background:${r.color}"></span><span class="truncate">${r.name}</span></div>`).join('');
    }

    function openPicker(){
      if(!rolePickerModal) return;
      rolePickerModal.classList.remove('hidden');
      // prevent body scroll on mobile when modal open
      try{ document.documentElement.style.overflow = 'hidden'; }catch(e){}
      populateRolePicker('');
      setTimeout(()=>{ if(rolePickerSearch) rolePickerSearch.focus(); },50);
    }
    function closePicker(){
      if(!rolePickerModal) return;
      rolePickerModal.classList.add('hidden');
      // restore body scroll
      try{ document.documentElement.style.overflow = ''; }catch(e){}
      if(rolePickerSearch) rolePickerSearch.value = '';
      if(rolePickerList) rolePickerList.innerHTML = '';
    }

    if(openRolePicker){
      openRolePicker.addEventListener('click', (e)=>{ e.preventDefault(); openPicker(); });
    }
    if(rolePickerBackdrop){ rolePickerBackdrop.addEventListener('click', closePicker); }
    if(closeRolePicker){ closeRolePicker.addEventListener('click', closePicker); }

    if(rolePickerSearch){
      rolePickerSearch.addEventListener('input', ()=> populateRolePicker(rolePickerSearch.value));
      rolePickerSearch.addEventListener('keydown', (e)=>{
        if(e.key === 'Enter'){
          e.preventDefault();
          // pick first item
          const first = rolePickerList && rolePickerList.querySelector('.role-item');
          if(first){ addId(first.dataset.id); closePicker(); }
        } else if(e.key === 'Escape'){
          closePicker();
        }
      });
    }

    // Close modal on Escape globally (only when open)
    document.addEventListener('keydown', (ev)=>{
      if(ev.key === 'Escape' && rolePickerModal && !rolePickerModal.classList.contains('hidden')){
        closePicker();
      }
    });

    if(rolePickerList){
      rolePickerList.addEventListener('click', (ev)=>{
        const it = ev.target.closest && ev.target.closest('.role-item');
        if(!it) return;
        addId(it.dataset.id);
        // remove the clicked item from list
        it.remove();
      });
    }

    if(rolePickerDone){ rolePickerDone.addEventListener('click', (e)=>{ e.preventDefault(); closePicker(); }); }

    staffChips.addEventListener('click', (ev)=>{
      const btn = ev.target.closest('.remove-chip');
      if(!btn) return;
      removeId(btn.dataset.id);
    });

      form.addEventListener('submit', async (e)=>{
        e.preventDefault();
        status.textContent = 'Guardando...';
        const prefix = document.getElementById('prefixInput').value.trim();
        const aiRolePrompt = document.getElementById('aiRoleInput').value.trim();
        let staffArr = [];
        if(typeof selectedIds !== 'undefined' && selectedIds && selectedIds.length){
          staffArr = selectedIds.slice();
        } else if (document.getElementById('staffInput')){
          const staffRaw = document.getElementById('staffInput').value.trim();
          staffArr = staffRaw ? staffRaw.split(',').map(s=>s.trim()).filter(Boolean) : [];
        }
        const payload = { prefix: prefix, aiRolePrompt: aiRolePrompt.length ? aiRolePrompt : null, staff: staffArr };
        try {
          const res = await fetch(`/api/dashboard/${encodeURIComponent('<%= selectedGuild %>')}/settings`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
          });
          const json = await res.json();
          if (res.ok && json.ok) {
            status.textContent = 'Guardado';
            setTimeout(()=> status.textContent = '', 2500);
          } else {
            status.textContent = json.error || 'Error';
          }
        } catch (err) {
          status.textContent = 'Error de red';
        }
      });
    })();
</script>
