{% extends "base.html" %}
{% block title %}Search — ABREKA{% endblock %}

{% block breadcrumb %}
<div class="breadcrumb"><a href="/">Dashboard</a> / Search</div>
{% endblock %}

{% block extra_css %}
.search-layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 20px;
}
@media (max-width: 768px) {
  .search-layout { grid-template-columns: 1fr; }
}

/* Search bar */
.search-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}
.search-bar input[type="text"] {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  font-family: var(--font);
  background: var(--surface);
  color: var(--text);
}
.search-bar input[type="text"]:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.15);
}

/* Facets sidebar */
.facets .facet-group {
  margin-bottom: 16px;
}
.facets .facet-group h3 {
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: var(--muted);
  margin-bottom: 6px;
  font-weight: 600;
}
.facets label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  padding: 2px 0;
  cursor: pointer;
}
.facets label:hover { color: var(--primary); }
.facet-count {
  margin-left: auto;
  font-size: 11px;
  color: var(--muted);
  background: var(--bg);
  padding: 0 6px;
  border-radius: 8px;
  min-width: 20px;
  text-align: center;
}

/* Active filter chips */
.filter-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px;
}
.chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 10px;
  background: var(--primary-light);
  border: 1px solid var(--primary);
  border-radius: 12px;
  font-size: 12px;
  color: var(--primary);
}
.chip a {
  color: var(--primary);
  font-weight: 700;
  font-size: 14px;
  line-height: 1;
}
.chip a:hover { color: #ef4444; text-decoration: none; }

.result-count {
  font-size: 13px;
  color: var(--muted);
  margin-bottom: 8px;
}
{% endblock %}

{% block content %}
<h1 class="mb-2">Search Experiments</h1>

<form method="get" action="/search" id="search-form">
  {# Preserve non-text filters as hidden inputs so the search bar form keeps them #}
  {% for s in status_filters %}
  <input type="hidden" name="status" value="{{ s }}">
  {% endfor %}
  {% for t in tag_filters %}
  <input type="hidden" name="tag" value="{{ t }}">
  {% endfor %}
  {% if has_metrics %}
  <input type="hidden" name="has_metrics" value="{{ has_metrics }}">
  {% endif %}
  {% if root_only %}
  <input type="hidden" name="root_only" value="1">
  {% endif %}
  {% if parent_filter %}
  <input type="hidden" name="parent" value="{{ parent_filter }}">
  {% endif %}
  <input type="hidden" name="sort" value="{{ sort_by }}">
  <input type="hidden" name="order" value="{{ order }}">

  <div class="search-bar">
    <input type="text" name="q" value="{{ q }}" placeholder="Word search, or /regex/ or /regex/i for case-insensitive">
    <button type="submit" class="btn btn-primary">Search</button>
  </div>
</form>
{% if search_error %}
<div class="card" style="background: #fef2f2; border-color: #fca5a5; color: #991b1b; margin-bottom: 12px; padding: 8px 14px; font-size: 13px;">
  {{ search_error }}
</div>
{% endif %}

<div class="search-layout">
  {# Facet sidebar #}
  <div class="facets">
    <div class="card">
      {# Status facets #}
      <div class="facet-group">
        <h3>Status</h3>
        {% set all_statuses = ["proposed", "implementing", "testing", "running", "completed", "failed"] %}
        {% for s in all_statuses %}
        {% set count = status_counts.get(s, 0) %}
        {% set checked = s in status_filters %}
        <label>
          <input type="checkbox" data-facet="status" value="{{ s }}" {% if checked %}checked{% endif %}>
          <span class="badge" style="background: {{ s | status_color }}; font-size: 11px; padding: 1px 8px;">{{ s }}</span>
          <span class="facet-count">{{ count }}</span>
        </label>
        {% endfor %}
      </div>

      {# Tag facets #}
      {% if all_tags %}
      <div class="facet-group">
        <h3>Tags</h3>
        {% for tag, count in all_tags | dictsort %}
        {% set checked = tag in tag_filters %}
        <label>
          <input type="checkbox" data-facet="tag" value="{{ tag }}" {% if checked %}checked{% endif %}>
          {{ tag }}
          <span class="facet-count">{{ tag_counts.get(tag, 0) }}</span>
        </label>
        {% endfor %}
      </div>
      {% endif %}

      {# Has metrics #}
      <div class="facet-group">
        <h3>Metrics</h3>
        <label>
          <input type="radio" name="has_metrics_radio" value="" {% if not has_metrics %}checked{% endif %} data-facet="has_metrics">
          Any
        </label>
        <label>
          <input type="radio" name="has_metrics_radio" value="yes" {% if has_metrics == 'yes' %}checked{% endif %} data-facet="has_metrics">
          Has metrics
        </label>
        <label>
          <input type="radio" name="has_metrics_radio" value="no" {% if has_metrics == 'no' %}checked{% endif %} data-facet="has_metrics">
          No metrics
        </label>
      </div>

      {# Lineage #}
      <div class="facet-group">
        <h3>Lineage</h3>
        <label>
          <input type="checkbox" data-facet="root_only" {% if root_only %}checked{% endif %}>
          Root experiments only
        </label>
      </div>

      <button type="button" class="btn" style="width: 100%; margin-top: 8px;" onclick="applyFacets()">Apply Filters</button>
      {% if status_filters or tag_filters or has_metrics or root_only or parent_filter %}
      <a href="/search{% if q %}?q={{ q }}{% endif %}" class="text-sm" style="display: block; text-align: center; margin-top: 6px;">Clear all filters</a>
      {% endif %}
    </div>
  </div>

  {# Results #}
  <div>
    {# Active filter chips #}
    {% if q or status_filters or tag_filters or has_metrics or root_only or parent_filter %}
    <div class="filter-chips">
      {% if q %}
      <span class="chip">q: {{ q }} <a href="{{ request.url | string | replace('q=' + q, '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endif %}
      {% for s in status_filters %}
      <span class="chip">status: {{ s }} <a href="{{ request.url | string | replace('status=' + s, '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endfor %}
      {% for t in tag_filters %}
      <span class="chip">tag: {{ t }} <a href="{{ request.url | string | replace('tag=' + t, '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endfor %}
      {% if has_metrics %}
      <span class="chip">metrics: {{ has_metrics }} <a href="{{ request.url | string | replace('has_metrics=' + has_metrics, '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endif %}
      {% if root_only %}
      <span class="chip">root only <a href="{{ request.url | string | replace('root_only=1', '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endif %}
      {% if parent_filter %}
      <span class="chip">parent: {{ parent_filter }} <a href="{{ request.url | string | replace('parent=' + parent_filter, '') | replace('&&', '&') | replace('?&', '?') }}">&times;</a></span>
      {% endif %}
    </div>
    {% endif %}

    <div class="result-count">{{ total_results }} experiment{{ 's' if total_results != 1 }} found</div>

    {% if experiments %}
    <div class="card">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Status</th>
            <th>Hypothesis</th>
            <th>{{ primary_metric }}</th>
            <th>Parents</th>
            <th>Tags</th>
            <th>Created</th>
          </tr>
        </thead>
        <tbody>
          {% for exp in experiments %}
          <tr>
            <td><a href="/experiments/{{ exp.id }}" class="text-mono" style="font-weight: 600;">{{ exp.id }}</a></td>
            <td>
              <span class="badge" style="background: {{ exp.status | status_color }};">{{ exp.status }}</span>
            </td>
            <td>{{ exp.hypothesis[:60] }}{% if exp.hypothesis|length > 60 %}...{% endif %}</td>
            <td class="text-mono">
              {% if exp.metrics and pm_split and exp.metrics.get(pm_split, {}).get(pm_key) is not none %}
                {{ "%.4f" | format(exp.metrics[pm_split][pm_key]) }}
              {% else %}
                <span class="text-muted">—</span>
              {% endif %}
            </td>
            <td class="text-mono text-sm">
              {% for p in exp.parents %}
              <a href="/experiments/{{ p }}">{{ p }}</a>{% if not loop.last %}, {% endif %}
              {% endfor %}
              {% if not exp.parents %}<span class="text-muted">—</span>{% endif %}
            </td>
            <td class="text-sm">
              {% for t in exp.get('tags', []) %}
              <span style="background: #e2e5ea; padding: 1px 6px; border-radius: 4px; font-size: 11px;">{{ t }}</span>
              {% endfor %}
            </td>
            <td class="text-muted text-sm">{{ exp.created_at[:10] }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% else %}
    <div class="card">
      <p class="text-muted">No experiments found matching your criteria.</p>
    </div>
    {% endif %}
  </div>
</div>

<script>
function applyFacets() {
  const params = new URLSearchParams();
  const q = document.querySelector('input[name="q"]').value;
  if (q) params.set('q', q);

  document.querySelectorAll('[data-facet="status"]:checked').forEach(cb => {
    params.append('status', cb.value);
  });
  document.querySelectorAll('[data-facet="tag"]:checked').forEach(cb => {
    params.append('tag', cb.value);
  });

  const metricsRadio = document.querySelector('[data-facet="has_metrics"]:checked');
  if (metricsRadio && metricsRadio.value) {
    params.set('has_metrics', metricsRadio.value);
  }

  const rootOnly = document.querySelector('[data-facet="root_only"]');
  if (rootOnly && rootOnly.checked) {
    params.set('root_only', '1');
  }

  params.set('sort', '{{ sort_by }}');
  params.set('order', '{{ order }}');

  window.location.href = '/search?' + params.toString();
}
</script>
{% endblock %}
