{# Pagina Setari: sub-taburi interne — Cont (date firma + plan + parola) /
   Credentiale RAR / Cheie API. `activ_subtab` (server) alege panoul activ dupa fiecare
   swap HTMX, ca re-randarea sa nu resete la primul tab. Comutarea intre taburi
   fara server = JS delegat in base.html (#card-cont). #}
{% set _firma_ok = account_meta.name and account_meta.email and account_meta.cui %}
{% set _rar_ok = medii_disponibile and medii_disponibile|length > 0 %}
{% set _subtab = activ_subtab|default('cont') %}
{% if _subtab == 'firma' %}{% set _subtab = 'cont' %}{% endif %}
<div class="card" id="card-cont" data-activ-subtab="{{ _subtab }}">
  <h2 class="setari-title">
    <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.6 4.6l2.1 2.1M17.3 17.3l2.1 2.1M4.6 19.4l2.1-2.1M17.3 6.7l2.1-2.1"/></svg>
    Setari
  </h2>

  <div class="setari-subtabs" role="tablist" aria-label="Sectiuni setari">
    <button type="button" class="setari-subtab{{ ' is-active' if _subtab == 'cont' else '' }}" role="tab" data-subtab="cont"
            aria-selected="{{ 'true' if _subtab == 'cont' else 'false' }}">
      <span class="st-dot {{ 'ok' if _firma_ok else 'warn' }}" aria-hidden="true"></span>Cont</button>
    <button type="button" class="setari-subtab{{ ' is-active' if _subtab == 'rar' else '' }}" role="tab" data-subtab="rar"
            aria-selected="{{ 'true' if _subtab == 'rar' else 'false' }}">
      <span class="st-dot {{ 'ok' if _rar_ok else 'warn' }}" aria-hidden="true"></span>Credentiale RAR</button>
    <button type="button" class="setari-subtab{{ ' is-active' if _subtab == 'api' else '' }}" role="tab" data-subtab="api"
            aria-selected="{{ 'true' if _subtab == 'api' else 'false' }}">
      <span class="st-dot {{ 'ok' if are_cheie else 'warn' }}" aria-hidden="true"></span>Cheie API</button>
  </div>

  {# ================= Sub-tab: Cont (date firma + plan + parola) ================ #}
  <div class="setari-pane" data-subpane="cont" role="tabpanel"
       {% if _subtab != 'cont' %}hidden{% endif %}>

    {# --- Date firma --- #}
    <div class="setari-zone-title">
      <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 21V4a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v17"/><path d="M15 9h4a1 1 0 0 1 1 1v11"/><path d="M2 21h20"/><path d="M8 7h3M8 11h3M8 15h3"/></svg>
      Date firma
      <span class="setari-badge {{ 'sb-ok' if _firma_ok else 'sb-warn' }}">{{ 'complet' if _firma_ok else 'incomplet' }}</span>
    </div>

    {% if date_firma_mesaj %}<div class="flash" style="margin-bottom:12px;">{{ date_firma_mesaj }}</div>{% endif %}
    {% if date_firma_eroare %}<div class="banner" style="margin-bottom:12px; padding:8px 12px;">{{ date_firma_eroare }}</div>{% endif %}

    <form hx-post="/cont/date-firma" hx-target="#card-cont" hx-swap="outerHTML">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div class="setari-fgrid">
        <div>
          <label for="df-companie">Companie</label>
          <input id="df-companie" type="text" name="companie" required value="{{ account_meta.name or '' }}"
                 placeholder="Numele firmei (ex. Service Auto SRL)">
        </div>
        <div>
          <label for="df-cui">CUI</label>
          <input id="df-cui" type="text" name="cui" required value="{{ account_meta.cui or '' }}"
                 placeholder="RO12345678">
        </div>
        <div class="fg-full">
          <label for="df-email">Email contact</label>
          <input id="df-email" type="email" name="email" required value="{{ account_meta.email or '' }}"
                 placeholder="contact@firma.ro">
        </div>
      </div>
      <div class="setari-btn-row">
        <button type="submit">Salveaza</button>
        <span class="setari-micro">Apar pe declaratiile RAR si pe facturi.</span>
      </div>
    </form>

    {# --- Plan --- #}
    {% if plan_linie is defined %}
    <hr class="setari-subzone-sep">
    <div id="sectiune-plan" class="setari-zone-title">
      <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 3 8l9 5 9-5z"/><path d="M3 13l9 5 9-5"/></svg>
      Plan
    </div>
    {# plan_linie vine ca "Plan: <tier> · <detaliu>"; aici tier-ul apare O data, bold. #}
    {% set _plan_text = plan_linie|replace('Plan: ', '', 1) %}
    {% set _plan_parts = _plan_text.split(' · ', 1) %}
    <div class="plan-row">
      <span class="plan-tier">{{ _plan_parts[0] }}</span>
      {% if _plan_parts|length > 1 %}
      <span class="plan-usage" style="{% if plan_limita_atinsa|default(false) %}color:var(--err); font-weight:600;{% elif plan_warn|default(false) %}color:var(--warn); font-weight:600;{% endif %}">{{ _plan_parts[1] }}</span>
      {% endif %}
    </div>
    {% if monthly_limit_val|default(none) and usage_lunar is defined %}
    {% set _pct = (usage_lunar / monthly_limit_val * 100)|round|int %}
    <div class="plan-meter" role="progressbar" aria-valuenow="{{ usage_lunar }}" aria-valuemin="0"
         aria-valuemax="{{ monthly_limit_val }}" aria-label="Consum plan luna curenta">
      <span style="width:{{ [_pct, 100]|min }}%;{% if plan_limita_atinsa|default(false) %} background:var(--err);{% elif plan_warn|default(false) %} background:var(--warn);{% endif %}"></span>
    </div>
    {% endif %}
    {% if plan_limita_atinsa|default(false) %}
    <p class="setari-micro" style="color:var(--err); margin:0 0 6px;">Limita lunara atinsa — trimiterile noi sunt blocate pana luna viitoare.</p>
    {% endif %}
    <p class="setari-micro" style="margin:0;">Pentru mai mult volum sau acces API, <a href="mailto:contact@romfast.ro">contacteaza-ne</a>.</p>
    {% endif %}

    {# --- Parola de acces --- #}
    <hr class="setari-subzone-sep">
    <div class="setari-zone-title">
      <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/><circle cx="12" cy="15.5" r="1.2"/></svg>
      Parola de acces
    </div>
    <p class="setari-zone-desc">Parola dashboard-ului — separata de credentialele RAR. Minim 10 caractere.</p>

    {% if parola_mesaj %}<div class="flash" style="margin-bottom:12px;">{{ parola_mesaj }}</div>{% endif %}
    {% if parola_eroare %}<div class="banner" style="margin-bottom:12px; padding:8px 12px;">{{ parola_eroare }}</div>{% endif %}

    <form hx-post="/cont/schimba-parola" hx-target="#card-cont" hx-swap="outerHTML">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div class="setari-fgrid">
        <div class="fg-full" style="max-width:273px;">
          <label for="pw-actuala">Parola actuala</label>
          <input id="pw-actuala" type="password" name="parola_actuala" autocomplete="current-password">
        </div>
        <div>
          <label for="pw-noua">Parola noua</label>
          <input id="pw-noua" type="password" name="parola_noua" autocomplete="new-password">
        </div>
        <div>
          <label for="pw-confirma">Confirma parola noua</label>
          <input id="pw-confirma" type="password" name="parola_confirma" autocomplete="new-password">
        </div>
      </div>
      <button type="submit">Schimba parola</button>
    </form>
  </div>

  {# ========================= Sub-tab: Credentiale RAR ========================= #}
  <div class="setari-pane" data-subpane="rar" role="tabpanel"
       {% if _subtab != 'rar' %}hidden{% endif %}>
    <div class="setari-zone-title">
      <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 11l1.5-4A2 2 0 0 1 8.4 5.6h7.2A2 2 0 0 1 17.5 7L19 11"/><path d="M4 11h16v6H4z"/><path d="M6 17v2M18 17v2"/><circle cx="7.5" cy="14" r="1"/><circle cx="16.5" cy="14" r="1"/></svg>
      Credentiale RAR
      <span class="setari-badge {{ 'sb-ok' if _rar_ok else 'sb-warn' }}">{{ 'configurat' if _rar_ok else 'neconfigurat' }}</span>
    </div>
    <p class="setari-zone-desc">
      Fiecare mediu are propriile credentiale, verificate la salvare. Trimiterile merg doar pe mediile active.
    </p>

    {% if creds_mesaj %}<div class="flash" style="margin-bottom:12px;">{{ creds_mesaj }}</div>{% endif %}
    {% if creds_eroare %}<div class="banner" style="margin-bottom:12px; padding:8px 12px;">{{ creds_eroare }}</div>{% endif %}

    <form hx-post="/cont/rar-medii" hx-target="#card-cont" hx-swap="outerHTML">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">

      <div class="env-cards">
        <!-- Testare -->
        <div class="env-card{% if test_disponibil %} active-test{% endif %}">
          <h4>Testare
            {% if test_disponibil %}<span class="setari-badge sb-ok">configurat</span>{% else %}<span class="setari-badge sb-info">inactiv</span>{% endif %}
          </h4>
          <label class="env-sw">
            <input type="checkbox" name="test_enabled" value="1" {% if test_enabled %}checked{% endif %}>
            Activare Testare
          </label>
          <label class="env-lbl" for="rar-test-email">Email RAR Testare</label>
          <input id="rar-test-email" type="email" name="test_email" placeholder="email@service.ro">
          <label class="env-lbl" for="rar-test-parola">Parola RAR Testare</label>
          <input id="rar-test-parola" type="password" name="test_parola" autocomplete="new-password"
                 {% if test_disponibil %}placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull; (setata)"{% endif %}>
          {% if creds_test_mesaj %}<div class="flash" style="margin-top:6px;">{{ creds_test_mesaj }}</div>{% endif %}
          {% if creds_test_eroare %}<div class="banner" style="margin-top:6px; padding:8px 12px;">{{ creds_test_eroare }}</div>{% endif %}
        </div>

        <!-- Productie -->
        <div class="env-card{% if not prod_disponibil %} inactive{% endif %}">
          <h4>Productie
            {% if prod_disponibil %}<span class="setari-badge sb-ok">configurat</span>{% else %}<span class="setari-badge sb-warn">inactiv</span>{% endif %}
          </h4>
          <label class="env-sw">
            <input type="checkbox" name="prod_enabled" value="1" {% if prod_enabled %}checked{% endif %}>
            Activare Productie
          </label>
          <label class="env-lbl" for="rar-prod-email">Email RAR Productie</label>
          <input id="rar-prod-email" type="email" name="prod_email" placeholder="email@service.ro">
          <label class="env-lbl" for="rar-prod-parola">Parola RAR Productie</label>
          <input id="rar-prod-parola" type="password" name="prod_parola" autocomplete="new-password"
                 {% if prod_disponibil %}placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull; (setata)"{% endif %}>
          <label class="env-confirm">
            <input type="checkbox" name="prod_confirmare" value="1">
            <span>Confirm: trimiterile pe Productie sunt declaratii reale (L.142), finale si fara anulare.</span>
          </label>
          {% if creds_prod_mesaj %}<div class="flash" style="margin-top:6px;">{{ creds_prod_mesaj }}</div>{% endif %}
          {% if creds_prod_eroare %}<div class="banner" style="margin-top:6px; padding:8px 12px;">{{ creds_prod_eroare }}</div>{% endif %}
        </div>
      </div>

      <div class="default-env">
        <label for="rar-env-default" style="font-size:13px; color:var(--muted);">Mediu implicit pentru trimiteri</label>
        {% if medii_disponibile %}
        <select id="rar-env-default" name="rar_env_default">
          {% for env in medii_disponibile %}
          <option value="{{ env }}"{% if env == rar_env_default %} selected{% endif %}>{{ "Testare" if env == "test" else "Productie" }}</option>
          {% endfor %}
        </select>
        {% else %}
        <span style="font-size:13px; color:var(--muted);">Activeaza si valideaza un mediu intai.</span>
        {% endif %}
        {% if creds_default_mesaj %}<div class="flash" style="margin-top:6px; flex-basis:100%;">{{ creds_default_mesaj }}</div>{% endif %}
        {% if creds_default_eroare %}<div class="banner" style="margin-top:6px; padding:8px 12px; flex-basis:100%;">{{ creds_default_eroare }}</div>{% endif %}
      </div>

      <div class="setari-btn-row">
        <button type="submit">Salveaza</button>
        <span class="setari-micro">Parolele se stocheaza criptat.</span>
      </div>
    </form>
  </div>

  {# ============================ Sub-tab: Cheie API ============================ #}
  <div class="setari-pane" data-subpane="api" role="tabpanel"
       {% if _subtab != 'api' %}hidden{% endif %}>
    <div class="setari-zone-title">
      <svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="15" r="4"/><path d="M11 12l9-9"/><path d="M17 6l2.5 2.5M14 9l2.5 2.5"/></svg>
      Cheie API
      <span class="setari-badge {{ 'sb-ok' if are_cheie else 'sb-warn' }}">{{ 'activa' if are_cheie else 'lipsa' }}</span>
    </div>
    <p class="setari-zone-desc">
      Pentru trimiteri din softul propriu / ROAAUTO. Se afiseaza integral o singura data.
    </p>

    {% if api_key %}
      <div class="flash" style="margin-bottom:12px;">Cheia a fost rotita. Salveaz-o acum — nu o vei mai putea vedea.</div>
      <div class="keybox">{{ api_key }}</div>
      <button type="button" class="btn-secondary" style="margin-top:8px;"
              data-key="{{ api_key }}"
              onclick="navigator.clipboard.writeText(this.dataset.key).then(()=>this.textContent='Copiat!')">
        Copiaza cheia
      </button>
    {% endif %}

    {% if rot_eroare %}<div class="banner" style="margin:12px 0; padding:8px 12px;">{{ rot_eroare }}</div>{% endif %}

    <form hx-post="/cont/roteste-cheie" hx-target="#card-cont" hx-swap="outerHTML"
          style="margin-top:{% if api_key %}14px{% else %}0{% endif %};">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div class="setari-btn-row">
        <button type="submit" class="btn-warn">{{ 'Roteste cheia API' if are_cheie else 'Genereaza cheia API' }}</button>
        <span class="setari-micro">Rotirea revoca imediat cheia veche.</span>
      </div>
    </form>
  </div>
</div>
