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

{% block extra_css %}
{{ pygments_css }}

/* Tabs */
.tab-bar { display: flex; gap: 0; border-bottom: 2px solid var(--border); margin-bottom: 16px; }
.tab-btn {
  padding: 8px 20px;
  font-size: 13px;
  font-weight: 600;
  color: var(--muted);
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
  cursor: pointer;
  transition: color 0.15s, border-color 0.15s;
}
.tab-btn:hover { color: var(--text); }
.tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); }
.tab-panel { display: none; }
.tab-panel.active { display: block; }

/* File browser (VS Code style) */
.file-browser {
  display: flex;
  border: 1px solid var(--border);
  border-radius: 8px;
  background: var(--surface);
  min-height: 500px;
  --sidebar-width: 260px;
  --splitter-width: 8px;
}
.file-sidebar {
  width: var(--sidebar-width);
  min-width: var(--sidebar-width);
  border-right: 1px solid var(--border);
  overflow-y: auto;
  max-height: 600px;
  font-family: var(--mono);
  font-size: 13px;
  flex-shrink: 0;
  transition: width 0.2s, min-width 0.2s, padding 0.2s, border 0.2s;
}
.file-sidebar.collapsed { width: 0; min-width: 0; overflow: hidden; border-right: none; }
.file-splitter {
  width: var(--splitter-width);
  flex-shrink: 0;
  cursor: col-resize;
  background: transparent;
  position: relative;
}
.file-splitter::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  width: 1px;
  transform: translateX(-50%);
  background: var(--border);
}
.file-browser.resizing, .file-browser.resizing * { cursor: col-resize !important; user-select: none; }
.file-browser.sidebar-collapsed .file-splitter { display: none; }
.file-sidebar-header {
  padding: 10px 12px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: var(--muted);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.file-item {
  display: flex;
  align-items: center;
  padding: 3px 8px;
  cursor: pointer;
  color: var(--text);
  border-left: 2px solid transparent;
}
.file-item:hover { background: var(--primary-light); }
.file-item.active { background: var(--primary-light); border-left-color: var(--primary); }
.file-item.dir { font-weight: 600; color: var(--muted); cursor: default; }
.file-item.binary { opacity: 0.5; cursor: default; }
.file-item .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-item .size { font-size: 11px; color: var(--muted); margin-left: 8px; }

.file-content-area {
  flex: 1;
  min-width: 0;
  overflow: auto;
  max-height: 600px;
  display: flex;
  flex-direction: column;
}
.file-content-header {
  padding: 8px 12px;
  font-size: 12px;
  font-family: var(--mono);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fafbfc;
  flex-shrink: 0;
}
.file-content-header .file-path { color: var(--text); font-weight: 600; }
.file-content-header .file-meta-inline { color: var(--muted); display: flex; gap: 12px; align-items: center; }
.file-content-body {
  flex: 1;
  overflow: auto;
  padding: 0;
}
.file-content-body .highlight { border-radius: 0; margin: 0; }
.file-content-body .highlight pre { margin: 0; padding: 12px; overflow-x: auto; font-size: 12px; line-height: 1.6; }
.file-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--muted);
  font-size: 14px;
}
.truncation-warning {
  background: #fef3c7; border-bottom: 1px solid #f59e0b;
  padding: 6px 12px; font-size: 12px; color: #92400e; flex-shrink: 0;
}
.binary-notice {
  display: flex; align-items: center; justify-content: center;
  height: 100%; color: var(--muted); font-size: 14px;
}

/* Toolbar buttons */
.icon-btn {
  background: none;
  border: 1px solid var(--border);
  border-radius: 4px;
  padding: 3px 8px;
  cursor: pointer;
  font-size: 12px;
  color: var(--muted);
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.icon-btn:hover { background: var(--primary-light); color: var(--text); }

/* Run output full width */
.run-output-card pre {
  max-height: 400px;
  overflow-y: auto;
}
{% endblock %}

{% block content %}
<div class="breadcrumb"><a href="/">Dashboard</a> / <a href="/experiments">Experiments</a> / {{ exp_id }}</div>

<div class="flex items-center gap-2 mb-2">
  <h1>Experiment {{ exp_id }}</h1>
  <span class="badge" style="background: {{ exp.status.value | status_color }}; font-size: 14px;">{{ exp.status.value }}</span>
</div>

<!-- Tab bar -->
<div class="tab-bar">
  <button class="tab-btn active" data-tab="overview">Overview</button>
  <button class="tab-btn" data-tab="files">Files</button>
</div>

<!-- Overview tab -->
<div id="tab-overview" class="tab-panel active">
  <div class="grid grid-2">
    <!-- Left column: metadata -->
    <div>
      <div class="card">
        <h3>Details</h3>
        <table>
          <tr><td style="width: 120px; font-weight: 600;">Status</td><td><span class="badge" style="background: {{ exp.status.value | status_color }};">{{ exp.status.value }}</span></td></tr>
          <tr><td style="font-weight: 600;">Created</td><td>{{ exp.created_at.isoformat()[:19] }}</td></tr>
          {% if exp.completed_at %}
          <tr><td style="font-weight: 600;">Completed</td><td>{{ exp.completed_at.isoformat()[:19] }}</td></tr>
          {% endif %}
          <tr>
            <td style="font-weight: 600;">Parents</td>
            <td>
              {% for p in exp.parents %}
              <a href="/experiments/{{ p }}" class="text-mono">{{ p }}</a>{% if not loop.last %}, {% endif %}
              {% endfor %}
              {% if not exp.parents %}<span class="text-muted">none</span>{% endif %}
            </td>
          </tr>
          <tr>
            <td style="font-weight: 600;">Children</td>
            <td>
              {% for c in children %}
              <a href="/experiments/{{ c }}" class="text-mono">{{ c }}</a>{% if not loop.last %}, {% endif %}
              {% endfor %}
              {% if not children %}<span class="text-muted">none</span>{% endif %}
            </td>
          </tr>
          <tr>
            <td style="font-weight: 600;">Tags</td>
            <td>
              {% for t in exp.tags %}
              <span style="background: #e2e5ea; padding: 1px 6px; border-radius: 4px; font-size: 12px;">{{ t }}</span>
              {% endfor %}
              {% if not exp.tags %}<span class="text-muted">none</span>{% endif %}
            </td>
          </tr>
        </table>
      </div>

      <div class="card">
        <h3>Hypothesis</h3>
        <p>{{ exp.hypothesis }}</p>
      </div>

      <div class="card">
        <h3>Method</h3>
        <p>{{ exp.method }}</p>
      </div>

      {% if exp.failure_reason %}
      <div class="card" style="border-left: 4px solid #ef4444;">
        <h3>Failure Reason</h3>
        <p>{{ exp.failure_reason }}</p>
      </div>
      {% endif %}
    </div>

    <!-- Right column: metrics + sessions -->
    <div>
      {% if exp.metrics %}
      <div class="card">
        <h3>Metrics</h3>
        <table>
          <thead><tr><th>Split</th><th>Metric</th><th>Value</th></tr></thead>
          <tbody>
            {% for split, kvs in exp.metrics.items() %}
              {% for key, val in kvs.items() %}
              <tr>
                <td class="text-mono">{{ split }}</td>
                <td class="text-mono">{{ key }}</td>
                <td class="text-mono" style="font-weight: 600;">{{ "%.6f" | format(val) if val is number else val }}</td>
              </tr>
              {% endfor %}
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}

      {% if runtime_rows %}
      <div class="card">
        <h3>Runtime Costs</h3>
        <table>
          <thead><tr><th>Stage</th><th>Attempts</th><th>Total (s)</th><th>Last (s)</th><th>Status</th></tr></thead>
          <tbody>
            {% for row in runtime_rows %}
            <tr>
              <td class="text-mono" style="font-weight: 600;">{{ row.stage }}</td>
              <td class="text-mono">{{ row.attempts }}</td>
              <td class="text-mono">{{ "%.2f" | format(row.seconds_total) }}</td>
              <td class="text-mono">{{ "%.2f" | format(row.seconds_last) }}</td>
              <td>{{ row.last_status }}</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
        <p class="text-muted text-sm" style="margin-top: 10px;">Total runtime: {{ runtime_total_seconds | human_duration }}</p>
      </div>
      {% endif %}

      <div class="card">
        <h3>Sessions</h3>
        {% if sessions %}
        <table>
          <thead><tr><th>Stage</th><th>Size</th><th></th></tr></thead>
          <tbody>
            {% for s in sessions %}
            <tr>
              <td style="font-weight: 600;">{{ s.stage }}</td>
              <td class="text-muted text-sm">{{ "%.0f" | format(s.size_kb) }} KB</td>
              <td><a href="/experiments/{{ exp_id }}/sessions/{{ s.stage }}">View session</a></td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
        {% else %}
        <p class="text-muted">No session recordings found.</p>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Run output: full width -->
  {% if run_output %}
  <div class="card run-output-card">
    <h3>Run Output</h3>
    <details>
      <summary>Show output ({{ run_output | length }} chars)</summary>
      <pre>{{ run_output }}</pre>
    </details>
  </div>
  {% endif %}

  <!-- Findings: full width -->
  {% if findings %}
  <div class="card mt-2">
    <h3>Findings</h3>
    <div class="md-content">{{ findings | md }}</div>
  </div>
  {% endif %}
</div>

<!-- Files tab -->
<div id="tab-files" class="tab-panel">
  <div class="file-browser" id="file-browser">
    <div class="file-sidebar" id="file-sidebar">
      <div class="file-sidebar-header">
        <span>Explorer</span>
      </div>
      {% if file_entries %}
        {% for e in file_entries %}
        <div class="file-item{% if e.is_dir %} dir{% elif e.is_binary and not e.is_image %} binary{% endif %}"
             style="padding-left: {{ 10 + e.depth * 16 }}px;"
             {% if not e.is_dir and (not e.is_binary or e.is_image) %}
             data-path="{{ e.relative_path }}"
             onclick="openFile(this)"
             {% endif %}>
          <span class="name" title="{{ e.relative_path }}">{% if e.is_dir %}{{ e.name }}/{% else %}{{ e.name }}{% endif %}</span>
          {% if not e.is_dir %}
          <span class="size">{{ e.size_bytes | filesize }}</span>
          {% endif %}
        </div>
        {% endfor %}
      {% else %}
        <div style="padding: 16px; color: var(--muted); font-size: 13px;">No files found.</div>
      {% endif %}
    </div>
    <div class="file-splitter" id="file-splitter" role="separator" aria-orientation="vertical" aria-label="Drag to resize the file explorer"></div>
    <div class="file-content-area" id="file-content-area">
      <div class="file-placeholder" id="file-placeholder">
        Select a file to view its contents
      </div>
      <div id="file-viewer" style="display: none; flex-direction: column; height: 100%;">
        <div class="file-content-header">
          <span class="file-path" id="viewer-path"></span>
          <div class="file-meta-inline">
            <span id="viewer-lang"></span>
            <span id="viewer-size"></span>
            <button class="icon-btn" id="btn-expand" onclick="toggleSidebar()" title="Toggle sidebar">
              <span id="expand-icon">&#x2194;</span> <span id="expand-label">Expand</span>
            </button>
          </div>
        </div>
        <div id="viewer-truncation" class="truncation-warning" style="display: none;"></div>
        <div class="file-content-body" id="viewer-body"></div>
      </div>
    </div>
  </div>
</div>

<script>
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
  });
});

// File browser
const expId = '{{ exp_id }}';
const fileBrowser = document.getElementById('file-browser');
const fileSplitter = document.getElementById('file-splitter');
const fileSidebar = document.getElementById('file-sidebar');
let activeFileEl = null;
let sidebarCollapsed = false;
let sidebarWidth = 260;
let resizingSidebar = false;
const SIDEBAR_MIN_WIDTH = 180;
const SIDEBAR_MAX_WIDTH = 520;
const SIDEBAR_WIDTH_STORAGE_KEY = 'abreka:file-browser-width:' + expId;

function loadSidebarWidth() {
  try {
    const value = window.localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY);
    if (value === null) return null;
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) ? parsed : null;
  } catch (_) {
    return null;
  }
}

function saveSidebarWidth(width) {
  try {
    window.localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(width));
  } catch (_) {}
}

function setSidebarWidth(width) {
  sidebarWidth = Math.max(SIDEBAR_MIN_WIDTH, Math.min(SIDEBAR_MAX_WIDTH, width));
  fileBrowser.style.setProperty('--sidebar-width', sidebarWidth + 'px');
  saveSidebarWidth(sidebarWidth);
}

function beginSidebarResize(event) {
  if (sidebarCollapsed) return;
  resizingSidebar = true;
  fileBrowser.classList.add('resizing');
  document.body.style.userSelect = 'none';
  document.body.style.cursor = 'col-resize';
  if (fileSplitter.setPointerCapture && event.pointerId !== undefined) {
    try { fileSplitter.setPointerCapture(event.pointerId); } catch (_) {}
  }
  event.preventDefault();
}

function updateSidebarResize(event) {
  if (!resizingSidebar || sidebarCollapsed) return;
  const rect = fileBrowser.getBoundingClientRect();
  setSidebarWidth(event.clientX - rect.left);
}

function endSidebarResize(event) {
  if (!resizingSidebar) return;
  resizingSidebar = false;
  fileBrowser.classList.remove('resizing');
  document.body.style.userSelect = '';
  document.body.style.cursor = '';
  if (fileSplitter.releasePointerCapture && event && event.pointerId !== undefined) {
    try { fileSplitter.releasePointerCapture(event.pointerId); } catch (_) {}
  }
}

if (fileSplitter) {
  fileSplitter.addEventListener('pointerdown', beginSidebarResize);
  document.addEventListener('pointermove', updateSidebarResize);
  document.addEventListener('pointerup', endSidebarResize);
  document.addEventListener('pointercancel', endSidebarResize);
}

const savedSidebarWidth = loadSidebarWidth();
if (savedSidebarWidth !== null) {
  sidebarWidth = savedSidebarWidth;
}
setSidebarWidth(sidebarWidth);

function openFile(el) {
  const path = el.dataset.path;
  if (!path) return;

  // Mark active
  if (activeFileEl) activeFileEl.classList.remove('active');
  el.classList.add('active');
  activeFileEl = el;

  // Fetch content
  const viewer = document.getElementById('file-viewer');
  const placeholder = document.getElementById('file-placeholder');
  const body = document.getElementById('viewer-body');

  document.getElementById('viewer-path').textContent = path;
  body.innerHTML = '<div class="file-placeholder">Loading...</div>';
  placeholder.style.display = 'none';
  viewer.style.display = 'flex';

  fetch('/api/experiments/' + expId + '/file/' + path)
    .then(r => r.json())
    .then(data => {
      if (data.error) {
        body.innerHTML = '<div class="file-placeholder">' + data.error + '</div>';
        return;
      }
      document.getElementById('viewer-lang').textContent = data.language;
      document.getElementById('viewer-size').textContent = formatSize(data.original_size);

      const trunc = document.getElementById('viewer-truncation');
      if (data.truncated) {
        trunc.textContent = 'File truncated — showing first 100 KB of ' + formatSize(data.original_size) + '.';
        trunc.style.display = 'block';
      } else {
        trunc.style.display = 'none';
      }

      if (data.is_image) {
        const img = document.createElement('img');
        img.src = data.raw_url;
        img.alt = path;
        img.style.maxWidth = '100%';
        img.style.height = 'auto';
        img.style.display = 'block';
        body.innerHTML = '';
        const wrap = document.createElement('div');
        wrap.style.padding = '12px';
        wrap.appendChild(img);
        body.appendChild(wrap);
      } else if (data.is_binary) {
        body.innerHTML = '<div class="binary-notice">Binary file (' + formatSize(data.original_size) + ') — cannot be displayed.</div>';
      } else {
        body.innerHTML = data.highlighted_html;
      }
    })
    .catch(() => {
      body.innerHTML = '<div class="file-placeholder">Failed to load file.</div>';
    });
}

function toggleSidebar() {
  sidebarCollapsed = !sidebarCollapsed;
  fileSidebar.classList.toggle('collapsed', sidebarCollapsed);
  fileBrowser.classList.toggle('sidebar-collapsed', sidebarCollapsed);
  document.getElementById('expand-label').textContent = sidebarCollapsed ? 'Show files' : 'Expand';
  if (!sidebarCollapsed) setSidebarWidth(sidebarWidth);
}

function formatSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / 1048576).toFixed(1) + ' MB';
}
</script>
{% endblock %}
