{% extends "admin/base_admin.html" %}
{% set admin_page = "affiliate" %}

{% block title %}{% if editing %}Edit Product{% else %}New Product{% endif %} - Admin - {{ config.APP_NAME }}{% endblock %}

{% block admin_head %}
<script>
function slugify(text) {
  return text.toLowerCase()
    .replace(/[äöü]/g, c => ({'ä':'ae','ö':'oe','ü':'ue'}[c]))
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}
document.addEventListener('DOMContentLoaded', function() {
  var nameInput = document.getElementById('f-name');
  var slugInput = document.getElementById('f-slug');
  if (nameInput && slugInput && !slugInput.value) {
    nameInput.addEventListener('input', function() {
      if (!slugInput.dataset.manual) {
        slugInput.value = slugify(nameInput.value);
      }
    });
    slugInput.addEventListener('input', function() {
      slugInput.dataset.manual = '1';
    });
  }

  // Toggle program-based vs manual URL fields
  function toggleProgramFields() {
    var sel = document.getElementById('f-program');
    if (!sel) return;
    var isManual = sel.value === '0' || sel.value === '';
    document.getElementById('f-product-id-row').style.display = isManual ? 'none' : '';
    document.getElementById('f-manual-url-row').style.display = isManual ? '' : 'none';
  }
  var programSel = document.getElementById('f-program');
  if (programSel) {
    programSel.addEventListener('change', toggleProgramFields);
    toggleProgramFields();
  }
});
</script>
{% endblock %}

{% block admin_content %}
  <header class="flex justify-between items-center mb-6">
    <div>
      <a href="{{ url_for('admin.affiliate_products') }}" class="text-slate text-sm" style="text-decoration:none">← Products</a>
      <h1 class="text-2xl mt-1">{% if editing %}Edit Product{% else %}New Product{% endif %}</h1>
    </div>
  </header>

  {# HTMX preview trigger — outside the grid so it takes no layout space #}
  <div style="display:none"
       hx-post="{{ url_for('admin.affiliate_preview') }}"
       hx-target="#product-preview"
       hx-trigger="load, input from:#affiliate-form delay:600ms"
       hx-include="#affiliate-form"
       hx-push-url="false">
  </div>

  <div style="display:grid;grid-template-columns:1fr 380px;gap:2rem;align-items:start" class="affiliate-form-grid">

    {# ── Left: form ── #}
    <form method="post" id="affiliate-form"
          action="{% if editing %}{{ url_for('admin.affiliate_edit', product_id=product_id) }}{% else %}{{ url_for('admin.affiliate_new') }}{% endif %}">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

      <div class="card" style="padding:1.5rem;display:flex;flex-direction:column;gap:1.25rem;">

        {# Name #}
        <div>
          <label class="form-label" for="f-name">Name *</label>
          <input id="f-name" type="text" name="name" value="{{ data.get('name','') }}"
                 class="form-input" placeholder="e.g. Bullpadel Vertex 04" required>
        </div>

        {# Slug #}
        <div>
          <label class="form-label" for="f-slug">Slug *</label>
          <input id="f-slug" type="text" name="slug" value="{{ data.get('slug','') }}"
                 class="form-input" placeholder="e.g. bullpadel-vertex-04-amazon" required
                 pattern="[a-z0-9][a-z0-9\-]*">
          <p class="form-hint">Lowercase letters, numbers, hyphens only. Include retailer to disambiguate (e.g. <code>-amazon</code>, <code>-padelnuestro</code>).</p>
        </div>

        {# Brand + Category row #}
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
          <div>
            <label class="form-label" for="f-brand">Brand</label>
            <input id="f-brand" type="text" name="brand" value="{{ data.get('brand','') }}"
                   class="form-input" placeholder="e.g. Bullpadel">
          </div>
          <div>
            <label class="form-label" for="f-category">Category</label>
            <select id="f-category" name="category" class="form-input">
              {% for cat in categories %}
              <option value="{{ cat }}" {% if data.get('category','accessory') == cat %}selected{% endif %}>{{ cat | capitalize }}</option>
              {% endfor %}
            </select>
          </div>
        </div>

        {# Program dropdown #}
        <div>
          <label class="form-label" for="f-program">Affiliate Program</label>
          <select id="f-program" name="program_id" class="form-input">
            <option value="0" {% if not data.get('program_id') %}selected{% endif %}>Manual (custom URL)</option>
            {% for prog in programs %}
            <option value="{{ prog.id }}" {% if data.get('program_id') == prog.id %}selected{% endif %}>{{ prog.name }}</option>
            {% endfor %}
          </select>
          <p class="form-hint">Select a program to auto-build the URL, or choose Manual for a custom link.</p>
        </div>

        {# Product Identifier (shown when program selected) #}
        <div id="f-product-id-row">
          <label class="form-label" for="f-product-id">Product ID *</label>
          <input id="f-product-id" type="text" name="product_identifier"
                 value="{{ data.get('product_identifier','') }}"
                 class="form-input" placeholder="e.g. B0XXXXXXXXX (ASIN for Amazon)">
          <p class="form-hint">ASIN, product path, or other program-specific identifier. URL is assembled at redirect time.</p>
        </div>

        {# Manual URL (shown when Manual selected) #}
        <div id="f-manual-url-row">
          <label class="form-label" for="f-url">Affiliate URL</label>
          <input id="f-url" type="url" name="affiliate_url" value="{{ data.get('affiliate_url','') }}"
                 class="form-input" placeholder="https://www.amazon.de/dp/B0XXXXX?tag=padelnomics-21">
          <p class="form-hint">Full URL with tracking params already baked in. Used as fallback if no program is set.</p>
        </div>

        {# Retailer (auto-populated from program; editable for manual products) #}
        <div>
          <label class="form-label" for="f-retailer">Retailer <span class="form-hint" style="font-weight:normal">(auto-filled from program)</span></label>
          <input id="f-retailer" type="text" name="retailer" value="{{ data.get('retailer','') }}"
                 class="form-input" placeholder="e.g. Amazon, Padel Nuestro"
                 list="retailers-list">
          <datalist id="retailers-list">
            {% for r in retailers %}
            <option value="{{ r }}">
            {% endfor %}
          </datalist>
        </div>

        {# Image URL #}
        <div>
          <label class="form-label" for="f-image">Image URL</label>
          <input id="f-image" type="text" name="image_url" value="{{ data.get('image_url','') }}"
                 class="form-input" placeholder="/static/images/affiliate/bullpadel-vertex-04.webp">
          <p class="form-hint">Local path (recommended) or external URL.</p>
        </div>

        {# Price + Rating row #}
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
          <div>
            <label class="form-label" for="f-price">Price (EUR)</label>
            <input id="f-price" type="number" name="price_eur" value="{{ data.get('price_eur','') }}"
                   class="form-input" placeholder="149.99" step="0.01" min="0">
          </div>
          <div>
            <label class="form-label" for="f-rating">Rating (0–5)</label>
            <input id="f-rating" type="number" name="rating" value="{{ data.get('rating','') }}"
                   class="form-input" placeholder="4.3" step="0.1" min="0" max="5">
          </div>
        </div>

        {# Description #}
        <div>
          <label class="form-label" for="f-desc">Short Description</label>
          <textarea id="f-desc" name="description" rows="3"
                    class="form-input" placeholder="One to two sentences describing the product...">{{ data.get('description','') }}</textarea>
        </div>

        {# Pros #}
        <div>
          <label class="form-label" for="f-pros">Pros <span class="form-hint" style="font-weight:normal">(one per line)</span></label>
          <textarea id="f-pros" name="pros" rows="4"
                    class="form-input" placeholder="Carbon frame for maximum power&#10;Diamond shape for aggressive players">{{ data.get('pros_text', data.get('pros','')) }}</textarea>
        </div>

        {# Cons #}
        <div>
          <label class="form-label" for="f-cons">Cons <span class="form-hint" style="font-weight:normal">(one per line)</span></label>
          <textarea id="f-cons" name="cons" rows="3"
                    class="form-input" placeholder="Only for advanced players">{{ data.get('cons_text', data.get('cons','')) }}</textarea>
        </div>

        {# CTA Label #}
        <div>
          <label class="form-label" for="f-cta">CTA Label</label>
          <input id="f-cta" type="text" name="cta_label" value="{{ data.get('cta_label','') }}"
                 class="form-input" placeholder='Leave empty for default "Zum Angebot"'>
        </div>

        {# Status + Language + Sort #}
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;">
          <div>
            <label class="form-label" for="f-status">Status</label>
            <select id="f-status" name="status" class="form-input">
              {% for s in statuses %}
              <option value="{{ s }}" {% if data.get('status','draft') == s %}selected{% endif %}>{{ s | capitalize }}</option>
              {% endfor %}
            </select>
          </div>
          <div>
            <label class="form-label" for="f-lang">Language</label>
            <select id="f-lang" name="language" class="form-input">
              <option value="de" {% if data.get('language','de') == 'de' %}selected{% endif %}>DE</option>
              <option value="en" {% if data.get('language','de') == 'en' %}selected{% endif %}>EN</option>
            </select>
          </div>
          <div>
            <label class="form-label" for="f-sort">Sort Order</label>
            <input id="f-sort" type="number" name="sort_order" value="{{ data.get('sort_order', 0) }}"
                   class="form-input" min="0">
          </div>
        </div>

        {# Actions #}
        <div class="flex gap-3 justify-between" style="margin-top:.5rem">
          <div class="flex gap-2">
            <button type="submit" class="btn" formaction="{% if editing %}{{ url_for('admin.affiliate_edit', product_id=product_id) }}{% else %}{{ url_for('admin.affiliate_new') }}{% endif %}">
              {% if editing %}Save Changes{% else %}Create Product{% endif %}
            </button>
            <a href="{{ url_for('admin.affiliate_products') }}" class="btn-outline">Cancel</a>
          </div>
          {% if editing %}
          <form method="post" action="{{ url_for('admin.affiliate_delete', product_id=product_id) }}" style="margin:0" hx-boost="true">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="btn-outline"
          </form>
          {% endif %}
        </div>

      </div>
    </form>

    {# ── Right: live preview ── #}
    <div style="position:sticky;top:1.5rem;">
      <div class="text-xs font-semibold text-slate mb-2" style="text-transform:uppercase;letter-spacing:.06em;">Preview</div>
      <div id="product-preview" style="border:1px solid #E2E8F0;border-radius:12px;padding:1rem;background:#F8FAFC;min-height:180px;">
        <p style="color:#94A3B8;font-size:.875rem;text-align:center;margin-top:2rem;">Loading preview…</p>
      </div>
    </div>

  </div>

  <style>
    @media (max-width: 900px) {
      .affiliate-form-grid { grid-template-columns: 1fr !important; }
    }
  </style>
{% endblock %}
