{% from "components/_tabs.html" import tabs_intro %}
<header class="page-heading">
  <p class="eyebrow">ORGANIZACIÓN IMPERIAL</p>
  <h1>Planificación, avisos y calendario</h1>
  <p>Prepara hasta diez órdenes sin gastar recursos, consulta cuándo podrán ejecutarse y reúne todos los vencimientos en una agenda textual.</p>
</header>
<div data-tab-scope="planning">
{{ tabs_intro('planning', 'Apartados de planificación', 'Organiza por separado las órdenes previstas, los avisos y el calendario, conservando todos los controles.') }}

<section class="panel" aria-labelledby="plan-title" data-tab-panel data-tab-id="planificacion-ordenes" data-tab-label="Órdenes previstas">
  <p class="eyebrow">PLAN DE PRODUCCIÓN</p>
  <h2 id="plan-title">Órdenes previstas</h2>
  <p>Añadir una orden no la ejecuta. La autorización al gobernador permite iniciarla automáticamente solo cuando llegue a la primera posición, cumpla requisitos, tenga recursos y no exista otra cola incompatible.</p>
  <form method="post" action="{{ url_for('plan_add_action') }}" class="stacked-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <label>Planeta
      <select name="planet_id">{% for own_planet in planets %}<option value="{{ own_planet.id }}">{{ own_planet.alias or own_planet.name }} [{{ own_planet.galaxy }}:{{ own_planet.system }}:{{ own_planet.position }}]</option>{% endfor %}</select>
    </label>
    <label>Tipo de orden
      <select name="order_type" data-plan-type>
        {% for key, label in PLAN_TYPES.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}
      </select>
    </label>
    <label>Elemento
      <select name="item" data-plan-item>
        <optgroup label="Edificios" data-plan-group="building">{% for key, definition in BUILDINGS.items() %}<option value="{{ key }}">{{ definition.name }}</option>{% endfor %}</optgroup>
        <optgroup label="Investigaciones" data-plan-group="research">{% for key, definition in TECHNOLOGIES.items() %}<option value="{{ key }}">{{ definition.name }}</option>{% endfor %}</optgroup>
        <optgroup label="Naves" data-plan-group="ship">{% for key, definition in SHIPS.items() %}<option value="{{ key }}">{{ definition.name }}</option>{% endfor %}</optgroup>
        <optgroup label="Defensas" data-plan-group="defense">{% for key, definition in DEFENSES.items() %}<option value="{{ key }}">{{ definition.name }}</option>{% endfor %}</optgroup>
      </select>
    </label>
    <label>Cantidad para naves o defensas
      <input name="amount" type="number" min="1" max="100000" value="1">
    </label>
    <label class="check-row"><input type="checkbox" name="governor_allowed" value="1"> Autorizar ejecución automática por el gobernador</label>
    <button class="button button-primary" type="submit">Añadir al plan</button>
  </form>

  {% if plan_orders %}
  <div class="table-wrap">
    <table>
      <caption>{{ plan_orders|length }} de 10 órdenes previstas, en orden de prioridad.</caption>
      <thead><tr><th scope="col">Posición y orden</th><th scope="col">Coste</th><th scope="col">Estado calculado</th><th scope="col">Tiempo previsto</th><th scope="col">Automatización</th><th scope="col">Acciones</th></tr></thead>
      <tbody>
      {% for item in plan_orders %}
        <tr>
          <th scope="row">{{ item.row.position }}. {{ item.definition.name }}{% if item.row.order_type in ['ship','defense'] %} × {{ item.row.amount }}{% else %} nivel {{ item.target }}{% endif %}<br><small>{{ item.row.planet_name }} · {{ PLAN_TYPES[item.row.order_type] }}</small></th>
          <td>{{ item.cost.metal|number }} metal; {{ item.cost.crystal|number }} cristal; {{ item.cost.deuterium|number }} deuterio<br><small>Acumulado: {{ item.cumulative_cost.metal|number }} metal; {{ item.cumulative_cost.crystal|number }} cristal; {{ item.cumulative_cost.deuterium|number }} deuterio.</small></td>
          <td>{{ item.state }}</td>
          <td>Duración aproximada: {{ item.estimated_duration|duration }}.{% if item.estimated_completion_at %}<br>Si sigues el plan desde ahora: <time datetime="{{ item.estimated_completion_at|date_iso }}">{{ item.estimated_completion_at|date_label }}</time>.{% else %}<br>Sin fecha hasta resolver la pausa o el requisito.{% endif %}</td>
          <td>{{ 'Autorizada' if item.row.governor_allowed else 'Manual' }}</td>
          <td>
            <form method="post" action="{{ url_for('plan_move_action') }}" class="button-row">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="order_id" value="{{ item.row.id }}">
              <button class="button" name="direction" value="up" type="submit" {% if loop.first %}disabled{% endif %}>Subir</button>
              <button class="button" name="direction" value="down" type="submit" {% if loop.last %}disabled{% endif %}>Bajar</button>
            </form>
            <form method="post" action="{{ url_for('plan_update_action') }}" class="button-row">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="order_id" value="{{ item.row.id }}">
              <button class="button" name="plan_action" value="pause" type="submit">{{ 'Reanudar' if item.row.status == 'paused' else 'Pausar' }}</button>
              <button class="button" name="plan_action" value="governor" type="submit">{{ 'Revocar gobernador' if item.row.governor_allowed else 'Autorizar gobernador' }}</button>
              <button class="button button-danger" name="plan_action" value="remove" type="submit">Retirar del plan</button>
            </form>
            <form method="post" action="{{ url_for('plan_execute_action') }}">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="order_id" value="{{ item.row.id }}">
              <button class="button button-primary" type="submit" {% if not item.ready or item.row.status == 'paused' %}disabled{% endif %}>Iniciar ahora</button>
            </form>
          </td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
  </div>
  {% else %}<p class="empty-state">El plan está vacío.</p>{% endif %}
</section>

<section class="panel panel-wide" aria-labelledby="forecast-title" data-tab-panel data-tab-id="planificacion-prevision" data-tab-label="Previsión acumulada">
  <p class="eyebrow">COLAS Y PLAN IMPERIAL</p>
  <h2 id="forecast-title">Previsión acumulada</h2>
  <p>{{ queue_forecast.notice }}</p>
  <p><a class="button" href="{{ url_for('queue_forecast_export_action', format_name='csv') }}">Descargar CSV</a> <a class="button" href="{{ url_for('queue_forecast_export_action', format_name='json') }}">Descargar JSON</a></p>
  <dl class="definition-list">
    <div><dt>Colas activas</dt><dd>{{ queue_forecast.active|length }}</dd></div>
    <div><dt>Órdenes previstas</dt><dd>{{ queue_forecast.planned|length }}</dd></div>
    <div><dt>Órdenes sin fecha fiable</dt><dd>{{ queue_forecast.blocked }}</dd></div>
    <div><dt>Final estimado</dt><dd>{% if queue_forecast.estimated_finish_at %}<time datetime="{{ queue_forecast.estimated_finish_at|date_iso }}">{{ queue_forecast.estimated_finish_at|date_label }}</time>{% else %}Sin trabajos{% endif %}</dd></div>
  </dl>
  {% set forecast_items = queue_forecast.active + queue_forecast.planned %}
  {% if forecast_items %}
  <div class="table-wrap">
    <table>
      <caption>Colas pagadas y órdenes no reservadas, diferenciadas explícitamente.</caption>
      <thead><tr><th scope="col">Estado</th><th scope="col">Orden</th><th scope="col">Planeta</th><th scope="col">Coste</th><th scope="col">Final</th><th scope="col">Fiabilidad</th></tr></thead>
      <tbody>
        {% for item in forecast_items %}
        <tr>
          <th scope="row">{{ 'Activa y pagada' if item.kind == 'active' else 'Prevista sin reserva' }}</th>
          <td>{{ item.name }} · {{ item.category }}</td>
          <td>{{ item.planet }}</td>
          <td>{{ item.cost.metal|default(0)|number }} metal; {{ item.cost.crystal|default(0)|number }} cristal; {{ item.cost.deuterium|default(0)|number }} deuterio</td>
          <td>{% if item.completes_at %}<time datetime="{{ item.completes_at|date_iso }}">{{ item.completes_at|date_label }}</time>{% else %}Sin fecha{% endif %}</td>
          <td>{{ item.uncertainty }}{% if item.state %}<br><small>{{ item.state }}</small>{% endif %}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% else %}<p class="empty-state">No hay colas ni órdenes previstas.</p>{% endif %}
</section>

<section class="panel panel-wide" aria-labelledby="consumables-title" data-tab-panel data-tab-id="planificacion-directivas" data-tab-label="Directivas consumibles">
  <p class="eyebrow">RECOMPENSAS SIN MONETIZACIÓN</p>
  <h2 id="consumables-title">Directivas estratégicas consumibles</h2>
  <p>Se obtienen jugando, mediante expediciones, logros y temporadas. Humano e IA usan el mismo inventario, límites y efectos. Cada uso exige una vista previa y confirmación.</p>
  {% if consumable_preview %}
  <section id="consumable-confirmation" class="notice notice-warning" aria-labelledby="consumable-confirmation-title" tabindex="-1">
    <h3 id="consumable-confirmation-title">Confirmar {{ consumable_preview.amount }} × {{ consumable_preview.item_name }}</h3>
    <p><strong>Efecto exacto:</strong> {{ consumable_preview.effect }}</p>
    <p>{{ consumable_preview.warning }}</p>
    <form method="post" action="{{ url_for('consumable_apply_action') }}" class="stacked-form">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <label class="check-row"><input type="checkbox" name="confirm" value="1" required> Confirmo el consumible, la cantidad, el objetivo y el efecto descrito</label>
      <button class="button button-primary" type="submit">Aplicar directiva confirmada</button>
    </form>
  </section>
  {% endif %}
  <div class="card-grid">
    {% for consumable in strategic_consumables %}
    <article class="entity-card">
      <h3>{{ consumable.name }}</h3>
      <p>{{ consumable.description }}</p>
      <p><strong>Disponibles:</strong> {{ consumable.amount }}. Máximo por lote: {{ consumable.max_batch }}.</p>
      {% set targets = consumable_targets.get(consumable.target_type,[]) %}
      <form method="post" action="{{ url_for('consumable_preview_action') }}" class="stacked-form">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="item_key" value="{{ consumable.key }}">
        <label>Cantidad de {{ consumable.name }}<input name="amount" type="number" min="1" max="{{ [consumable.amount,consumable.max_batch]|min }}" value="1" {% if not consumable.amount %}disabled{% endif %}></label>
        <label>Objetivo
          <select name="target_id" {% if not targets %}disabled{% endif %}>{% for target in targets %}<option value="{{ target.id }}">{{ target.label }}</option>{% endfor %}</select>
        </label>
        <button class="button" type="submit" {% if not consumable.amount or not targets %}disabled{% endif %}>Calcular efecto antes de usar</button>
      </form>
    </article>
    {% endfor %}
  </div>
  {% if recent_consumable_uses %}
  <h3>Historial de usos</h3>
  <ol>{% for use in recent_consumable_uses %}<li>{{ use.amount }} × {{ use.item_key }}: {{ use.summary }} — {{ 'deshecho' if use.undone else 'aplicado' }}.{% if loop.first and not use.undone and session.get('consumable_undo_window') %}<form method="post" action="{{ url_for('consumable_undo_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="use_id" value="{{ use.id }}"><button class="button button-danger" type="submit">Deshacer antes del siguiente ciclo</button></form>{% endif %}</li>{% endfor %}</ol>
  {% endif %}
</section>

<section class="panel" aria-labelledby="notifications-title" data-tab-panel data-tab-id="planificacion-avisos" data-tab-label="Avisos">
  <p class="eyebrow">CENTRO DE AVISOS</p>
  <h2 id="notifications-title">Preferencias y privacidad</h2>
  <form method="post" action="{{ url_for('notification_preferences_action') }}" class="stacked-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <label class="check-row"><input type="checkbox" name="enabled" value="1" {% if notification_preferences.enabled %}checked{% endif %}> Activar el centro de avisos</label>
    <label class="check-row"><input type="checkbox" name="os_notifications" value="1" {% if notification_preferences.os_notifications %}checked{% endif %}> Permitir avisos del navegador y Windows</label>
    <label>Antelación
      <select name="advance_minutes"><option value="0" {% if notification_preferences.advance_minutes == 0 %}selected{% endif %}>Al ocurrir</option><option value="5" {% if notification_preferences.advance_minutes == 5 %}selected{% endif %}>5 minutos antes</option><option value="30" {% if notification_preferences.advance_minutes == 30 %}selected{% endif %}>30 minutos antes</option></select>
    </label>
    <label class="check-row"><input type="checkbox" name="privacy_mode" value="1" {% if notification_preferences.privacy_mode %}checked{% endif %}> Ocultar detalles sensibles fuera del juego</label>
    <label class="check-row"><input type="checkbox" name="group_mode" value="1" {% if notification_preferences.group_mode %}checked{% endif %}> Agrupar avisos relacionados</label>
    <fieldset><legend>Categorías permitidas</legend>
      <div class="form-grid">{% for key, label in NOTIFICATION_CATEGORIES.items() %}<label class="check-row"><input type="checkbox" name="categories" value="{{ key }}" {% if key in notification_categories_enabled %}checked{% endif %}> {{ label }}</label>{% endfor %}</div>
    </fieldset>
    <button class="button button-primary" type="submit">Guardar preferencias</button>
  </form>
  <button class="button" type="button" data-request-notifications>Solicitar permiso del navegador para avisos externos</button>
  <p>Los avisos externos solo se solicitan después de activarlos aquí y conceder permiso al navegador. El juego continúa siendo completamente utilizable sin ellos.</p>
  {% if notifications %}
    <form method="post" action="{{ url_for('notification_read_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="button" type="submit">Marcar todos como leídos</button></form>
    <ol class="message-list">{% for notice in notifications %}<li><article><header><span class="report-category">{{ NOTIFICATION_CATEGORIES.get(notice.category,notice.category) }} · {{ 'Pendiente' if not notice.is_read else 'Leído' }}</span><h3>{{ notice.title }}</h3><time datetime="{{ notice.event_at|date_iso }}">{{ notice.event_at|date_label }}</time></header><p>{{ notice.body }}</p></article></li>{% endfor %}</ol>
  {% else %}<p class="empty-state">Todavía no hay avisos registrados.</p>{% endif %}
</section>

<section class="panel" aria-labelledby="calendar-title" data-tab-panel data-tab-id="planificacion-calendario" data-tab-label="Calendario">
  <p class="eyebrow">AGENDA UNIFICADA</p>
  <h2 id="calendar-title">Calendario estratégico</h2>
  <p><a class="button" href="{{ url_for('calendar_export_action') }}">Descargar calendario ICS</a></p>
  <form method="get" action="{{ url_for('game_view', section='planning') }}" class="inline-form" aria-label="Filtrar calendario">
    <label>Planeta<select name="calendar_planet"><option value="">Todos</option>{% for own_planet in planets %}<option value="{{ own_planet.id }}" {% if calendar_filters.planet == own_planet.id %}selected{% endif %}>{{ own_planet.alias or own_planet.name }}</option>{% endfor %}</select></label>
    <label>Tipo<select name="calendar_category"><option value="">Todos</option>{% for category in calendar_categories %}<option value="{{ category }}" {% if calendar_filters.category == category %}selected{% endif %}>{{ category }}</option>{% endfor %}</select></label>
    <button class="button" type="submit">Aplicar filtros</button>
  </form>
  <form method="post" action="{{ url_for('reminder_add_action') }}" class="stacked-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <label>Título<input name="title" maxlength="100" required></label>
    <label>Fecha y hora<input name="remind_at" type="datetime-local" required></label>
    <label>Categoría<input name="category" maxlength="30" value="personal"></label>
    <label>Planeta opcional<select name="planet_id"><option value="">Sin planeta</option>{% for own_planet in planets %}<option value="{{ own_planet.id }}">{{ own_planet.alias or own_planet.name }}</option>{% endfor %}</select></label>
    <label>Nota<textarea name="note" maxlength="500" rows="3"></textarea></label>
    <button class="button button-primary" type="submit">Crear recordatorio</button>
  </form>
  {% if calendar_entries %}<div class="table-wrap"><table><caption>Agenda ordenada cronológicamente.</caption><thead><tr><th scope="col">Fecha</th><th scope="col">Categoría</th><th scope="col">Acontecimiento</th><th scope="col">Planeta</th><th scope="col">Acción</th></tr></thead><tbody>{% for entry in calendar_entries %}<tr><th scope="row"><time datetime="{{ entry.at|date_iso }}">{{ entry.at|date_label }}</time></th><td>{{ entry.category }}</td><td>{{ entry.title }}{% if entry.note %}<br><small>{{ entry.note }}</small>{% endif %}</td><td>{{ entry.planet or '—' }}</td><td>{% if entry.reminder_id %}<form method="post" action="{{ url_for('reminder_complete_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="reminder_id" value="{{ entry.reminder_id }}"><button class="button" type="submit">Completar</button></form>{% else %}Automático{% endif %}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="empty-state">No hay acontecimientos próximos.</p>{% endif %}
</section>
</div>
