<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Scrylo{% if title %} — {{ title }}{% endif %}</title>

  <!-- Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com"/>
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Bricolage+Grotesque:wght@400;600;800&family=DM+Sans:ital,wght@0,300;0,400;0,500;1,400&display=swap" rel="stylesheet"/>

  <!-- Tailwind CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            mono:    ['JetBrains Mono', 'monospace'],
            display: ['Bricolage Grotesque', 'sans-serif'],
            sans:    ['DM Sans', 'sans-serif'],
          },
        }
      }
    }
  </script>

  <!-- HTMX -->
  <script src="https://unpkg.com/htmx.org@1.9.12"></script>

  <style>
    /* ── CSS variables — single source of truth ─────────────────── */
    :root {
      --bg:           #0b0a08;
      --surface:      #0e0c09;
      --card:         #121008;
      --border:       #1e1c14;
      --border-dim:   #151208;
      --accent:       #f59e0b;
      --accent-glow:  rgba(245,158,11,0.12);
      --accent-ring:  rgba(245,158,11,0.25);
      --green:        #4ade80;
      --green-dim:    rgba(74,222,128,0.1);

      /* Text hierarchy — the fix: no more near-invisible colours */
      --text-primary:   #f0ebe0;   /* headings, names, important values */
      --text-body:      #d4cfc5;   /* normal body text, table cells */
      --text-muted:     #8a7c60;   /* descriptions, secondary info */
      --text-dim:       #5a5040;   /* nav labels at rest, placeholders */
      --text-faint:     #3a3428;   /* borders-as-text, timestamps, very secondary */
      --text-invisible: #2a261c;   /* section dividers, version numbers */
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }
    html { scroll-behavior: smooth; }
    body {
      background: var(--bg);
      color: var(--text-body);
      font-family: 'DM Sans', sans-serif;
      min-height: 100vh;
      display: flex;
    }

    /* Subtle scanline overlay */
    body::after {
      content: '';
      position: fixed; inset: 0; pointer-events: none; z-index: 9999;
      background: repeating-linear-gradient(
        0deg,
        transparent,
        transparent 2px,
        rgba(0,0,0,0.025) 2px,
        rgba(0,0,0,0.025) 4px
      );
    }

    /* ── Sidebar ─────────────────────────────────────────────────── */
    .sidebar {
      width: 220px;
      flex-shrink: 0;
      background: var(--surface);
      border-right: 1px solid var(--border);
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      position: fixed;
      top: 0; left: 0; bottom: 0;
    }

    .main-content {
      margin-left: 220px;
      flex: 1;
      min-height: 100vh;
    }

    /* ── Nav items ───────────────────────────────────────────────── */
    .nav-item {
      display: flex;
      align-items: center;
      gap: 0.7rem;
      padding: 0.6rem 0.85rem;
      font-family: 'DM Sans', sans-serif;
      font-size: 0.82rem;
      color: var(--text-dim);          /* #5a5040 — readable, not invisible */
      text-decoration: none;
      border-radius: 7px;
      margin: 0.05rem 0.5rem;
      transition: all 0.15s;
      cursor: pointer;
    }
    .nav-item:hover {
      color: var(--text-body);         /* #d4cfc5 on hover */
      background: #151208;
    }
    .nav-item.active {
      color: var(--accent);            /* amber when active */
      background: var(--accent-glow);
    }
    .nav-item .nav-icon {
      font-size: 0.9rem;
      width: 18px;
      text-align: center;
      flex-shrink: 0;
    }
    .nav-item .nav-week {
      margin-left: auto;
      font-family: 'JetBrains Mono', monospace;
      font-size: 0.58rem;
      color: var(--text-faint);
    }
    .nav-item.active .nav-week { color: rgba(245,158,11,0.45); }

    /* Nav section dividers */
    .nav-divider {
      padding: 0.9rem 1.1rem 0.3rem;
      font-family: 'JetBrains Mono', monospace;
      font-size: 0.58rem;
      color: var(--text-invisible);
      letter-spacing: 0.12em;
      text-transform: uppercase;
    }

    /* ── Page header ─────────────────────────────────────────────── */
    .page-header {
      border-bottom: 1px solid var(--border);
      padding: 1.25rem 2rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: var(--surface);
    }
    .page-title {
      font-family: 'Bricolage Grotesque', sans-serif;
      font-size: 0.95rem;
      font-weight: 700;
      color: var(--text-primary);      /* #f0ebe0 — clearly readable */
    }
    .page-title span { color: var(--accent); }
    .page-subtitle {
      font-family: 'JetBrains Mono', monospace;
      font-size: 0.62rem;
      color: var(--text-dim);          /* #5a5040 — visible but secondary */
      margin-top: 0.2rem;
    }

    /* ── Stat card ───────────────────────────────────────────────── */
    .stat-card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 1.25rem 1.5rem;
    }
    .stat-label {
      font-family: 'JetBrains Mono', monospace;
      font-size: 0.6rem;
      color: var(--text-dim);          /* was #3a3428 — now readable */
      letter-spacing: 0.1em;
      text-transform: uppercase;
      margin-bottom: 0.5rem;
    }
    .stat-value {
      font-family: 'Bricolage Grotesque', sans-serif;
      font-size: 2rem;
      font-weight: 800;
      color: var(--text-primary);
      letter-spacing: -0.02em;
    }

    /* ── Coming-soon card ────────────────────────────────────────── */
    .coming-soon {
      border: 1px dashed var(--border);
      border-radius: 8px;
      padding: 3rem 2rem;
      text-align: center;
      max-width: 480px;
      margin: 3rem auto;
    }

    /* ── Section headers ─────────────────────────────────────────── */
    .section-label {
      font-family: 'JetBrains Mono', monospace;
      font-size: 0.62rem;
      color: var(--text-faint);        /* #3a3428 — dimmer but only for // dividers */
      letter-spacing: 0.1em;
      text-transform: uppercase;
      margin-bottom: 1rem;
    }

    /* ── HTMX loading indicator ──────────────────────────────────── */
    .htmx-indicator { display: none; }
    .htmx-request .htmx-indicator { display: inline-block; }

    /* ── Scrollbar ───────────────────────────────────────────────── */
    ::-webkit-scrollbar { width: 4px; }
    ::-webkit-scrollbar-track { background: var(--bg); }
    ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
    ::-webkit-scrollbar-thumb:hover { background: #2a261c; }

    /* ── Status dot ──────────────────────────────────────────────── */
    .status-dot {
      width: 6px; height: 6px;
      border-radius: 50%;
      display: inline-block;
      flex-shrink: 0;
    }
  </style>
</head>
<body>

<!-- ── SIDEBAR ──────────────────────────────────────────────── -->
<aside class="sidebar">

  <!-- Logo -->
  <div style="padding:1.2rem 1.2rem 1rem;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:0.65rem;">
    <div style="width:28px;height:28px;background:var(--accent);border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:0.85rem;flex-shrink:0;box-shadow:0 0 14px rgba(245,158,11,0.25);">⚡</div>
    <div>
      <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.88rem;font-weight:800;color:var(--text-primary);letter-spacing:-0.01em;">Scrylo</div>
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.54rem;color:var(--text-invisible);letter-spacing:0.06em;">v0.1.0 · local</div>
    </div>
  </div>

  <!-- Nav -->
  <nav style="flex:1;padding:0.75rem 0;overflow-y:auto;">

    <div class="nav-divider">// pipeline</div>

    <a href="/" class="nav-item {% if active_page == 'dashboard' %}active{% endif %}">
      <span class="nav-icon">⬡</span>
      Dashboard
    </a>

    <a href="/leads" class="nav-item {% if active_page == 'leads' %}active{% endif %}">
      <span class="nav-icon">🔍</span>
      Lead Finder
      <span class="nav-week">W3</span>
    </a>

    <a href="/pitch" class="nav-item {% if active_page == 'pitch' %}active{% endif %}">
      <span class="nav-icon">✍️</span>
      Pitch Writer
      <span class="nav-week">W5</span>
    </a>

    <a href="/send" class="nav-item {% if active_page == 'send' %}active{% endif %}">
      <span class="nav-icon">🚀</span>
      Send Queue
      <span class="nav-week">W6</span>
    </a>

    <div class="nav-divider" style="margin-top:0.5rem;">// system</div>

    <a href="/settings" class="nav-item {% if active_page == 'settings' %}active{% endif %}">
      <span class="nav-icon">⚙</span>
      Settings
    </a>

  </nav>

  <!-- System status footer -->
  <div style="padding:1rem 1.2rem;border-top:1px solid var(--border);">
    <div style="font-family:'JetBrains Mono',monospace;font-size:0.58rem;color:var(--text-invisible);letter-spacing:0.1em;margin-bottom:0.6rem;">// status</div>
    <div style="display:flex;flex-direction:column;gap:0.35rem;">

      <div style="display:flex;align-items:center;justify-content:space-between;">
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);">model</span>
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;
          color:{% if model_ready %}var(--green){% else %}var(--text-dim){% endif %};">
          {% if model_ready %}ready{% else %}not loaded{% endif %}
        </span>
      </div>

      <div style="display:flex;align-items:center;justify-content:space-between;">
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);">db</span>
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--green);">sqlite ✓</span>
      </div>

      <div style="display:flex;align-items:center;justify-content:space-between;">
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);">leads</span>
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-body);">{{ total_leads }}</span>
      </div>

    </div>
  </div>

</aside>

<!-- ── MAIN CONTENT ──────────────────────────────────────────── -->
<main class="main-content">

  <!-- Dependency warning bar — shows install buttons for any missing dep -->
  {% if deps_missing %}
  <div id="depsWarningBar" style="background:rgba(245,158,11,0.07);border-bottom:1px solid rgba(245,158,11,0.2);padding:0.7rem 1.5rem;display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
    <span style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--accent);flex-shrink:0;">⚠ setup needed</span>
    <div style="flex:1;display:flex;flex-wrap:wrap;gap:0.5rem;">
      {% for key, msg in deps_missing.items() %}
      <button onclick="openInstallModal('{{ key }}')" style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.3);color:var(--accent);padding:0.25rem 0.65rem;border-radius:4px;cursor:pointer;transition:all 0.15s;white-space:nowrap;" onmouseover="this.style.background='rgba(245,158,11,0.18)'" onmouseout="this.style.background='rgba(245,158,11,0.1)'">
        Install {{ key.replace('_', ' ') }} →
      </button>
      {% endfor %}
    </div>
    <button onclick="document.getElementById('depsWarningBar').style.display='none'" style="background:none;border:none;color:var(--text-faint);cursor:pointer;font-size:0.9rem;padding:0 0.25rem;">✕</button>
  </div>
  {% endif %}

  {% block content %}{% endblock %}
</main>

<!-- ── Install modal ── -->
<div id="installModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.65);z-index:1000;align-items:center;justify-content:center;">
  <div style="background:var(--card);border:1px solid var(--border);border-radius:12px;padding:1.75rem;max-width:520px;width:94%;box-shadow:0 24px 64px rgba(0,0,0,0.5);display:flex;flex-direction:column;gap:1.1rem;">

    <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;">
      <div>
        <div id="installModalTitle" style="font-family:'Bricolage Grotesque',sans-serif;font-size:1.05rem;font-weight:800;color:var(--text-primary);margin-bottom:0.3rem;"></div>
        <div id="installModalSize"  style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--accent);"></div>
      </div>
      <button onclick="closeInstallModal()" style="background:none;border:none;color:var(--text-faint);cursor:pointer;font-size:1rem;padding:0.1rem 0.3rem;flex-shrink:0;">✕</button>
    </div>

    <div id="installModalNote" style="font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--text-muted);line-height:1.7;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:0.85rem 1rem;"></div>

    <div id="installConfirmRow" style="display:flex;gap:0.75rem;">
      <button id="installYesBtn" onclick="startInstall()" style="flex:1;background:var(--accent);color:#0b0a08;font-family:'Bricolage Grotesque',sans-serif;font-size:0.9rem;font-weight:800;padding:0.65rem 1rem;border:none;border-radius:7px;cursor:pointer;transition:all 0.15s;" onmouseover="this.style.background='#fbbf24'" onmouseout="this.style.background='var(--accent)'">
        Yes, install it
      </button>
      <button onclick="closeInstallModal()" style="flex:1;background:transparent;color:var(--text-muted);font-family:'Bricolage Grotesque',sans-serif;font-size:0.9rem;font-weight:700;padding:0.65rem 1rem;border:1px solid var(--border);border-radius:7px;cursor:pointer;">
        Not now
      </button>
    </div>

    <div id="installProgressWrap" style="display:none;flex-direction:column;gap:0.75rem;">
      <div style="display:flex;align-items:center;gap:0.65rem;">
        <div id="installSpinner" style="width:14px;height:14px;border:2px solid rgba(245,158,11,0.2);border-top-color:var(--accent);border-radius:50%;animation:spin 0.8s linear infinite;flex-shrink:0;"></div>
        <span id="installProgressLabel" style="font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--accent);">Installing...</span>
      </div>
      <div id="installLog" style="background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:0.75rem 0.85rem;max-height:200px;overflow-y:auto;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-muted);line-height:1.7;white-space:pre-wrap;"></div>
      <div id="installDoneRow" style="display:none;">
        <button onclick="location.reload()" style="width:100%;background:var(--accent);color:#0b0a08;font-family:'Bricolage Grotesque',sans-serif;font-size:0.9rem;font-weight:800;padding:0.65rem 1rem;border:none;border-radius:7px;cursor:pointer;">✓ Done — Refresh page</button>
      </div>
      <div id="installErrorRow" style="display:none;font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:#f87171;background:rgba(248,113,113,0.07);border:1px solid rgba(248,113,113,0.2);border-radius:6px;padding:0.75rem 0.85rem;line-height:1.6;"></div>
    </div>

  </div>
</div>

<style>
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<script>
let _installDepKey    = null;
let _installPollTimer = null;

function openInstallModal(depKey) {
  _installDepKey = depKey;
  document.getElementById('installConfirmRow').style.display   = 'flex';
  document.getElementById('installProgressWrap').style.display = 'none';
  document.getElementById('installDoneRow').style.display      = 'none';
  document.getElementById('installErrorRow').style.display     = 'none';
  document.getElementById('installLog').textContent            = '';
  document.getElementById('installProgressLabel').textContent  = 'Installing...';
  document.getElementById('installSpinner').style.cssText      = 'width:14px;height:14px;border:2px solid rgba(245,158,11,0.2);border-top-color:var(--accent);border-radius:50%;animation:spin 0.8s linear infinite;flex-shrink:0;';

  fetch('/api/dep-info/' + depKey)
    .then(r => r.json())
    .then(info => {
      document.getElementById('installModalTitle').textContent = 'Install ' + info.name + '?';
      document.getElementById('installModalSize').textContent  = info.size + ' download';
      document.getElementById('installModalNote').textContent  = info.note;
      document.getElementById('installModal').style.display    = 'flex';
    })
    .catch(() => {
      document.getElementById('installModalTitle').textContent = 'Install ' + depKey + '?';
      document.getElementById('installModalSize').textContent  = '';
      document.getElementById('installModalNote').textContent  = '';
      document.getElementById('installModal').style.display    = 'flex';
    });
}

function closeInstallModal() {
  if (_installPollTimer) clearInterval(_installPollTimer);
  document.getElementById('installModal').style.display = 'none';
  _installDepKey = null;
}

function startInstall() {
  if (!_installDepKey) return;
  document.getElementById('installConfirmRow').style.display   = 'none';
  document.getElementById('installProgressWrap').style.display = 'flex';

  fetch('/api/install-dep/' + _installDepKey, { method: 'POST' })
    .then(r => r.json())
    .then(data => {
      if (!data.started && data.reason !== 'already running') {
        showInstallError('Failed to start: ' + (data.reason || 'unknown'));
        return;
      }
      _installPollTimer = setInterval(pollInstall, 1200);
    })
    .catch(e => showInstallError(e.toString()));
}

function pollInstall() {
  fetch('/api/install-status/' + _installDepKey)
    .then(r => r.json())
    .then(job => {
      const logEl = document.getElementById('installLog');
      logEl.textContent = (job.log || []).join('\n');
      logEl.scrollTop   = logEl.scrollHeight;

      if (job.status === 'done') {
        clearInterval(_installPollTimer);
        document.getElementById('installProgressLabel').textContent = '✓ Installation complete';
        document.getElementById('installSpinner').style.animation   = 'none';
        document.getElementById('installSpinner').style.border      = '2px solid var(--green)';
        document.getElementById('installDoneRow').style.display     = 'block';
        // Remove this dep button from warning bar
        document.querySelectorAll('#depsWarningBar button').forEach(btn => {
          if (btn.textContent.toLowerCase().includes(_installDepKey.replace('_', ' '))) btn.remove();
        });
      } else if (job.status === 'error') {
        clearInterval(_installPollTimer);
        showInstallError(job.error || 'Installation failed');
      }
    })
    .catch(() => {});
}

function showInstallError(msg) {
  const el = document.getElementById('installErrorRow');
  el.textContent   = '✗ ' + msg;
  el.style.display = 'block';
  document.getElementById('installSpinner').style.animation      = 'none';
  document.getElementById('installProgressLabel').textContent    = 'Installation failed';
  document.getElementById('installDoneRow').innerHTML = '<button onclick="startInstall()" style="width:100%;background:var(--border);color:var(--text-muted);font-family:\"Bricolage Grotesque\",sans-serif;font-size:0.9rem;font-weight:700;padding:0.65rem 1rem;border:none;border-radius:7px;cursor:pointer;">↺ Try again</button>';
  document.getElementById('installDoneRow').style.display = 'block';
}

document.getElementById('installModal').addEventListener('click', function(e) {
  if (e.target === this) closeInstallModal();
});
</script>

</body>
</html>
