<%- include('partials/header') %>
<%- include('partials/nav') %>

<main class="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">

  <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-8 pb-6 border-b border-sky-100">
    <div>
      <h1 class="text-3xl font-bold text-slate-900">Products</h1>
      <p class="text-sm text-slate-500 mt-1">Package a shared email server, SMS account, or Telegram bot into a fixed daily-limit plan users can request by name.</p>
    </div>
    <div class="mt-4 md:mt-0">
      <a href="/admin" class="inline-flex items-center px-4 py-2 text-sm font-semibold text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 rounded-xl shadow-sm transition">
        ← Back to Admin
      </a>
    </div>
  </div>

  <% if (error) { %>
    <div class="mb-6 px-4 py-3 rounded-lg text-sm border bg-red-50 border-red-200 text-red-600"><%= error %></div>
  <% } %>
  <% if (message) { %>
    <div class="mb-6 px-4 py-3 rounded-lg text-sm border bg-emerald-50 border-emerald-200 text-emerald-700"><%= message %></div>
  <% } %>

  <% const CHANNEL_ICON = { email: '✉️', sms: '💬', telegram: '✈️' }; %>

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

    <!-- Left: Add product form -->
    <div class="lg:col-span-1">
      <div class="bg-white rounded-2xl border border-sky-100 shadow-sm p-6 sticky top-24">
        <h3 class="text-lg font-bold text-slate-900 mb-1">New Product</h3>
        <p class="text-xs text-slate-500 mb-4">Pick one of your published global resources, then fix a daily send-out quota for it.</p>

        <form action="/admin/products" method="POST" class="space-y-4" id="product-form">
          <div>
            <label class="block text-xs font-medium text-slate-600 mb-1">Channel</label>
            <select name="channel" id="product-channel" class="block w-full px-3 py-2 border border-slate-300 rounded-lg shadow-sm text-sm focus:outline-none focus:ring-2 focus:ring-brand-500">
              <option value="email">✉️ Email</option>
              <option value="sms">💬 SMS</option>
              <option value="telegram">✈️ Telegram</option>
            </select>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-600 mb-1">Resource</label>
            <% Object.keys(resourcesByChannel).forEach(channel => { %>
              <select name="resource_id" data-channel="<%= channel %>" class="product-resource-select block w-full px-3 py-2 border border-slate-300 rounded-lg shadow-sm text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 <%= channel === 'email' ? '' : 'hidden' %>">
                <% if (resourcesByChannel[channel].length === 0) { %>
                  <option value="">No global <%= channel %> resource yet</option>
                <% } else { %>
                  <% resourcesByChannel[channel].forEach(r => { %>
                    <option value="<%= r.id %>"><%= r.label %> (<%= r.daily_limit == null ? 'no cap' : r.daily_limit + '/day' %>)</option>
                  <% }) %>
                <% } %>
              </select>
            <% }) %>
            <p class="text-xs text-slate-400 mt-1">Only global resources appear here — mark one global from its own page first.</p>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-600 mb-1">Product Name</label>
            <input type="text" name="name" required placeholder="e.g. Starter Email — 100/day" class="block w-full px-3 py-2 border border-slate-300 rounded-lg shadow-sm text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500">
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-600 mb-1">Daily Limit</label>
            <input type="number" name="daily_limit" min="1" required placeholder="100" class="block w-full px-3 py-2 border border-slate-300 rounded-lg shadow-sm text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500">
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-600 mb-1">Description <span class="text-slate-400 font-normal">(optional)</span></label>
            <textarea name="description" rows="2" placeholder="Shown to users on the Requests page" class="block w-full px-3 py-2 border border-slate-300 rounded-lg shadow-sm text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500"></textarea>
          </div>

          <button type="submit" class="w-full flex justify-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-brand-500 hover:bg-brand-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-500 transition">
            Add Product
          </button>
        </form>

        <script>
          // Swap which resource <select> is submitted based on the chosen channel —
          // each channel's options are a separate <select name="resource_id">, and
          // only the visible one has a name, so only it gets submitted.
          (function () {
            const channelSelect = document.getElementById('product-channel');
            const resourceSelects = document.querySelectorAll('.product-resource-select');
            function sync() {
              resourceSelects.forEach((sel) => {
                const match = sel.dataset.channel === channelSelect.value;
                sel.classList.toggle('hidden', !match);
                sel.disabled = !match;
              });
            }
            channelSelect.addEventListener('change', sync);
            sync();
          })();
        </script>
      </div>
    </div>

    <!-- Right: Product list -->
    <div class="lg:col-span-2">
      <div class="bg-white rounded-2xl border border-sky-100 shadow-sm overflow-hidden">
        <div class="p-6 border-b border-sky-100">
          <h3 class="text-lg font-bold text-slate-900">Products</h3>
          <p class="text-xs text-slate-500 mt-0.5"><%= products.length %> product<%= products.length === 1 ? '' : 's' %></p>
        </div>

        <% if (products.length === 0) { %>
          <div class="p-12 text-center text-slate-400">
            <p class="text-4xl mb-2">📦</p>
            <p class="text-sm">No products yet. Publish a global resource on its own page, then package it here.</p>
          </div>
        <% } else { %>
          <div class="divide-y divide-sky-50">
            <% products.forEach(p => { %>
              <div class="p-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <div>
                  <p class="text-sm font-bold text-slate-900 flex items-center gap-2">
                    <%= CHANNEL_ICON[p.channel] %> <%= p.name %>
                    <% if (!p.is_active) { %><span class="px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide bg-slate-100 text-slate-500 rounded">Inactive</span><% } %>
                  </p>
                  <p class="text-xs text-slate-500 mt-0.5"><%= p.daily_limit %>/day on <%= p.resource_label %><% if (p.description) { %> &middot; <%= p.description %><% } %></p>
                </div>
                <div class="flex gap-2 flex-shrink-0">
                  <form action="/admin/products/<%= p.id %>/toggle" method="POST">
                    <input type="hidden" name="active" value="<%= p.is_active ? '0' : '1' %>">
                    <button type="submit" class="px-3 py-1.5 text-xs font-semibold rounded-lg shadow-sm transition <%= p.is_active ? 'text-slate-600 bg-slate-100 hover:bg-slate-200' : 'text-white bg-emerald-500 hover:bg-emerald-600' %>">
                      <%= p.is_active ? 'Deactivate' : 'Activate' %>
                    </button>
                  </form>
                  <form action="/admin/products/<%= p.id %>/delete" method="POST" onsubmit="return confirm('Delete this product? Existing allocations made from it keep working — this only removes it from the request page.');">
                    <button type="submit" class="px-3 py-1.5 text-xs font-semibold text-red-500 hover:text-red-600">Delete</button>
                  </form>
                </div>
              </div>
            <% }) %>
          </div>
        <% } %>
      </div>
    </div>

  </div>
</main>

<%- include('partials/footer') %>
