{% extends "dashboard/base.html" %}

{% block title %}Schedules — {{ dashboard_title }}{% endblock %}
{% block page_title %}Schedules{% endblock %}

{% block content %}
<div class="px-8 py-6">

  <!-- Page Header -->
  <div class="mb-6 flex items-center justify-between">
    <div>
      <h1 class="text-2xl font-bold text-white tracking-tight">Schedules &amp; Cronjobs</h1>
      <p class="text-slate-400 text-sm mt-1">Manage and monitor your automated workflows.</p>
    </div>
    {% if current_user and current_user.is_admin %}
    <button onclick="document.getElementById('create-schedule-modal').classList.remove('hidden')"
      class="px-4 py-2.5 bg-primary text-white rounded-lg text-sm font-bold hover:bg-primary/90 transition-colors inline-flex items-center gap-2">
      <span class="material-symbols-outlined text-base">add</span>
      New Schedule
    </button>
    {% endif %}
  </div>

  {% if create_error %}
  <div class="p-4 mb-5 rounded-lg border border-rose-500/20 bg-rose-500/5 text-rose-400 flex gap-3">
    <span class="material-symbols-outlined text-rose-500 flex-shrink-0">error</span>
    <span class="text-sm">{{ create_error }}</span>
  </div>
  {% endif %}

  <!-- Stats Bar -->
  <div class="stats-bar mb-6">
    <div class="stats-bar-card">
      <div class="stats-bar-label">Total Scheduled</div>
      <div class="stats-bar-value">
        {% if schedule_stats %}{{ schedule_stats.total_scheduled }}{% else %}{{ (schedules|length + user_schedules|length) }}{% endif %}
      </div>
    </div>
    <div class="stats-bar-card">
      <div class="stats-bar-label">Active</div>
      <div class="stats-bar-value text-emerald-400">
        {% if schedule_stats %}{{ schedule_stats.active_schedules }}{% else %}{{ (schedules|selectattr('enabled')|list|length + user_schedules|selectattr('enabled')|list|length) }}{% endif %}
      </div>
    </div>
    <div class="stats-bar-card">
      <div class="stats-bar-label">Success (24h)</div>
      <div class="stats-bar-value">
        {% if schedule_stats %}{{ schedule_stats.success }}{% else %}—{% endif %}
      </div>
    </div>
    <div class="stats-bar-card">
      <div class="stats-bar-label">Recent Failures</div>
      <div class="stats-bar-value text-rose-400">
        {% if schedule_stats %}{{ schedule_stats.failed }}{% else %}0{% endif %}
      </div>
    </div>
  </div>

  {% if schedules or user_schedules %}
  <div class="bg-surface rounded-xl border border-border-dark shadow-sm overflow-hidden">

    <!-- Tab Bar + Filter Actions -->
    <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between border-b border-border-dark px-5 py-3 gap-3">
      <div class="flex gap-0.5 bg-surface-2 rounded-lg p-1">
        <button id="sched-tab-all" onclick="filterSchedules('all')" class="px-3 py-1.5 text-xs font-bold rounded-md bg-surface text-white shadow-sm whitespace-nowrap">All</button>
        <button id="sched-tab-enabled" onclick="filterSchedules('enabled')" class="px-3 py-1.5 text-xs font-medium text-slate-400 hover:text-white whitespace-nowrap transition-colors rounded-md">Enabled</button>
        <button id="sched-tab-disabled" onclick="filterSchedules('disabled')" class="px-3 py-1.5 text-xs font-medium text-slate-400 hover:text-white whitespace-nowrap transition-colors rounded-md">Disabled</button>
      </div>
    </div>

    <div class="overflow-x-auto">
      <table class="w-full text-left border-collapse" id="schedules-table">
        <thead>
          <tr class="bg-surface-2 border-b border-border-dark text-slate-500 text-[11px] font-bold uppercase tracking-wider">
            <th class="px-5 py-3.5">Name</th>
            <th class="px-5 py-3.5">Agent</th>
            <th class="px-5 py-3.5">Cron</th>
            <th class="px-5 py-3.5">Type</th>
            <th class="px-5 py-3.5 text-center">Enabled</th>
            <th class="px-5 py-3.5">Next Run</th>
            <th class="px-5 py-3.5 text-right">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-border-dark/50">
          {% for s in schedules %}
          <tr class="group hover:bg-surface-2 transition-colors sched-row" data-enabled="{{ 'true' if s.enabled else 'false' }}">
            <td class="px-5 py-4 whitespace-nowrap">
              <div class="flex items-center gap-3">
                <div class="h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary flex-shrink-0">
                  <span class="material-symbols-outlined text-sm">schedule</span>
                </div>
                <div>
                  <p class="text-sm font-semibold text-white">{{ s.name }}</p>
                  <p class="text-[10px] text-slate-500 uppercase">{{ s.timezone }}</p>
                </div>
              </div>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <span class="text-sm text-slate-300">{{ agent_names.get(s.agent_id, s.agent_id) }}</span>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <span class="cron-chip">{{ s.cron_expr }}</span>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              {% if s.source == 'admin' %}
              <span class="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-bold bg-amber-500/10 border border-amber-500/20 text-amber-400 uppercase">Admin</span>
              {% else %}
              <span class="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-bold bg-primary/10 border border-primary/20 text-primary uppercase">Workspace</span>
              {% endif %}
            </td>
            <td class="px-5 py-4 whitespace-nowrap text-center">
              {% if current_user and current_user.is_admin %}
              <label class="toggle-switch">
                <input type="checkbox" {% if s.enabled %}checked{% endif %}
                  hx-post="/dashboard/schedules/{{ s.id }}/toggle"
                  hx-swap="none"
                  onchange="this.closest('tr').dataset.enabled = this.checked ? 'true' : 'false'" />
                <span class="toggle-track"></span>
              </label>
              {% else %}
              <span class="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-medium {% if s.enabled %}text-emerald-400{% else %}text-slate-500{% endif %}">{{ 'On' if s.enabled else 'Off' }}</span>
              {% endif %}
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <div class="flex flex-col">
                <span class="text-sm text-slate-200">{{ format_datetime(s.next_run_at) if s.next_run_at else '—' }}</span>
                <span class="text-[10px] text-slate-500">{{ relative_time(s.next_run_at) if s.next_run_at else '' }}</span>
              </div>
            </td>
            <td class="px-5 py-4 whitespace-nowrap text-right">
              {% if current_user and current_user.is_admin %}
              <div class="flex items-center justify-end gap-1">
                <a href="/dashboard/schedules/{{ s.id }}/detail"
                   class="p-1.5 text-slate-500 hover:text-primary transition-colors rounded-lg hover:bg-primary/10"
                   title="Edit Schedule">
                  <span class="material-symbols-outlined text-base">edit</span>
                </a>
                {% if s.source == 'admin' %}
                <form method="POST" action="/dashboard/schedules/{{ s.id }}/delete"
                      onsubmit="return confirm('Delete this schedule?')">
                  <button type="submit"
                    class="p-1.5 text-slate-500 hover:text-rose-400 transition-colors rounded-lg hover:bg-rose-500/10"
                    title="Delete Schedule">
                    <span class="material-symbols-outlined text-base">delete</span>
                  </button>
                </form>
                {% endif %}
              </div>
              {% else %}
              <button class="p-1.5 text-slate-500 hover:text-primary transition-colors rounded-lg hover:bg-primary/10">
                <span class="material-symbols-outlined text-base">more_horiz</span>
              </button>
              {% endif %}
            </td>
          </tr>
          {% endfor %}

          {% for s in user_schedules %}
          <tr class="group hover:bg-surface-2 transition-colors sched-row" data-enabled="{{ 'true' if s.enabled else 'false' }}">
            <td class="px-5 py-4 whitespace-nowrap">
              <div class="flex items-center gap-3">
                <div class="h-8 w-8 rounded-lg bg-purple-500/10 flex items-center justify-center text-purple-400 flex-shrink-0">
                  <span class="material-symbols-outlined text-sm">person</span>
                </div>
                <div>
                  <p class="text-sm font-semibold text-white">{{ s.name }}</p>
                  <p class="text-[10px] text-slate-500 uppercase">{{ s.timezone }}</p>
                </div>
              </div>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <span class="text-sm text-slate-300">{{ agent_names.get(s.agent_id, s.agent_id) }}</span>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <span class="cron-chip">{{ s.cron_expr }}</span>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <span class="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-bold bg-purple-500/10 border border-purple-500/20 text-purple-400 uppercase">Personal</span>
            </td>
            <td class="px-5 py-4 whitespace-nowrap text-center">
              <label class="toggle-switch">
                <input type="checkbox" {% if s.enabled %}checked{% endif %}
                  hx-post="/dashboard/my-schedules/{{ s.id }}/toggle"
                  hx-swap="none"
                  onchange="this.closest('tr').dataset.enabled = this.checked ? 'true' : 'false'" />
                <span class="toggle-track"></span>
              </label>
            </td>
            <td class="px-5 py-4 whitespace-nowrap">
              <div class="flex flex-col">
                <span class="text-sm text-slate-200">{{ format_datetime(s.next_run_at) if s.next_run_at else '—' }}</span>
                <span class="text-[10px] text-slate-500">{{ relative_time(s.next_run_at) if s.next_run_at else '' }}</span>
              </div>
            </td>
            <td class="px-5 py-4 whitespace-nowrap text-right">
              <a href="/dashboard/my-schedules" class="p-1.5 text-slate-500 hover:text-primary transition-colors rounded-lg hover:bg-primary/10 inline-flex" title="Edit Schedule">
                <span class="material-symbols-outlined text-base">edit</span>
              </a>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    <!-- Footer -->
    <div class="px-5 py-3 border-t border-border-dark/50 bg-surface-2/30">
      <p class="text-[10px] text-slate-600">Schedules are derived from agent <code class="text-slate-500">AGENT.md</code> files, admin-created, or personal tasks.</p>
    </div>
  </div>

  {% else %}
  <div class="py-20 flex flex-col items-center justify-center text-center bg-surface rounded-xl border border-border-dark">
    <div class="w-16 h-16 bg-surface-2 border border-border-dark rounded-full flex items-center justify-center text-slate-500 mb-4">
      <span class="material-symbols-outlined text-3xl">calendar_month</span>
    </div>
    <h3 class="text-base font-bold text-white mb-1">No schedules configured</h3>
    <p class="text-sm text-slate-500 max-w-sm">Add <code class="text-slate-400">schedules:</code> to your agent's <code class="text-slate-400">AGENT.md</code>, <a href="/dashboard/my-schedules" class="text-primary font-bold">create a personal schedule</a>, or use the "New Schedule" button above.</p>
  </div>
  {% endif %}

</div>

<!-- Create Schedule Modal -->
{% if current_user and current_user.is_admin %}
<div id="create-schedule-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
  <div class="bg-surface border border-border-dark rounded-xl shadow-2xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
    <div class="flex items-center justify-between px-5 py-4 border-b border-border-dark">
      <h2 class="text-lg font-bold text-white">New Admin Schedule</h2>
      <button onclick="document.getElementById('create-schedule-modal').classList.add('hidden')"
        class="p-1 text-slate-500 hover:text-white transition-colors rounded-lg">
        <span class="material-symbols-outlined">close</span>
      </button>
    </div>
    <form method="POST" action="/dashboard/schedules/create" class="p-5 space-y-4">
      <div>
        <label for="cs-agent" class="block text-sm font-medium text-slate-300 mb-1">Agent</label>
        <select id="cs-agent" name="agent_id" required
          class="input w-full">
          {% for a in agents %}
          <option value="{{ a.id }}">{{ a.display_name or a.id }}</option>
          {% endfor %}
        </select>
      </div>
      <div>
        <label for="cs-name" class="block text-sm font-medium text-slate-300 mb-1">Name</label>
        <input type="text" id="cs-name" name="name" required pattern="^[a-zA-Z0-9_.\-]+$"
          class="input w-full" style="font-family: var(--font-mono, monospace);"
          placeholder="weekly-report">
        <p class="text-[10px] text-slate-500 mt-1">Letters, digits, dashes, underscores, dots only.</p>
      </div>
      <!-- Cron Schedule Builder -->
      <div>
        <label class="block text-sm font-medium text-slate-300 mb-2">Frequency</label>

        <!-- Preset buttons -->
        <div id="cs-freq-presets" style="display:flex; flex-wrap:wrap; gap: var(--space-2); margin-bottom: var(--space-3);">
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn" data-freq="every-minutes">Every N minutes</button>
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn" data-freq="hourly">Hourly</button>
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn active" data-freq="daily">Daily</button>
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn" data-freq="weekly">Weekly</button>
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn" data-freq="monthly">Monthly</button>
          <button type="button" class="btn btn-ghost btn-sm cs-freq-btn" data-freq="custom">Custom cron</button>
        </div>

        <!-- Every N minutes -->
        <div id="cs-freq-every-minutes" class="cs-freq-options" style="display:none;">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Run every</label>
          <div style="display:flex; align-items:center; gap: var(--space-2);">
            <select id="cs-interval-minutes" class="input" style="width: 6rem;">
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="15" selected>15</option>
              <option value="20">20</option>
              <option value="30">30</option>
            </select>
            <span class="text-sm text-muted">minutes</span>
          </div>
        </div>

        <!-- Hourly -->
        <div id="cs-freq-hourly" class="cs-freq-options" style="display:none;">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">At minute</label>
          <select id="cs-hourly-minute" class="input" style="width: 6rem;">
            <option value="0">:00</option>
            <option value="15">:15</option>
            <option value="30">:30</option>
            <option value="45">:45</option>
          </select>
        </div>

        <!-- Daily -->
        <div id="cs-freq-daily" class="cs-freq-options">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Time</label>
          <div style="display:flex; align-items:center; gap: var(--space-2);">
            <select id="cs-daily-hour" class="input" style="width: 6rem;">
              {% for h in range(24) %}
              <option value="{{ h }}" {% if h == 9 %}selected{% endif %}>{{ "%02d"|format(h) }}:00</option>
              {% endfor %}
            </select>
            <select id="cs-daily-minute" class="input" style="width: 6rem;">
              <option value="0" selected>:00</option>
              <option value="15">:15</option>
              <option value="30">:30</option>
              <option value="45">:45</option>
            </select>
          </div>
        </div>

        <!-- Weekly -->
        <div id="cs-freq-weekly" class="cs-freq-options" style="display:none;">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Days</label>
          <div id="cs-weekday-picker" style="display:flex; gap: var(--space-1); margin-bottom: var(--space-2);">
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="1">Mon</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn active" data-day="2">Tue</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="3">Wed</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="4">Thu</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="5">Fri</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="6">Sat</button>
            <button type="button" class="btn btn-ghost btn-sm cs-weekday-btn" data-day="0">Sun</button>
          </div>
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Time</label>
          <div style="display:flex; align-items:center; gap: var(--space-2);">
            <select id="cs-weekly-hour" class="input" style="width: 6rem;">
              {% for h in range(24) %}
              <option value="{{ h }}" {% if h == 9 %}selected{% endif %}>{{ "%02d"|format(h) }}:00</option>
              {% endfor %}
            </select>
            <select id="cs-weekly-minute" class="input" style="width: 6rem;">
              <option value="0" selected>:00</option>
              <option value="15">:15</option>
              <option value="30">:30</option>
              <option value="45">:45</option>
            </select>
          </div>
        </div>

        <!-- Monthly -->
        <div id="cs-freq-monthly" class="cs-freq-options" style="display:none;">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Day of month</label>
          <div style="display:flex; align-items:center; gap: var(--space-2); margin-bottom: var(--space-2);">
            <select id="cs-monthly-day" class="input" style="width: 6rem;">
              {% for d in range(1, 29) %}
              <option value="{{ d }}">{{ d }}{{ "st" if d == 1 else ("nd" if d == 2 else ("rd" if d == 3 else "th")) }}</option>
              {% endfor %}
            </select>
            <span class="text-sm text-muted">of each month</span>
          </div>
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Time</label>
          <div style="display:flex; align-items:center; gap: var(--space-2);">
            <select id="cs-monthly-hour" class="input" style="width: 6rem;">
              {% for h in range(24) %}
              <option value="{{ h }}" {% if h == 9 %}selected{% endif %}>{{ "%02d"|format(h) }}:00</option>
              {% endfor %}
            </select>
            <select id="cs-monthly-minute" class="input" style="width: 6rem;">
              <option value="0" selected>:00</option>
              <option value="15">:15</option>
              <option value="30">:30</option>
              <option value="45">:45</option>
            </select>
          </div>
        </div>

        <!-- Custom cron -->
        <div id="cs-freq-custom" class="cs-freq-options" style="display:none;">
          <label class="form-label text-sm" style="margin-bottom: var(--space-1);">Cron expression</label>
          <input type="text" id="cs-custom-cron-input" class="input" style="width:100%; font-family: var(--font-mono, monospace);" placeholder="*/15 * * * *" />
          <div class="text-xs text-muted" style="margin-top: var(--space-1);">Format: minute hour day-of-month month day-of-week</div>
        </div>

        <!-- Preview -->
        <div id="cs-cron-preview" style="margin-top: var(--space-2); padding: var(--space-2) var(--space-3); background: var(--color-surface-alt, rgba(0,0,0,0.03)); border-radius: 6px; display:flex; align-items:center; gap: var(--space-2);">
          <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="opacity:0.5; flex-shrink:0;">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span class="text-sm"><strong>Cron:</strong> <code id="cs-cron-display" class="text-mono">0 9 * * *</code></span>
          <span class="text-sm text-muted" style="margin-left: var(--space-2);" id="cs-cron-human">Every day at 09:00</span>
        </div>

        <!-- Hidden cron field submitted with form -->
        <input type="hidden" name="cron_expr" id="cs-cron-value" value="0 9 * * *" />
      </div>
      <div>
        <label for="cs-message" class="block text-sm font-medium text-slate-300 mb-1">Message</label>
        <textarea id="cs-message" name="message" rows="3" required
          class="input w-full"
          placeholder="Generate the weekly report..."></textarea>
      </div>
      <div>
        <label for="cs-instructions" class="block text-sm font-medium text-slate-300 mb-1">Instructions <span class="text-slate-500 font-normal">(optional)</span></label>
        <textarea id="cs-instructions" name="instructions" rows="3"
          class="input w-full"
          placeholder="Custom system prompt instructions..."></textarea>
      </div>
      <div>
        <label for="cs-timezone" class="block text-sm font-medium text-slate-300 mb-1">Timezone</label>
        <input type="text" id="cs-timezone" name="timezone" value="UTC"
          class="input w-full">
      </div>
      <div class="flex items-center gap-3">
        <label class="relative inline-flex items-center cursor-pointer">
          <input type="checkbox" name="enabled" value="on" checked class="sr-only peer">
          <div class="w-9 h-5 bg-surface-2 border border-border-dark rounded-full peer peer-checked:bg-primary/20 peer-checked:border-primary/50 after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-slate-400 after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full peer-checked:after:bg-primary"></div>
        </label>
        <span class="text-sm text-slate-300">Enabled</span>
      </div>
      <div class="pt-2 flex justify-end gap-3">
        <button type="button" onclick="document.getElementById('create-schedule-modal').classList.add('hidden')"
          class="px-4 py-2 text-sm font-medium text-slate-400 hover:text-white transition-colors">Cancel</button>
        <button type="submit" class="px-5 py-2.5 bg-primary text-white rounded-lg text-sm font-bold hover:bg-primary/90 transition-colors">
          Create Schedule
        </button>
      </div>
    </form>
  </div>
</div>
{% endif %}

<style>
  .cs-freq-btn.active,
  .cs-weekday-btn.active {
    background: var(--color-primary, #6366f1) !important;
    color: #fff !important;
    border-color: var(--color-primary, #6366f1) !important;
  }
  .cs-freq-btn:hover, .cs-weekday-btn:hover {
    background: var(--color-surface-hover, rgba(0,0,0,0.06));
  }
</style>

<script>
(function() {
  const freqBtns = document.querySelectorAll('.cs-freq-btn');
  const freqPanels = document.querySelectorAll('.cs-freq-options');
  const cronValue = document.getElementById('cs-cron-value');
  const cronDisplay = document.getElementById('cs-cron-display');
  const cronHuman = document.getElementById('cs-cron-human');
  const weekdayBtns = document.querySelectorAll('.cs-weekday-btn');

  if (!cronValue) return; // modal not rendered (non-admin)

  let currentFreq = 'daily';

  function showPanel(freq) {
    currentFreq = freq;
    freqPanels.forEach(p => p.style.display = 'none');
    const panel = document.getElementById('cs-freq-' + freq);
    if (panel) panel.style.display = '';
    freqBtns.forEach(b => b.classList.toggle('active', b.dataset.freq === freq));
    updateCron();
  }

  function getSelectedWeekdays() {
    const days = [];
    weekdayBtns.forEach(b => { if (b.classList.contains('active')) days.push(b.dataset.day); });
    return days.length ? days : ['1'];
  }

  function padTime(h, m) {
    return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0');
  }

  function dayName(d) {
    return ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][parseInt(d)];
  }

  function updateCron() {
    let cron = '';
    let human = '';

    switch (currentFreq) {
      case 'every-minutes': {
        const mins = document.getElementById('cs-interval-minutes').value;
        cron = '*/' + mins + ' * * * *';
        human = 'Every ' + mins + ' minutes';
        break;
      }
      case 'hourly': {
        const m = document.getElementById('cs-hourly-minute').value;
        cron = m + ' * * * *';
        human = 'Every hour at :' + String(m).padStart(2, '0');
        break;
      }
      case 'daily': {
        const h = document.getElementById('cs-daily-hour').value;
        const m = document.getElementById('cs-daily-minute').value;
        cron = m + ' ' + h + ' * * *';
        human = 'Every day at ' + padTime(h, m);
        break;
      }
      case 'weekly': {
        const h = document.getElementById('cs-weekly-hour').value;
        const m = document.getElementById('cs-weekly-minute').value;
        const days = getSelectedWeekdays();
        cron = m + ' ' + h + ' * * ' + days.join(',');
        const dayNames = days.map(dayName).join(', ');
        human = 'Every ' + dayNames + ' at ' + padTime(h, m);
        break;
      }
      case 'monthly': {
        const h = document.getElementById('cs-monthly-hour').value;
        const m = document.getElementById('cs-monthly-minute').value;
        const d = document.getElementById('cs-monthly-day').value;
        cron = m + ' ' + h + ' ' + d + ' * *';
        human = 'Day ' + d + ' of each month at ' + padTime(h, m);
        break;
      }
      case 'custom': {
        cron = document.getElementById('cs-custom-cron-input').value || '* * * * *';
        human = 'Custom expression';
        break;
      }
    }

    cronValue.value = cron;
    cronDisplay.textContent = cron;
    cronHuman.textContent = human;
  }

  freqBtns.forEach(btn => {
    btn.addEventListener('click', () => showPanel(btn.dataset.freq));
  });

  weekdayBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      btn.classList.toggle('active');
      updateCron();
    });
  });

  document.querySelectorAll('.cs-freq-options select, .cs-freq-options input').forEach(el => {
    el.addEventListener('change', updateCron);
    el.addEventListener('input', updateCron);
  });

  updateCron();
})();

function filterSchedules(filter) {
  // Update tab styles
  const tabs = {all: 'sched-tab-all', enabled: 'sched-tab-enabled', disabled: 'sched-tab-disabled'};
  Object.keys(tabs).forEach(key => {
    const el = document.getElementById(tabs[key]);
    if (key === filter) {
      el.className = 'px-3 py-1.5 text-xs font-bold rounded-md bg-surface text-white shadow-sm whitespace-nowrap';
    } else {
      el.className = 'px-3 py-1.5 text-xs font-medium text-slate-400 hover:text-white whitespace-nowrap transition-colors rounded-md';
    }
  });

  // Filter rows
  const rows = document.querySelectorAll('.sched-row');
  rows.forEach(row => {
    const enabled = row.dataset.enabled === 'true';
    if (filter === 'all') {
      row.style.display = '';
    } else if (filter === 'enabled') {
      row.style.display = enabled ? '' : 'none';
    } else if (filter === 'disabled') {
      row.style.display = !enabled ? '' : 'none';
    }
  });
}
</script>
{% endblock %}
