{% extends "base.html" %}
{% block title %}Add Device — Battery Tracker{% endblock %}

{% block content %}
<h1>Add Device</h1>

<div class="card">
  <form method="post" action="{{ url_for('device_add') }}">
    <div class="form-group">
      <label for="name">Device Name <span class="text-danger">*</span></label>
      <input type="text" id="name" name="name" value="{{ form_name|default('') }}"
             placeholder="e.g. Game Controller" required>
    </div>

    <div class="form-group">
      <label for="battery_slots">Battery Slots <span class="text-danger">*</span></label>
      <input type="number" id="battery_slots" name="battery_slots"
             value="{{ form_slots|default(1) }}" min="1" required>
    </div>

    <div class="form-group">
      <label>Type</label>
      {% set _preset_types = ['Remote Control','Game Controller','Flashlight','Lock','Sensor','Toy','Clock','Smoke Detector'] %}
      {% set _cur_type = form_device_type|default('') %}
      <select id="device-type-select" onchange="metaSelectChanged(this,'device_type')">
        <option value="">— none —</option>
        {% for opt in _preset_types %}
        <option value="{{ opt }}" {% if _cur_type == opt %}selected{% endif %}>{{ opt }}</option>
        {% endfor %}
        {% for opt in device_types|default([]) %}
          {% if opt not in _preset_types %}
        <option value="{{ opt }}" {% if _cur_type == opt %}selected{% endif %}>{{ opt }}</option>
          {% endif %}
        {% endfor %}
        <option value="__new__" {% if _cur_type and _cur_type not in _preset_types and _cur_type not in device_types|default([]) %}selected{% endif %}>Other…</option>
      </select>
      <input type="text" id="device_type" name="device_type" value="{{ _cur_type }}"
             placeholder="Enter device type"
             style="display:{% if _cur_type and _cur_type not in _preset_types %}''{% else %}none{% endif %};margin-top:0.4rem;">
    </div>

    <div class="form-group">
      <label for="notes">Notes</label>
      <textarea id="notes" name="notes" placeholder="Optional notes…">{{ form_notes|default('') }}</textarea>
    </div>

    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Add Device</button>
      <a class="btn btn-secondary" href="{{ url_for('device_list') }}">Cancel</a>
    </div>
  </form>
</div>

<script>
function metaSelectChanged(sel, inputId) {
  var input = document.getElementById(inputId);
  if (sel.value === '__new__') {
    input.style.display = '';
    input.value = '';
    input.focus();
  } else {
    input.style.display = 'none';
    input.value = sel.value;
  }
}
</script>
{% endblock %}
