{% from 'partials/_macros.html' import color_identity %}
{% set pname = commander.name %}
{% set partner_preview_payload = partner_preview if partner_preview else None %}
{% set preview_colors = partner_preview_payload.color_identity if partner_preview_payload else [] %}
{% if preview_colors is none %}
  {% set preview_colors = [] %}
{% endif %}
{% set preview_label = partner_preview_payload.color_label if partner_preview_payload else '' %}
{% if not preview_label and preview_colors %}
  {% set preview_label = preview_colors|join(' / ') %}
{% endif %}
{% if not preview_label and partner_preview_payload and (preview_colors|length == 0) %}
  {% set preview_label = 'Colorless (C)' %}
{% endif %}
<div id="newdeck-commander-slot" hx-swap-oob="true" style="max-width:230px;">
  <aside class="card-preview" data-card-name="{{ pname }}" style="max-width: 230px;">
    <a href="https://scryfall.com/search?q={{ pname|urlencode }}" target="_blank" rel="noopener">
      <img src="https://api.scryfall.com/cards/named?fuzzy={{ pname|urlencode }}&format=image&version=normal" alt="{{ pname }} card image" data-card-name="{{ pname }}" style="width:200px; height:auto; display:block; border-radius:6px;" />
    </a>
  </aside>
  <div class="muted" style="font-size:12px; margin-top:.25rem; max-width: 230px;">{{ pname }}</div>
  {% if partner_preview_payload %}
  {% set partner_secondary_name = partner_preview_payload.secondary_name %}
  {% set partner_image_url = partner_preview_payload.secondary_image_url or partner_preview_payload.image_url %}
  {% if not partner_image_url and partner_secondary_name %}
    {% set partner_image_url = 'https://api.scryfall.com/cards/named?fuzzy=' ~ partner_secondary_name|urlencode ~ '&format=image&version=normal' %}
  {% endif %}
  {% set partner_href = partner_preview_payload.secondary_scryfall_url or partner_preview_payload.scryfall_url %}
  {% if not partner_href and partner_secondary_name %}
    {% set partner_href = 'https://scryfall.com/search?q=' ~ partner_secondary_name|urlencode %}
  {% endif %}
  {% if partner_image_url %}
  <aside class="card-preview partner-card-preview" style="max-width: 230px; margin-top:.75rem;">
    {% if partner_href %}<a href="{{ partner_href }}" target="_blank" rel="noopener">{% endif %}
    <img src="{{ partner_image_url }}" alt="{{ (partner_secondary_name or 'Selected card') ~ ' card image' }}" data-card-name="{{ partner_secondary_name or '' }}" style="width:200px; height:auto; display:block; border-radius:6px;" loading="lazy" decoding="async" />
    {% if partner_href %}</a>{% endif %}
  </aside>
  {% endif %}
  {% if partner_secondary_name %}
  <div class="muted" style="font-size:12px; margin-top:.25rem; max-width: 230px;">
    {% if partner_preview_payload.secondary_role_label %}<strong>{{ partner_preview_payload.secondary_role_label }}</strong>: {% endif %}{{ partner_secondary_name }}
  </div>
  {% endif %}
  <div class="muted" style="font-size:12px; margin-top:.35rem; display:flex; align-items:center; gap:.35rem; flex-wrap:wrap;">
    {{ color_identity(preview_colors, is_colorless=(preview_colors|length == 0), aria_label=preview_label or '', title_text=preview_label or '') }}
    <span>{{ preview_label }}</span>
  </div>
  {% if partner_preview_payload.theme_tags %}
  <div class="muted" style="font-size:12px; margin-top:.25rem;">
    Combined themes: {{ partner_preview_payload.theme_tags|join(', ') }}
  </div>
  {% endif %}
  {% endif %}
  <script>
    try {
      var nm = document.querySelector('input[name="name"]');
      var value = document.querySelector('#newdeck-commander-slot [data-card-name]')?.getAttribute('data-card-name') || '{{ pname|e }}';
      if (nm && (!nm.value || !nm.value.trim())) { nm.value = value; }
    } catch(_) {}
  </script>
</div>

{% set exclusion = commander.exclusion if commander is defined and commander.exclusion is defined else None %}
{% if exclusion %}
  {% set eligible_raw = exclusion.eligible_faces if exclusion.eligible_faces is defined else [] %}
  {% set eligible_list = eligible_raw if eligible_raw is iterable else [] %}
  {% set eligible_lower = eligible_list | map('lower') | list %}
  {% set current_lower = commander.name|lower %}
  {% if eligible_list and (current_lower not in eligible_lower or exclusion.reason == 'secondary_face_only') %}
    <div class="muted" style="font-size:12px; margin-top:.35rem; color:#facc15;" role="note">
      {% if eligible_list|length == 1 %}
        ⚠ This commander only works from '{{ eligible_list[0] }}'.
        {% if exclusion.primary_face and exclusion.primary_face|lower != eligible_list[0]|lower %}
          Front face '{{ exclusion.primary_face }}' can't lead a deck.
        {% endif %}
        We'll build using the supported face automatically.
      {% else %}
        ⚠ This commander only works from these faces: {{ eligible_list | join(', ') }}. We'll build using the supported faces automatically.
      {% endif %}
    </div>
  {% endif %}
{% endif %}

<div>
  {% if tags and tags|length %}
  <div class="muted" style="font-size:12px; margin-bottom:.35rem;">Pick up to three themes. Toggle AND/OR to control how themes combine.</div>
  <div style="display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; margin-bottom:.35rem;">
    <span class="muted" style="font-size:12px;">Combine</span>
    <div role="group" aria-label="Combine mode">
      <label style="margin-right:.35rem;" title="AND prioritizes cards that match multiple of your themes (tighter synergy, smaller pool).">
        <input type="radio" name="combine_mode_radio" value="AND" checked /> AND
      </label>
      <label title="OR treats your themes as a union (broader pool, fills easier).">
        <input type="radio" name="combine_mode_radio" value="OR" /> OR
      </label>
    </div>
    <button type="button" id="modal-reset-tags" class="chip" style="margin-left:.35rem;">Reset themes</button>
    <span id="modal-tag-count" class="muted" style="font-size:12px;"></span>
  </div>
  <div id="modal-tag-reco-block" data-has-reco="{% if recommended and recommended|length %}1{% else %}0{% endif %}" {% if not (recommended and recommended|length) %}style="display:none;"{% endif %}>
    <div class="muted" style="font-size:12px; margin:.25rem 0 .35rem 0;">Recommended</div>
    <div id="modal-tag-reco" aria-label="Recommended themes" data-original-tags='{{ (recommended or []) | tojson }}' style="display:flex; gap:.35rem; flex-wrap:wrap; margin-bottom:.5rem;">
      {% if recommended and recommended|length %}
        {% for r in recommended %}
          {% set tip = (recommended_reasons[r] if (recommended_reasons is defined and recommended_reasons and recommended_reasons.get(r)) else 'Recommended for this commander') %}
          <button type="button" class="chip chip-reco" data-tag="{{ r }}" title="{{ tip }}">★ {{ r }}</button>
        {% endfor %}
      {% endif %}
      <button type="button" id="modal-reco-select-all" class="chip" title="Add recommended up to 3" {% if not (recommended and recommended|length) %}style="display:none;"{% endif %}>Select all</button>
    </div>
  </div>
  <div id="modal-tag-list" aria-label="Available themes" style="display:flex; gap:.35rem; flex-wrap:wrap;">
    {% for t in tags %}
      <button type="button" class="chip" data-tag="{{ t }}">{{ t }}</button>
    {% endfor %}
  </div>
  {% else %}
    <p class="muted">No theme tags available for this commander.</p>
  {% endif %}
  <!-- hidden inputs that the main modal form will submit -->
  <input type="hidden" name="primary_tag" id="modal_primary_tag" />
  <input type="hidden" name="secondary_tag" id="modal_secondary_tag" />
  <input type="hidden" name="tertiary_tag" id="modal_tertiary_tag" />
  <input type="hidden" name="tag_mode" id="modal_tag_mode" value="AND" />

  <div id="modal-selected-themes" class="muted" style="font-size:12px; margin-top:.5rem;">
    <em>No themes selected yet.</em>
  </div>
</div>

{% set partner_id_prefix = 'modal' %}
{% set partner_scope = 'modal' %}
{% include "build/_partner_controls.html" %}

{# Always update the bracket dropdown on commander change; hide 1–2 only when gc_commander is true #}
<div id="newdeck-bracket-slot" hx-swap-oob="true">
  <label>Bracket
    <select name="bracket">
      {% for b in brackets %}
        {% if not gc_commander or b.level >= 3 %}
        <option value="{{ b.level }}" {% if b.level == 3 %}selected{% endif %}>Bracket {{ b.level }}: {{ b.name }}</option>
        {% endif %}
      {% endfor %}
    </select>
  </label>
  {% if gc_commander %}
    <div class="muted" style="font-size:12px; margin-top:.25rem;">Commander is a Game Changer; brackets 1–2 are unavailable.</div>
  {% endif %}
</div>

<script>
(function(){
  var list = document.getElementById('modal-tag-list');
  var recoBlock = document.getElementById('modal-tag-reco-block');
  var reco = document.getElementById('modal-tag-reco');
  var selAll = document.getElementById('modal-reco-select-all');
  var resetBtn = document.getElementById('modal-reset-tags');
  var p = document.getElementById('modal_primary_tag');
  var s = document.getElementById('modal_secondary_tag');
  var t = document.getElementById('modal_tertiary_tag');
  var mode = document.getElementById('modal_tag_mode');
  var countEl = document.getElementById('modal-tag-count');
  var selSummary = document.getElementById('modal-selected-themes');
  if (!list) return;
  var previewScope = 'modal';
  function readPartnerPreviewTags(){
    if (typeof window === 'undefined') return [];
    var store = window.partnerPreviewState;
    if (!store) return [];
    var state = store[previewScope];
    if (!state) return [];
    if (Array.isArray(state.theme_tags) && state.theme_tags.length){ return state.theme_tags.slice(); }
    var payload = state.payload;
    if (payload && Array.isArray(payload.theme_tags)){ return payload.theme_tags.slice(); }
    return [];
  }

  function getSel(){ var a=[]; if(p&&p.value)a.push(p.value); if(s&&s.value)a.push(s.value); if(t&&t.value)a.push(t.value); return a; }
  function setSel(a){ a = Array.from(new Set(a||[])).filter(Boolean).slice(0,3); if(p) p.value=a[0]||''; if(s) s.value=a[1]||''; if(t) t.value=a[2]||''; updateUI(); }
  function toggle(tag){ var cur=getSel(); var i=cur.indexOf(tag); if(i>=0){cur.splice(i,1);} else { if(cur.length>=3){cur=cur.slice(1);} cur.push(tag);} setSel(cur); }
  function updateUI(){
    try{ if(countEl) countEl.textContent = getSel().length + ' / 3 selected'; }catch(_){ }
    try{
      if(selSummary){
        var sel = getSel();
        if(!sel.length){ selSummary.innerHTML = '<em>No themes selected yet.</em>'; }
        else {
          var parts = [];
          sel.forEach(function(tag, idx){ parts.push((idx+1) + '. ' + tag); });
          selSummary.textContent = 'Selected: ' + parts.join('  ·  ');
        }
      }
    }catch(_){ }
    function apply(container){ if(!container) return; var chips = container.querySelectorAll('button.chip'); chips.forEach(function(btn){ var tag=btn.dataset.tag||''; var active=getSel().indexOf(tag)>=0; btn.classList.toggle('active', active); btn.setAttribute('aria-pressed', active?'true':'false'); }); }
    apply(list); apply(reco);
  // Notify parent modal so it can refresh multi-copy suggestions
  try{ document.dispatchEvent(new CustomEvent('newdeck:tagsChanged')); }catch(_){ }
  }
  if (resetBtn) resetBtn.addEventListener('click', function(){ setSel([]); });
  list.addEventListener('click', function(e){
    var btn = e.target.closest('button.chip');
    if (!btn || !list.contains(btn)) return;
    var tag = btn.dataset.tag || '';
    if (tag){ toggle(tag); }
  });
  if (reco){
    reco.addEventListener('click', function(e){
      var btn = e.target.closest('button');
      if (!btn || !reco.contains(btn)) return;
      if (btn.id === 'modal-reco-select-all'){
        try {
          var cur = getSel();
          var recs = Array.from(reco.querySelectorAll('button.chip-reco')).map(function(b){ return b.dataset.tag || ''; }).filter(Boolean);
          var combined = cur.slice();
          recs.forEach(function(x){ if (combined.indexOf(x) === -1) combined.push(x); });
          setSel(combined.slice(-3));
        } catch(_){ }
        return;
      }
      if (btn.classList.contains('chip-reco')){
        var tag = btn.dataset.tag || '';
        if (tag){ toggle(tag); }
      }
    });
  }
  document.querySelectorAll('input[name="combine_mode_radio"]').forEach(function(r){ r.addEventListener('change', function(){ if(mode){ mode.value = r.value; } }); });
  function updatePartnerRecommendations(tags){
    if (!reco) return;
    Array.from(reco.querySelectorAll('button.partner-suggestion')).forEach(function(btn){ btn.remove(); });
    var unique = [];
    var seen = new Set();
    (Array.isArray(tags) ? tags : []).forEach(function(tag){
      var value = String(tag || '').trim();
      if (!value) return;
      var key = value.toLowerCase();
      if (seen.has(key)) return;
      seen.add(key);
      unique.push(value);
    });
    var insertBefore = selAll && selAll.parentElement === reco ? selAll : null;
    unique.forEach(function(tag){
      var btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'chip chip-reco partner-suggestion';
      btn.dataset.tag = tag;
      btn.title = 'Synergizes with selected partner pairing';
      btn.textContent = '★ ' + tag;
      if (insertBefore){ reco.insertBefore(btn, insertBefore); }
      else { reco.appendChild(btn); }
    });
    var hasAny = reco.querySelectorAll('button.chip-reco').length > 0;
    if (recoBlock){
      recoBlock.style.display = hasAny ? '' : 'none';
      recoBlock.setAttribute('data-has-reco', hasAny ? '1' : '0');
    }
    if (selAll){ selAll.style.display = hasAny ? '' : 'none'; }
    updateUI();
  }

  document.addEventListener('partner:preview', function(evt){
    var detail = (evt && evt.detail) || {};
    if (detail.scope && detail.scope !== previewScope) return;
    var tags = Array.isArray(detail.theme_tags) && detail.theme_tags.length ? detail.theme_tags : [];
    if (!tags.length && detail.payload && Array.isArray(detail.payload.theme_tags)){
      tags = detail.payload.theme_tags;
    }
    updatePartnerRecommendations(tags);
  });

  var initialPartnerTags = readPartnerPreviewTags();
  updatePartnerRecommendations(initialPartnerTags);
  updateUI();
})();
</script>
