{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>Test Feature Builder</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="{% static 'css/uikit.min.css' %}">
    <style>
      .operation-card {
        border: 1px solid #dadada;
        border-radius: 8px;
        margin: 8px 0;
        padding: 12px;
        background: #fafbfc;
        position: relative;
      }
      .subtitle {
        font-size: 14px;
        color: #777;
      }
      table.reqtable { width:100%; font-size:14px; margin-bottom:8px; }
      table.reqtable th, table.reqtable td { padding:4px 6px; }
      table.reqtable input, table.reqtable select { min-width: 70px; }
      .remove-row { color: #d44; font-weight:bold; cursor:pointer; }
      .add-row-btn { font-size: 13px; margin-top: 2px; }
      summary { font-weight: bold; cursor:pointer; }
    </style>
</head>
<body>
<div class="uk-container uk-padding">
    <h1 class="uk-text-center uk-margin">Test Feature Builder<br><span class="subtitle">Structured Table Entry UI</span></h1>
    <form id="feature-test-form" 
          hx-post="{% if feature %}/{{ system }}/feature/{{ feature.id }}{% else %}/{{ system }}/feature/new{% endif %}"
          hx-trigger="submit"
          hx-target="#toast-dock"
          hx-swap="innerHTML"
          method="POST" autocomplete="off">
      {% csrf_token %}
      <div class="uk-margin">
        <label class="uk-form-label" for="feature_name">Name</label>
        <input class="uk-input" id="feature_name" name="feature_name" type="text" value="{{feature.feature_name|default:''}}" required>
      </div>
      <div class="uk-margin">
        <div id="trait-dock"></div>
        <input id="trait-ajax-autocomplete" class="uk-input uk-input-small">
        <div id="trait-suggestions"></div>
      </div> 
      <div class="uk-width-1-1">
          <label class="uk-form-label" for="feature_description">Description</label>
          <div class="uk-form-controls">
              <textarea class="uk-textarea" id="feature_description" name="feature_description" rows="3">{{feature.feature_description|default:''}}</textarea>
          </div>
      </div>  
      <div class="uk-margin">
        <label class="uk-form-label">Feature Requirements</label>
        <table id="reqtable" class="uk-table reqtable">
          <thead>
            <tr>
              <th>Attribute</th>
              <th>Condition</th>
              <th>Value</th>
            </tr>
          </thead>
          <tbody>
            {% for req in feature.feature_requirements %}
                    <tr>
                      <td><input class="uk-input" type="text" value="{{ req.attr }}"></td>
                      <td>
                        <select class="uk-select">
                          <option value="==" {% if req.condition == "==" %}selected{% endif %}>=</option>
                          <option value=">=" {% if req.condition == ">=" %}selected{% endif %}>&ge;</option>
                          <option value="<=" {% if req.condition == "<=" %}selected{% endif %}>&le;</option>
                          <option value="!=" {% if req.condition == "!=" %}selected{% endif %}>&ne;</option>
                        </select>
                      </td>
                      <td><input class="uk-input" type="text" value="{{ req.value }}"></td>
                    </tr>
            {% endfor %}
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-button-xsmall add-row-btn" id="add-feature-req-btn" onclick="addFeatureRequirement()">Add Requirement</button>
      </div>
      <div>
        <h3>Operations
           <button id="add-operation-btn" type="button" class="uk-button uk-button-primary uk-button-small uk-margin-small-left">
              <span uk-icon="icon: plus"></span> Add Operation
           </button>
        </h3>
        <div id="operations-list"></div>
      </div>
      <div class="uk-margin">
        <button  class="uk-button uk-button-primary uk-width-1-1">Submit Feature</button>
      </div>
    </form>
</div>

<script src="{% static 'js/uikit.min.js' %}"></script>
<script src="{% static 'js/uikit-icons.min.js' %}"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>

  var operations = {{ feature.feature_data.operations|default:'[]'|safe }};
  var selectedTraits = {{ traits|default:'[]'|safe }};
  renderOperations()
  renderTraitChips()

  console.log(operations)
  console.log(selectedTraits)

  document.getElementById('trait-ajax-autocomplete').addEventListener('input', function(){
  let query = this.value.trim();
  if(query.length < 2) return;
  fetch(`/traits/search/?system={{ system }}&q=${encodeURIComponent(query)}`)
    .then(resp => resp.json())
    .then(data => {
        let suggestionElement = document.getElementById('trait-suggestions')

        if(data.length > 0){
          suggestionElement.innerHTML = '<strong>Here are some suggestions: </strong>'
        } else {
          suggestionElement.innerHTML = ''
        }

        data.forEach(trait => {
          let a_link = document.createElement('a')
          a_link.href = "#";
          a_link.innerHTML = trait.trait_name
          a_link.onclick = function(e){
            e.preventDefault();
            addTrait(trait);
          }
      
          suggestionElement.appendChild(a_link)
          suggestionElement.appendChild(document.createTextNode(" "));
          
        });
        suggestionElement.style.display = 'block';
      });
  });


  function renderTraitChips(){
    let traitDock = document.getElementById('trait-dock');
    traitDock.innerHTML = ""; 
    selectedTraits.forEach(tr => {
      let traitChip = document.createElement('span');
      traitChip.className = "uk-label uk-label-primary uk-margin-small-right uk-margin-small-bottom";
      traitChip.innerHTML = `${tr.trait_name}
        <a href='#' style='color:white;margin-left:6px' onclick='removeTrait("${tr.id}");return false;'>&times;</a>`;
      traitDock.appendChild(traitChip);
    });
  }
  
  function addTrait(trait){
    if (selectedTraits.some(t => t.id === trait.id)) return;
    selectedTraits.push(trait)
    console.log(selectedTraits)
    renderTraitChips()
  }

  function removeTrait(id){
    selectedTraits = selectedTraits.filter(t => String(t.id) !== String(id));
    console.log(selectedTraits)
    renderTraitChips()
  }

  function addFeatureRequirement(){
    var table = document.getElementById(`reqtable`);
    var tbody = table.querySelector('tbody');
    var tblRow = document.createElement('tr');

    var attrCell = document.createElement('td');
    var attrInput = document.createElement('input');
    attrInput.type = 'text';
    attrInput.className = 'uk-input';
    attrCell.appendChild(attrInput);
    tblRow.appendChild(attrCell);

    var conditionCell = document.createElement('td');
    var conditionSelect = document.createElement('select');
    conditionSelect.className = 'uk-select';
    ['==','>=','<=','!='].forEach(function(opt) {
    var option = document.createElement('option');
    option.value = opt;
    option.text = (opt === '==') ? '=' : opt;
    conditionSelect.appendChild(option);
    });
    conditionCell.appendChild(conditionSelect);
    tblRow.appendChild(conditionCell);

    var valueCell = document.createElement('td');
    var valueInput = document.createElement('input');
    valueInput.type = 'text';
    valueInput.className = 'uk-input';
    valueCell.appendChild(valueInput);
    tblRow.appendChild(valueCell);

    tbody.appendChild(tblRow)
  }

  function makeOperationCard(operation, idx) {
  const div = document.createElement('div');
  div.className = 'operation-card uk-grid-small';
  div.innerHTML += `<details ${operation._expanded ? 'open' : ''}>
  <summary>Operation #${idx+1}: ${operation.attr || '—'}<span class='subtitle'> (${operation.operation||''})</span></summary>
    <div class="uk-grid-small" uk-grid>
      <div class="uk-width-1-3">
        <label>Attribute
          <input id="operation-attribute${idx}" class="uk-input op-attribute" placeholder="Attribute" type="text" value="${operation.attr||''}">
        </label>
      </div>
      <div class="uk-width-1-3">
        <label>Operation
          <select id="operation-operation${idx}" class="uk-select op-operation">
            <option value="add" ${operation.operation==='add'?'selected':''}>Add</option>
            <option value="subtract" ${operation.operation==='subtract'?'selected':''}>Subtract</option>
            <option value="multiply" ${operation.operation==='multiply'?'selected':''}>Multiply</option>
            <option value="divide" ${operation.operation==='divide'?'selected':''}>Divide</option>
            <option value="set" ${operation.operation==='set'?'selected':''}>Set</option>
          </select>
        </label>
      </div>
      <div class="uk-width-1-3">
        <label>Value
          <input id="operation-value${idx}" class="uk-input op-value" type="text" value="${operation.value||''}">
        </label>
      </div>
    </div>
    <hr></hr>
    <div class="uk-margin-small">
      <div style="margin-top:6px;">
        <table class="uk-table" id="limits-table-op${idx}">
          <caption>Operations Limits</caption>
          <thead>
              <tr>
                  <th>Attribute</th>
                  <th>Condition</th>
                  <th>Value</th>
              </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-width-1-2" onclick=addOperationLimits(${idx})>Add Limit</button>
      </div>
      <hr></hr>
      <div style="margin-top:6px;">
        <table class="uk-table uk-table-small" id="reqs-table-op${idx}">
          <caption>Operations Requirements</caption>
          <thead>
              <tr>
                  <th>Attribute</th>
                  <th>Condition</th>
                  <th>Value</th>
              </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <button type="button" class="uk-button uk-button-default uk-width-1-2" onclick=addOperationRequirement(${idx})>Add Requirement</button>
      </div>
    </div>

    <button type="button" class="uk-button uk-button-danger uk-button-xsmall remove-op-btn"><span uk-icon="icon: close"></span> Remove Operation</button>
  </details>`;


  return div;
  }

  function addOperationLimits(idx){
  var table = document.getElementById(`limits-table-op${idx}`);
  var tbody = table.querySelector('tbody');
  var tblRow = document.createElement('tr');

  var attrCell = document.createElement('td');
  var attrInput = document.createElement('input');
  attrInput.type = 'text';
  attrInput.className = 'uk-input';
  attrCell.appendChild(attrInput);
  tblRow.appendChild(attrCell);

  var conditionCell = document.createElement('td');
  var conditionSelect = document.createElement('select');
  conditionSelect.className = 'uk-select';
  ['==','>=','<=','!='].forEach(function(opt) {
  var option = document.createElement('option');
  option.value = opt;
  option.text = (opt === '==') ? '=' : opt;
  conditionSelect.appendChild(option);
  });
  conditionCell.appendChild(conditionSelect);
  tblRow.appendChild(conditionCell);

  var valueCell = document.createElement('td');
  var valueInput = document.createElement('input');
  valueInput.type = 'text';
  valueInput.className = 'uk-input';
  valueCell.appendChild(valueInput);
  tblRow.appendChild(valueCell);

  tbody.appendChild(tblRow)
  }

  function addOperationRequirement(idx){
  var table = document.getElementById(`reqs-table-op${idx}`);
  var tbody = table.querySelector('tbody');
  var tblRow = document.createElement('tr');

  var attrCell = document.createElement('td');
  var attrInput = document.createElement('input');
  attrInput.type = 'text';
  attrInput.className = 'uk-input';
  attrCell.appendChild(attrInput);
  tblRow.appendChild(attrCell);

  var conditionCell = document.createElement('td');
  var conditionSelect = document.createElement('select');
  conditionSelect.className = 'uk-select';
  ['==','>=','<=','!='].forEach(function(opt) {
  var option = document.createElement('option');
  option.value = opt;
  option.text = (opt === '==') ? '=' : opt;
  conditionSelect.appendChild(option);
  });
  conditionCell.appendChild(conditionSelect);
  tblRow.appendChild(conditionCell);

  var valueCell = document.createElement('td');
  var valueInput = document.createElement('input');
  valueInput.type = 'text';
  valueInput.className = 'uk-input';
  valueCell.appendChild(valueInput);
  tblRow.appendChild(valueCell);

  tbody.appendChild(tblRow)
  }

  function readRequestTableRows(tableId){
  const table = document.getElementById(tableId);
  if(!table) return [];
  const rows = table.querySelectorAll('tbody tr');
  let arr = [];
  console.log(rows)
  rows.forEach(row => {
  const cells = row.querySelectorAll('td');

  if(cells.length>=3){
    const attr = cells[0].querySelector('input')?.value || "";
    const condition = cells[1].querySelector('select')?.value || "";
    const value = cells[2].querySelector('input')?.value || "";
    if(attr || condition || value){
      arr.push({attr, condition, value});
    }
  }
  })
  return arr;
  }

  function renderOperations() {
  const cont = document.getElementById('operations-list');
  cont.innerHTML = '';
  operations.forEach((op, i) => {
  cont.appendChild(makeOperationCard(op, i));
  });
  }

  document.getElementById('add-operation-btn').onclick = function() {
  operations.push({ attribute: '', operation: '', value: '', limits: [], requirements: [], _expanded:true });
  renderOperations();
  };

  document.getElementById('feature-test-form').onsubmit = function(e) {

  operations.forEach((op, idx) => {
  op.attribute = document.getElementById('operation-attribute' + idx).value;
  op.operation = document.getElementById('operation-operation' + idx).value;
  op.value = document.getElementById('operation-value' + idx).value;
  op.limits = readRequestTableRows('limits-table-op' + idx);
  op.requirements = readRequestTableRows('reqs-table-op' + idx)
  })

  let feature_requirements = readRequestTableRows('reqtable')


  let payload = {
  feature_name: document.getElementById('feature_name').value,
  feature_description: document.getElementById('feature_description').value,
  feature_requirements: feature_requirements,
  feature_data: {
    operations: operations.map(({_expanded, ...op})=>op)
  },
  feature_traits: selectedTraits
  };

  let field = document.getElementById('feature_payload');

  if (!field) {
  field = document.createElement('input');
  field.type = 'hidden';
  field.id = 'feature_payload';
  field.name = 'feature_payload';
  this.appendChild(field);
  }

  field.value = JSON.stringify(payload);

  console.log(field)

  };

</script>

<button class="uk-button uk-button-default uk-button-small uk-float-right" type="button" uk-toggle="target: #sidebar-character-attributes" style="position:fixed;top:16px;right:24px;z-index:1002">
  Show D&D Character Attributes
</button>

<div id="sidebar-character-attributes" uk-offcanvas="flip: true; overlay: true">
  <div class="uk-offcanvas-bar">
    <button class="uk-offcanvas-close" type="button" uk-close></button>
    <h3>D&D 5e Character Attributes</h3>
    <p>Use these attribute names in your features and operations:</p>
    <ul class="uk-list" style="column-count: 1;">
      <li>strength</li>
      <li>dexterity</li>
      <li>constitution</li>
      <li>intelligence</li>
      <li>wisdom</li>
      <li>charisma</li>
      <li>level</li>
      <li>hp</li>
      <li>hp_temp</li>
      <li>armor_base</li>
      <li>inspiration</li>
      <li>proficiency</li>
      <li>athletics</li>
      <li>acrobatics</li>
      <li>sleight_of_hand</li>
      <li>stealth</li>
      <li>arcana</li>
      <li>history</li>
      <li>investigation</li>
      <li>nature</li>
      <li>religion</li>
      <li>animal_handling</li>
      <li>insight</li>
      <li>medicine</li>
      <li>perception</li>
      <li>survival</li>
      <li>deception</li>
      <li>intimidation</li>
      <li>performance</li>
      <li>persuasion</li>
      <li>speed_base</li>
      <li>darkvision</li>
      <li>blindsight</li>
      <li>tremorsense</li>
      <li>truesight</li>
      <li>spell_save_dc</li>
      <li>spell_attack_bonus</li>
      <li>known_spells</li>
      <li>prepared_spells</li>
      <li>spell_slots</li>
      <li>cantrips</li>
      <li>spellcasting_ability</li>
      <li>spellcasting_class</li>
    </ul>
    <p>If you are unsure, check main/models.py <br><small>(scroll sidebar to view more)</small></p>
  </div>
</div>

<div id="toast-dock"></div>

</body>
</html>
