{% extends "base.html" %}
{% block title %}Opex Planner · CalMiner{% endblock %}

{% block content %}
  <nav class="breadcrumb">
    <a href="{{ url_for('projects.project_list_page') }}">Projects</a>
    {% if project %}
      <a href="{{ url_for('projects.view_project', project_id=project.id) }}">{{ project.name }}</a>
    {% endif %}
    {% if scenario %}
      <a href="{{ url_for('scenarios.view_scenario', scenario_id=scenario.id) }}">{{ scenario.name }}</a>
    {% endif %}
    <span aria-current="page">Opex Planner</span>
  </nav>

  <header class="page-header">
    <div>
      <h1>Opex Planner</h1>
      <p class="text-muted">Capture recurring operational costs and review annual totals with escalation assumptions.</p>
    </div>
    <div class="header-actions">
      {% if scenario_url %}
        <a class="btn btn--secondary" href="{{ scenario_url }}">Scenario Overview</a>
      {% elif project_url %}
        <a class="btn btn--secondary" href="{{ project_url }}">Project Overview</a>
      {% elif cancel_url %}
        <a class="btn btn--secondary" href="{{ cancel_url }}">Back</a>
      {% endif %}
      {% if scenario_portfolio_url %}
        <a class="btn btn--secondary" href="{{ scenario_portfolio_url }}">Scenario Portfolio</a>
      {% endif %}
      <button class="btn btn--primary" type="submit" form="opex-form">Save &amp; Calculate</button>
    </div>
  </header>

  {% if errors %}
    <div class="alert alert-error">
      <h2 class="sr-only">Submission errors</h2>
      <ul>
        {% for message in errors %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
    </div>
  {% endif %}

  {% if notices %}
    <div class="alert alert-info">
      <ul>
        {% for message in notices %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
    </div>
  {% endif %}

  <form id="opex-form" class="form scenario-form" method="post" action="{{ form_action }}">
    <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}" />
    <input type="hidden" name="options[persist]" value="{{ '1' if options and options.persist else '' }}" />

    <div class="layout-two-column stackable">
      <section class="panel">
        <header class="section-header">
          <h2>Opex Components</h2>
          <p class="section-subtitle">List recurring cost items with frequency, unit cost, and quantities.</p>
        </header>

        <div class="table-actions">
          <button class="btn btn--secondary" type="button" data-action="add-opex-component">Add Component</button>
        </div>

        {% if component_errors %}
          <div class="alert alert-error slim" role="alert" aria-live="polite">
            <h3 class="sr-only">Component issues</h3>
            <ul>
              {% for message in component_errors %}
                <li>{{ message }}</li>
              {% endfor %}
            </ul>
          </div>
        {% endif %}

        {% if component_notices %}
          <div class="alert alert-info slim" role="status" aria-live="polite">
            <ul>
              {% for message in component_notices %}
                <li>{{ message }}</li>
              {% endfor %}
            </ul>
          </div>
        {% endif %}

        <div class="table-responsive horizontal-scroll">
          <table class="input-table">
            <thead>
              <tr>
                <th scope="col">Category</th>
                <th scope="col">Component</th>
                <th scope="col">Unit Cost</th>
                <th scope="col">Quantity</th>
                <th scope="col">Frequency</th>
                <th scope="col">Currency</th>
                <th scope="col">Start Period</th>
                <th scope="col">End Period</th>
              </tr>
            </thead>
            <tbody>
              {% set component_entries = (components if components else [{}]) %}
              {% for component in component_entries %}
                <tr data-row-index="{{ loop.index0 }}">
                  <td>
                    <input type="hidden" name="components[{{ loop.index0 }}][id]" value="{{ component.id or '' }}" />
                    <select name="components[{{ loop.index0 }}][category]">
                      {% for option in category_options %}
                        <option value="{{ option.value }}" {% if component.category == option.value %}selected{% endif %}>{{ option.label }}</option>
                      {% endfor %}
                    </select>
                  </td>
                  <td>
                    <input type="text" name="components[{{ loop.index0 }}][name]" value="{{ component.name or '' }}" />
                  </td>
                  <td>
                    <input type="number" min="0" step="0.01" name="components[{{ loop.index0 }}][unit_cost]" value="{{ component.unit_cost or '' }}" />
                  </td>
                  <td>
                    <input type="number" min="0" step="0.01" name="components[{{ loop.index0 }}][quantity]" value="{{ component.quantity or '' }}" />
                  </td>
                  <td>
                    <select name="components[{{ loop.index0 }}][frequency]">
                      {% for option in frequency_options %}
                        <option value="{{ option.value }}" {% if component.frequency == option.value %}selected{% endif %}>{{ option.label }}</option>
                      {% endfor %}
                    </select>
                  </td>
                  <td>
                    <input type="text" maxlength="3" name="components[{{ loop.index0 }}][currency]" value="{{ component.currency or currency_code or (scenario.currency if scenario else '') or (project.currency if project else '') }}" />
                  </td>
                  <td>
                    <input type="number" min="1" step="1" name="components[{{ loop.index0 }}][period_start]" value="{{ component.period_start or '' }}" />
                  </td>
                  <td>
                    <input type="number" min="1" step="1" name="components[{{ loop.index0 }}][period_end]" value="{{ component.period_end or '' }}" />
                  </td>
                  <td class="row-actions">
                    <button class="btn btn--link" type="button" data-action="remove-opex-component">Remove</button>
                  </td>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>

        <p class="muted">Use start and end periods to indicate when the cost applies within the evaluation horizon.</p>
      </section>

      <aside class="panel">
        <header class="section-header">
          <h2>Global Parameters</h2>
          <p class="section-subtitle">Control escalation and discount assumptions applied to totals.</p>
        </header>

        <div class="form-grid">
          <div class="form-group">
            <label for="opex_currency_code">Default Currency</label>
            <input id="opex_currency_code" name="parameters[currency_code]" type="text" maxlength="3" value="{{ parameters.currency_code or currency_code or (scenario.currency if scenario else '') or (project.currency if project else '') }}" />
          </div>
          <div class="form-group">
            <label for="opex_escalation_pct">Escalation (%)</label>
            <input id="opex_escalation_pct" name="parameters[escalation_pct]" type="number" min="0" max="100" step="0.01" value="{{ parameters.escalation_pct if parameters.escalation_pct is not none else '' }}" />
          </div>
          <div class="form-group">
            <label for="opex_discount_rate_pct">Discount Rate (%)</label>
            <input id="opex_discount_rate_pct" name="parameters[discount_rate_pct]" type="number" min="0" max="100" step="0.01" value="{{ parameters.discount_rate_pct if parameters.discount_rate_pct is not none else (scenario.discount_rate if scenario else '') }}" />
          </div>
          <div class="form-group">
            <label for="opex_horizon_years">Evaluation Horizon (years)</label>
            <input id="opex_horizon_years" name="parameters[evaluation_horizon_years]" type="number" min="1" step="1" value="{{ parameters.evaluation_horizon_years if parameters.evaluation_horizon_years is not none else default_horizon }}" />
          </div>
          <div class="form-group checkbox">
            <label>
              <input type="checkbox" name="parameters[apply_escalation]" value="1" {% if parameters.apply_escalation %}checked{% endif %} />
              Apply escalation to timeline totals
            </label>
          </div>
        </div>

        <div class="form-group">
          <label for="snapshot_notes">Snapshot Notes</label>
          <textarea id="snapshot_notes" name="options[snapshot_notes]" rows="3">{{ options.snapshot_notes or '' }}</textarea>
          <p class="field-help">Optional. Appears alongside persisted snapshots.</p>
        </div>

        <div class="panel">
          <h3>Assumptions</h3>
          <dl class="definition-list">
            <div>
              <dt>Categories Configured</dt>
              <dd>{{ category_options | length }}</dd>
            </div>
            <div>
              <dt>Frequencies Supported</dt>
              <dd>{{ frequency_options | length }}</dd>
            </div>
            <div>
              <dt>Last Updated</dt>
              <dd>{{ last_updated_at or '—' }}</dd>
            </div>
          </dl>
          <p class="muted">Defaults reflect scenario preferences. Adjust before calculating.</p>
        </div>
      </aside>
    </div>
  </form>

  <section class="report-section">
    <header class="section-header">
      <h2>Opex Summary</h2>
      <p class="section-subtitle">Annual totals, escalation impacts, and category breakdowns.</p>
    </header>

    {% if result %}
      <div class="report-grid">
        <article class="report-card">
          <h3>Annual Opex Total</h3>
          <p class="metric">
            <strong>{{ result.totals.overall_annual | currency_display(result.currency) }}</strong>
          </p>
        </article>
        <article class="report-card">
          <h3>Escalated Total</h3>
          <p class="metric">
            <strong>
              {% if result.totals.escalated_total is not none %}
                {{ result.totals.escalated_total | currency_display(result.currency) }}
              {% else %}
                —
              {% endif %}
            </strong>
          </p>
        </article>
        <article class="report-card">
          <h3>Annual Average (Escalated)</h3>
          <p class="metric">
            <strong>
              {% if result.metrics.annual_average is not none %}
                {{ result.metrics.annual_average | currency_display(result.currency) }}
              {% else %}
                —
              {% endif %}
            </strong>
          </p>
        </article>
      </div>

      <div class="panel">
        <h3>Category Breakdown</h3>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th scope="col">Category</th>
                <th scope="col">Annual Cost</th>
                <th scope="col">Share (%)</th>
              </tr>
            </thead>
            <tbody>
              {% for entry in result.totals.by_category %}
                <tr>
                  <td>{{ entry.category | title }}</td>
                  <td>{{ entry.annual_cost | currency_display(result.currency) }}</td>
                  <td>{% if entry.share is not none %}{{ entry.share | round(2) }}{% else %}—{% endif %}</td>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>

      <div class="panel">
        <h3>Timeline</h3>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th scope="col">Period</th>
                <th scope="col">Base Cost</th>
                <th scope="col">Escalated Cost</th>
              </tr>
            </thead>
            <tbody>
              {% for entry in result.timeline %}
                <tr>
                  <td>{{ entry.period }}</td>
                  <td>{{ entry.base_cost | currency_display(result.currency) }}</td>
                  <td>
                    {% if entry.escalated_cost is not none %}
                      {{ entry.escalated_cost | currency_display(result.currency) }}
                    {% else %}
                      —
                    {% endif %}
                  </td>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    {% else %}
      <p class="muted">Run the calculation to populate summary metrics and timeline insights.</p>
    {% endif %}
  </section>
{% endblock %}
