<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>xeen — Wybór sesji</title>
<style>
:root {
  --bg: #0f0f13;
  --surface: #1a1a24;
  --surface2: #24243a;
  --border: #2d2d44;
  --text: #e4e4ef;
  --text2: #8888aa;
  --accent: #7c5cfc;
  --accent2: #5c9cfc;
  --green: #4cda8a;
  --red: #fc5c7c;
  --orange: #fcac5c;
  --radius: 10px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { 
  font-family: 'Inter', -apple-system, sans-serif; 
  background: var(--bg); 
  color: var(--text); 
  min-height: 100vh; 
}

/* ─── Header ─────── */
.header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 24px; border-bottom: 1px solid var(--border);
}
.header h1 { font-size: 20px; font-weight: 700; }
.header h1 span { color: var(--accent); }
.header-actions { display: flex; gap: 12px; }

/* ─── Content ─────── */
.content { 
  padding: 40px 24px; 
  max-width: 1400px; 
  margin: 0 auto; 
}

.page-title {
  text-align: center;
  margin-bottom: 40px;
}
.page-title h2 {
  font-size: 28px;
  margin-bottom: 8px;
}
.page-title p {
  color: var(--text2);
  font-size: 14px;
}

/* ─── Session Grid ─────── */
.sessions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.session-card {
  background: var(--surface);
  border: 2px solid var(--border);
  border-radius: var(--radius);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.session-card:hover {
  border-color: var(--accent);
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(124, 92, 252, 0.2);
}

.session-card .delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(252, 92, 124, 0.85);
  border: none;
  color: white;
  font-size: 14px;
  cursor: pointer;
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: background 0.2s;
  line-height: 1;
}
.session-card:hover .delete-btn {
  display: flex;
}
.session-card .delete-btn:hover {
  background: var(--red);
}

.session-thumbnails {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 2px;
  background: var(--border);
  aspect-ratio: 1;
}

.session-thumbnail {
  background: var(--surface2);
  position: relative;
  overflow: hidden;
}

.session-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.session-thumbnail.empty {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text2);
  font-size: 24px;
}

.session-info {
  padding: 16px;
  background: var(--surface);
}

.session-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 6px;
  color: var(--text);
}

.session-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--text2);
}

/* ─── Toast ─────── */
.toast {
  position: fixed; bottom: 24px; right: 24px;
  background: var(--surface2); border: 1px solid var(--green);
  padding: 12px 20px; border-radius: 8px; font-size: 13px;
  transform: translateY(80px); opacity: 0; transition: all 0.3s;
  z-index: 1000;
}
.toast.show { transform: translateY(0); opacity: 1; }
.toast.error { border-color: var(--red); }

/* ─── Buttons ─────── */
.btn {
  padding: 10px 20px; 
  border: none; 
  border-radius: 8px;
  font-size: 13px; 
  font-weight: 600; 
  cursor: pointer; 
  transition: all 0.2s;
  text-decoration: none;
  display: inline-block;
}
.btn-primary { 
  background: var(--accent); 
  color: white; 
}
.btn-primary:hover { 
  background: #6b4ce8; 
}
.btn-success { 
  background: var(--green); 
  color: #111; 
}
.btn-outline { 
  background: transparent; 
  border: 1px solid var(--border); 
  color: var(--text); 
}
.btn-outline:hover { 
  border-color: var(--accent); 
}

/* ─── Empty state ─────── */
.empty-state { 
  text-align: center; 
  padding: 80px 20px; 
  color: var(--text2); 
}
.empty-state h3 { 
  color: var(--text); 
  margin-bottom: 12px; 
  font-size: 20px;
}
.empty-state p {
  margin-bottom: 24px;
}

/* ─── Spinner ─────── */
.spinner { 
  display: inline-block; 
  width: 40px; 
  height: 40px; 
  border: 4px solid var(--border); 
  border-top-color: var(--accent); 
  border-radius: 50%; 
  animation: spin 0.8s linear infinite;
  margin: 60px auto;
}
@keyframes spin { 
  to { transform: rotate(360deg); } 
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* ─── Trash Sidebar ─────── */
.trash-sidebar {
  position: fixed;
  right: 0; top: 0; bottom: 0;
  width: 260px;
  background: var(--surface);
  border-left: 1px solid var(--border);
  display: flex; flex-direction: column;
  transform: translateX(100%);
  transition: transform 0.3s;
  z-index: 200;
}
.trash-sidebar.open { transform: translateX(0); }
.trash-toggle {
  position: fixed;
  right: 16px; bottom: 80px;
  width: 48px; height: 48px;
  border-radius: 50%;
  background: var(--surface2);
  border: 1px solid var(--border);
  color: var(--text2);
  font-size: 22px;
  cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  z-index: 201;
  transition: all 0.2s;
  box-shadow: 0 4px 12px rgba(0,0,0,.4);
}
.trash-toggle:hover { border-color: var(--red); color: var(--red); }
.trash-toggle .badge {
  position: absolute; top: -4px; right: -4px;
  background: var(--red); color: white;
  font-size: 10px; font-weight: 700;
  width: 18px; height: 18px; border-radius: 50%;
  display: none; align-items: center; justify-content: center;
}
.trash-toggle .badge.show { display: flex; }
.trash-header {
  padding: 16px;
  border-bottom: 1px solid var(--border);
  display: flex; align-items: center; justify-content: space-between;
}
.trash-header h3 { font-size: 14px; font-weight: 600; }
.trash-close {
  background: none; border: none; color: var(--text2);
  cursor: pointer; font-size: 18px; line-height: 1;
}
.trash-close:hover { color: var(--text); }
.trash-list {
  flex: 1; overflow-y: auto;
  padding: 8px;
  display: flex; flex-direction: column; gap: 6px;
}
.trash-item {
  background: var(--surface2);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 10px 12px;
  display: flex; align-items: center; justify-content: space-between;
  gap: 8px;
}
.trash-item-name {
  font-size: 12px; color: var(--text2);
  flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.trash-item-restore {
  background: none; border: 1px solid var(--border);
  color: var(--text2); border-radius: 6px;
  padding: 3px 8px; font-size: 11px; cursor: pointer;
  white-space: nowrap;
}
.trash-item-restore:hover { border-color: var(--green); color: var(--green); }
.trash-item-purge {
  background: none; border: none;
  color: var(--text2); cursor: pointer; font-size: 14px;
}
.trash-item-purge:hover { color: var(--red); }
.trash-empty-msg {
  text-align: center; padding: 40px 16px;
  color: var(--text2); font-size: 13px;
}
.trash-footer {
  padding: 12px 16px;
  border-top: 1px solid var(--border);
}
.btn-danger {
  background: var(--red); color: white;
  width: 100%;
}
.btn-danger:hover { background: #e04060; }
</style>
</head>
<body>

<div class="header">
  <h1><span>xeen</span> capture</h1>
  <div class="header-actions">
    <a href="/capture" class="btn btn-success">📸 Nowe nagranie</a>
  </div>
</div>

<!-- Trash toggle button -->
<button class="trash-toggle" onclick="toggleTrash()" title="Kosz">
  🗑
  <span class="badge" id="trashBadge"></span>
</button>

<!-- Trash sidebar -->
<div class="trash-sidebar" id="trashSidebar">
  <div class="trash-header">
    <h3>🗑 Kosz</h3>
    <button class="trash-close" onclick="toggleTrash()">✕</button>
  </div>
  <div class="trash-list" id="trashList">
    <div class="trash-empty-msg">Kosz jest pusty</div>
  </div>
  <div class="trash-footer">
    <button class="btn btn-danger" onclick="emptyTrash()">Opróżnij kosz</button>
  </div>
</div>

<div class="content">
  <div class="page-title">
    <h2>Wybierz sesję</h2>
    <p>Kliknij na sesję aby rozpocząć edycję i eksport</p>
  </div>

  <div style="display:flex;gap:12px;margin-bottom:24px;flex-wrap:wrap">
    <a href="/capture" style="flex:1;min-width:200px;display:flex;align-items:center;justify-content:center;gap:10px;
       padding:20px 24px;border-radius:12px;background:var(--accent);color:var(--bg);font-size:16px;font-weight:600;
       text-decoration:none;transition:all .2s;border:2px solid var(--accent)">
      🎥 Nagraj ekran
    </a>
    <label style="flex:1;min-width:200px;display:flex;align-items:center;justify-content:center;gap:10px;
       padding:20px 24px;border-radius:12px;background:var(--surface2);color:var(--text);font-size:16px;font-weight:600;
       cursor:pointer;transition:all .2s;border:2px solid var(--border)">
      📂 Wrzuć screeny
      <input type="file" multiple accept="image/*" style="display:none" onchange="uploadNewSession(this.files)">
    </label>
  </div>

  <div id="sessionsContainer">
    <div class="loading-container">
      <div class="spinner"></div>
    </div>
  </div>
</div>

<script>
// ─── API Helper ───────────────────────────────────────────────────────────
async function api(path, opts = {}) {
  const res = await fetch('/api' + path, {
    headers: { 'Content-Type': 'application/json' },
    ...opts,
    body: opts.body ? JSON.stringify(opts.body) : undefined,
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

// ─── Load Sessions ────────────────────────────────────────────────────────
async function loadSessions() {
  const container = document.getElementById('sessionsContainer');
  
  try {
    const sessions = await api('/sessions');
    
    if (sessions.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <h3>Brak sesji</h3>
          <p>Rozpocznij nowe nagranie aby utworzyć pierwszą sesję</p>
          <a href="/capture" class="btn btn-primary">📸 Rozpocznij nagranie</a>
        </div>
      `;
      return;
    }

    // Take last 9 sessions
    const recentSessions = sessions.slice(0, 9);
    
    // Load thumbnails for each session
    const sessionsWithThumbs = await Promise.all(
      recentSessions.map(async (session) => {
        try {
          const thumbs = await api(`/sessions/${session.name}/thumbnails?limit=9`);
          return { ...session, thumbnails: thumbs.thumbnails };
        } catch (e) {
          console.error(`Failed to load thumbnails for ${session.name}:`, e);
          return { ...session, thumbnails: [] };
        }
      })
    );

    renderSessionsGrid(sessionsWithThumbs);
  } catch (e) {
    container.innerHTML = `
      <div class="empty-state">
        <h3>Błąd ładowania sesji</h3>
        <p>${e.message}</p>
      </div>
    `;
  }
}

// ─── Render Sessions Grid ─────────────────────────────────────────────────
function renderSessionsGrid(sessions) {
  const container = document.getElementById('sessionsContainer');
  const grid = document.createElement('div');
  grid.className = 'sessions-grid';

  sessions.forEach(session => {
    const card = document.createElement('div');
    card.className = 'session-card';
    card.onclick = () => window.location.href = `/session/${session.name}`;

    // Delete button
    const delBtn = document.createElement('button');
    delBtn.className = 'delete-btn';
    delBtn.title = 'Usuń sesję';
    delBtn.textContent = '✕';
    delBtn.onclick = (e) => {
      e.stopPropagation();
      deleteSession(session.name, card);
    };
    card.appendChild(delBtn);

    // Create 3x3 thumbnail grid
    const thumbsGrid = document.createElement('div');
    thumbsGrid.className = 'session-thumbnails';

    // Fill with up to 9 thumbnails
    for (let i = 0; i < 9; i++) {
      const thumbDiv = document.createElement('div');
      thumbDiv.className = 'session-thumbnail';

      if (i < session.thumbnails.length) {
        const img = document.createElement('img');
        img.src = session.thumbnails[i].thumb_url || session.thumbnails[i].url;
        img.alt = `Frame ${session.thumbnails[i].index}`;
        img.loading = 'lazy';
        thumbDiv.appendChild(img);
      } else {
        thumbDiv.classList.add('empty');
        thumbDiv.textContent = '·';
      }

      thumbsGrid.appendChild(thumbDiv);
    }

    // Session info
    const info = document.createElement('div');
    info.className = 'session-info';
    
    const name = document.createElement('div');
    name.className = 'session-name';
    name.textContent = session.name;
    
    const meta = document.createElement('div');
    meta.className = 'session-meta';
    meta.innerHTML = `
      <span>${session.frame_count} klatek</span>
      <span>${session.duration.toFixed(1)}s</span>
    `;

    info.appendChild(name);
    info.appendChild(meta);

    card.appendChild(thumbsGrid);
    card.appendChild(info);
    grid.appendChild(card);
  });

  container.innerHTML = '';
  container.appendChild(grid);
}

// ─── Trash ───────────────────────────────────────────────────────────────
const trash = [];  // { name, meta, cardEl }

function toggleTrash() {
  document.getElementById('trashSidebar').classList.toggle('open');
}

function updateTrashBadge() {
  const badge = document.getElementById('trashBadge');
  badge.textContent = trash.length;
  badge.classList.toggle('show', trash.length > 0);
}

function renderTrashList() {
  const list = document.getElementById('trashList');
  if (trash.length === 0) {
    list.innerHTML = '<div class="trash-empty-msg">Kosz jest pusty</div>';
    return;
  }
  list.innerHTML = '';
  trash.forEach((item, i) => {
    const el = document.createElement('div');
    el.className = 'trash-item';
    el.innerHTML = `
      <span class="trash-item-name" title="${item.name}">${item.name}</span>
      <button class="trash-item-restore" onclick="restoreSession(${i})">↩ Przywróć</button>
      <button class="trash-item-purge" onclick="purgeSession(${i})" title="Usuń trwale">✕</button>
    `;
    list.appendChild(el);
  });
}

async function deleteSession(name, cardEl) {
  // Animate card out
  cardEl.style.transition = 'opacity 0.25s, transform 0.25s';
  cardEl.style.opacity = '0';
  cardEl.style.transform = 'scale(0.9)';
  setTimeout(() => {
    cardEl.remove();
    const grid = document.querySelector('.sessions-grid');
    if (grid && grid.children.length === 0) loadSessions();
  }, 250);

  // Move to trash (soft delete — keep in memory, purge on demand)
  trash.unshift({ name, cardEl });
  updateTrashBadge();
  renderTrashList();
  toast(`Sesja przeniesiona do kosza — ↩ przywróć w koszu`);
}

async function restoreSession(i) {
  const item = trash.splice(i, 1)[0];
  updateTrashBadge();
  renderTrashList();
  // Reload grid to show restored card
  loadSessions();
  toast(`Sesja "${item.name}" przywrócona`);
}

async function purgeSession(i) {
  const item = trash.splice(i, 1)[0];
  try {
    await fetch(`/api/sessions/${item.name}`, { method: 'DELETE' });
  } catch (e) { /* ignore */ }
  updateTrashBadge();
  renderTrashList();
  toast(`Sesja "${item.name}" trwale usunięta`);
}

async function emptyTrash() {
  await Promise.all(trash.map(item =>
    fetch(`/api/sessions/${item.name}`, { method: 'DELETE' }).catch(() => {})
  ));
  trash.length = 0;
  updateTrashBadge();
  renderTrashList();
  toast('Kosz opróżniony');
}

// ─── Upload New Session ──────────────────────────────────────────────────
async function uploadNewSession(files) {
  if (!files || files.length === 0) return;
  toast(`Wgrywanie ${files.length} plików...`);
  const form = new FormData();
  for (const f of files) form.append('files', f);
  try {
    const res = await fetch('/api/sessions/upload', { method: 'POST', body: form });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    toast(`Sesja "${data.name}" utworzona z ${data.frame_count} klatkami`);
    window.location.href = `/session/${data.name}/tab/select`;
  } catch (e) {
    toast('Błąd uploadu: ' + e.message, true);
  }
}

// ─── Toast ────────────────────────────────────────────────────────────────
function toast(msg, isError = false) {
  let t = document.getElementById('toast');
  if (!t) {
    t = document.createElement('div');
    t.id = 'toast';
    document.body.appendChild(t);
  }
  t.className = 'toast' + (isError ? ' error' : '');
  t.textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 2500);
}

// ─── Init ─────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  loadSessions();
});
</script>
<div class="toast" id="toast"></div>

</body>
</html>
