{% extends "base.html" %}

{% block content %}
<style>
  /* Override base body for dashboard layout */
  body {
    padding: 0;
    justify-content: flex-start;
  }
  .container { max-width: none; }

  .dashboard-layout {
    display: flex;
    min-height: 100vh;
  }

  /* Sidebar */
  .sidebar {
    width: 260px;
    min-width: 260px;
    background: var(--surface);
    border-right: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    height: 100vh;
    position: sticky;
    top: 0;
    overflow-y: auto;
    z-index: 100;
  }

  .sidebar-brand {
    padding: 1.25rem 1.25rem 1rem;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 0.625rem;
  }
  .sidebar-brand img {
    width: 36px;
    height: 36px;
    object-fit: contain;
  }
  .sidebar-brand-name {
    font-weight: 700;
    font-size: 1.6rem;
    letter-spacing: -0.03em;
    line-height: 1;
    color: var(--text);
  }

  .sidebar-user {
    padding: 0.75rem 1rem;
    display: flex;
    align-items: center;
    gap: 0.625rem;
  }

  .avatar-circle {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--accent);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 0.75rem;
    flex-shrink: 0;
    overflow: hidden;
  }
  .avatar-circle img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .sidebar-user-info {
    min-width: 0;
  }
  .sidebar-user-name {
    font-weight: 600;
    font-size: 0.825rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .sidebar-user-title {
    font-size: 0.75rem;
    color: var(--text-muted);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .sidebar-nav {
    flex: 1;
    padding: 0.75rem 0;
  }

  .sidebar-section {
    padding: 0 0.75rem;
    margin-bottom: 0.5rem;
  }
  .sidebar-section-label {
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-muted);
    padding: 0.5rem 0.5rem 0.25rem;
  }

  .sidebar-link {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    border-radius: 8px;
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 0.875rem;
    font-weight: 500;
    transition: all 0.15s ease;
  }
  .sidebar-link:hover {
    background: var(--surface-hover);
    color: var(--text);
  }
  .sidebar-link.active {
    background: var(--accent-subtle);
    color: var(--accent);
    font-weight: 600;
  }
  .sidebar-link .icon {
    font-size: 1rem;
    width: 1.25rem;
    text-align: center;
    flex-shrink: 0;
  }

  .sidebar-bottom {
    padding: 0.75rem 1rem;
    border-top: 1px solid var(--border);
  }
  .sidebar-bottom form { margin: 0; }
  .sidebar-bottom-row {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    padding: 0.375rem 0;
  }
  .sidebar-bottom-row a {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    text-decoration: none;
    color: inherit;
    min-width: 0;
    flex: 1;
    border-radius: 8px;
    padding: 0.375rem 0.5rem;
    transition: background 0.15s ease;
  }
  .sidebar-bottom-row a:hover {
    background: var(--surface-hover);
  }
  .sidebar-signout {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 8px;
    color: var(--text-muted);
    background: none;
    border: none;
    font-size: 1rem;
    cursor: pointer;
    flex-shrink: 0;
    transition: all 0.15s ease;
  }
  .sidebar-signout:hover {
    background: var(--surface-hover);
    color: var(--error-text);
  }

  /* Main content */
  .dashboard-main {
    flex: 1;
    min-width: 0;
    padding: 2rem 2rem 2.5rem;
    overflow-y: auto;
  }
  .dashboard-main .container {
    max-width: 900px;
    width: 100%;
  }

  /* Mobile hamburger */
  .hamburger {
    display: none;
    position: fixed;
    top: 0.75rem;
    left: 0.75rem;
    z-index: 200;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 8px;
    width: 2.5rem;
    height: 2.5rem;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 1.25rem;
    color: var(--text);
    box-shadow: var(--shadow);
  }

  .sidebar-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.4);
    z-index: 99;
  }

  @media (max-width: 768px) {
    .hamburger { display: flex; }
    .sidebar {
      position: fixed;
      left: -280px;
      top: 0;
      height: 100vh;
      transition: left 0.25s ease;
      box-shadow: var(--shadow-lg);
    }
    .sidebar.open { left: 0; }
    .sidebar-overlay.open { display: block; }
    .dashboard-main { padding: 3.5rem 1rem 2rem; }
    .dashboard-main .card { padding: 1.25rem; }
  }

  /* Responsive helpers used by dashboard pages */
  .booking-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 0.75rem 0;
    gap: 0.75rem;
  }
  .booking-row .booking-info { flex: 1; min-width: 0; }
  .booking-row .booking-actions {
    display: flex;
    gap: 0.375rem;
    flex-shrink: 0;
    flex-wrap: wrap;
    align-items: center;
  }
  .et-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 0;
    gap: 0.75rem;
  }
  .et-row .et-info { flex: 1; min-width: 0; }
  .et-row .et-actions {
    display: flex;
    gap: 0.375rem;
    align-items: center;
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  /* Two-column form grids that stack on mobile */
  .form-grid-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
  }

  @media (max-width: 480px) {
    .booking-row { flex-direction: column; gap: 0.5rem; }
    .booking-row .booking-actions { width: 100%; }
    .et-row { flex-direction: column; align-items: flex-start; gap: 0.5rem; }
    .et-row .et-actions { width: 100%; }
    .dashboard-main { padding: 3.25rem 0.75rem 1.5rem; }
    .dashboard-main .card { padding: 1rem; }
    .form-grid-2 { grid-template-columns: 1fr; }
  }
</style>

<div class="dashboard-layout">
  <button class="hamburger" onclick="document.querySelector('.sidebar').classList.toggle('open'); document.querySelector('.sidebar-overlay').classList.toggle('open');">&#9776;</button>
  <div class="sidebar-overlay" onclick="document.querySelector('.sidebar').classList.remove('open'); this.classList.remove('open');"></div>

  <nav class="sidebar">
    <a href="/dashboard" class="sidebar-brand" style="text-decoration: none; color: inherit;">
      <img src="/brand-logo" alt="calrs">
      <span class="sidebar-brand-name"><span style="color: var(--accent);">cal</span><span style="color: #e45724;">rs</span></span>
    </a>

    <div class="sidebar-nav">
      <div class="sidebar-section">
        <div class="sidebar-section-label">Scheduling</div>
        <a href="/dashboard" class="sidebar-link {% if sidebar.active == 'overview' %}active{% endif %}">
          <span class="icon">&#9632;</span> Overview
        </a>
        <a href="/dashboard/event-types" class="sidebar-link {% if sidebar.active == 'event-types' %}active{% endif %}">
          <span class="icon">&#128197;</span> Event Types
        </a>
        <a href="/dashboard/bookings" class="sidebar-link {% if sidebar.active == 'bookings' %}active{% endif %}">
          <span class="icon">&#128203;</span> Bookings
        </a>
        <a href="/dashboard/teams" class="sidebar-link {% if sidebar.active == 'teams' %}active{% endif %}">
          <span class="icon">&#128101;</span> Teams
        </a>
      </div>

      <div class="sidebar-section">
        <div class="sidebar-section-label">Shared Links</div>
        <a href="/dashboard/invite-links" class="sidebar-link {% if sidebar.active == 'organization' %}active{% endif %}">
          <span class="icon">&#127970;</span> Invite Links
        </a>
      </div>

      <div class="sidebar-section">
        <div class="sidebar-section-label">Calendars</div>
        <a href="/dashboard/sources" class="sidebar-link {% if sidebar.active == 'sources' %}active{% endif %}">
          <span class="icon">&#128197;</span> Sources
        </a>
      </div>

      <div class="sidebar-section">
        <div class="sidebar-section-label">Personal</div>
        <a href="/dashboard/settings" class="sidebar-link {% if sidebar.active == 'settings' %}active{% endif %}">
          <span class="icon">&#9881;</span> Profile & Settings
        </a>
        <a href="/dashboard/troubleshoot" data-calrs-sync class="sidebar-link {% if sidebar.active == 'troubleshoot' %}active{% endif %}">
          <span class="icon">&#128269;</span> Troubleshoot
        </a>
      </div>

      {% if sidebar.user_role == "admin" %}
      <div class="sidebar-section">
        <div class="sidebar-section-label">Admin</div>
        <a href="/dashboard/admin" class="sidebar-link {% if sidebar.active == 'admin' %}active{% endif %}">
          <span class="icon">&#128272;</span> Admin Panel
        </a>
      </div>
      {% endif %}
    </div>

    <div class="sidebar-bottom">
      <div class="sidebar-bottom-row">
        <a href="/dashboard/settings">
          <div class="avatar-circle">
            {% if sidebar.has_avatar %}
              <img src="/avatar/{{ sidebar.user_id }}" alt="">
            {% else %}
              {{ sidebar.user_initials }}
            {% endif %}
          </div>
          <div class="sidebar-user-info">
            <div class="sidebar-user-name">{{ sidebar.user_name }}</div>
            {% if sidebar.user_title %}<div class="sidebar-user-title">{{ sidebar.user_title }}</div>{% endif %}
          </div>
        </a>
        <form method="post" action="/auth/logout" style="flex-shrink: 0;">
          <button type="submit" class="sidebar-signout" title="Sign out" aria-label="Sign out">&#8592;</button>
        </form>
      </div>
      {% if sidebar.version %}<div style="font-size: 0.7rem; color: var(--text-muted); padding: 0.25rem 0.75rem 0; opacity: 0.6;"><a href="https://github.com/olivierlambert/calrs/releases/tag/v{{ sidebar.version }}" target="_blank" rel="noopener" style="color: inherit; text-decoration: none;" title="View release notes">v{{ sidebar.version }}</a></div>{% endif %}
    </div>
  </nav>

  <main class="dashboard-main">
    <div class="container">
      <div id="tz-banner" style="display:none; margin-bottom: 1rem; padding: 0.75rem 1rem; border-radius: var(--radius); background: var(--accent-subtle); border: 1px solid var(--accent-border); font-size: 0.875rem;">
        <div style="display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; flex-wrap: wrap;">
          <span>Your browser timezone is <strong id="tz-detected"></strong> but your booking timezone is set to <strong id="tz-current"></strong>.</span>
          <span style="display: flex; gap: 0.5rem; flex-shrink: 0;">
            <button id="tz-update" class="slot-btn" style="cursor: pointer; font-weight: 600; color: var(--accent); border-color: var(--accent); font-size: 0.8rem; padding: 0.375rem 0.75rem;">Update</button>
            <button id="tz-dismiss" class="slot-btn" style="cursor: pointer; font-size: 0.8rem; padding: 0.375rem 0.75rem;">Dismiss</button>
          </span>
        </div>
      </div>
      <script>
      (function() {
        var userTz = '{{ sidebar.user_timezone|safe }}';
        var browserTz;
        try { browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch(e) { return; }
        if (!browserTz || browserTz === userTz) return;
        // Skip if both timezones resolve to the same UTC offset right now
        // (e.g. Europe/Paris and Europe/Berlin are identical)
        try {
          var now = new Date();
          var browserOffset = new Date(now.toLocaleString('en-US', {timeZone: browserTz})).getTime();
          var userOffset = new Date(now.toLocaleString('en-US', {timeZone: userTz})).getTime();
          if (browserOffset === userOffset) return;
        } catch(e) { /* fall through to show banner if offset check fails */ }
        var dismissed = sessionStorage.getItem('calrs_tz_dismissed');
        if (dismissed === browserTz + ':' + userTz) return;
        var banner = document.getElementById('tz-banner');
        document.getElementById('tz-detected').textContent = browserTz;
        document.getElementById('tz-current').textContent = userTz;
        banner.style.display = 'block';
        document.getElementById('tz-dismiss').addEventListener('click', function() {
          banner.style.display = 'none';
          sessionStorage.setItem('calrs_tz_dismissed', browserTz + ':' + userTz);
        });
        document.getElementById('tz-update').addEventListener('click', function() {
          var csrfCookie = document.cookie.split(';').map(function(c){return c.trim();}).find(function(c){return c.startsWith('__Host-calrs_csrf=');});
          var csrf = csrfCookie ? csrfCookie.split('=')[1] : '';
          fetch('/dashboard/settings/timezone', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-Token': csrf},
            body: JSON.stringify({timezone: browserTz})
          }).then(function(r) {
            if (r.ok) { banner.style.display = 'none'; location.reload(); }
          });
        });
      })();
      </script>
      {% block dashboard_content %}{% endblock %}
    </div>
  </main>
</div>
<script>
// Shared markdown preview renderer
function renderMdPreview(md) {
  return md
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/~~(.+?)~~/g, '<del>$1</del>')
    .replace(/`(.+?)`/g, '<code style="background:rgba(127,127,127,0.15);padding:0.1em 0.3em;border-radius:3px;font-size:0.85em;">$1</code>')
    .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:var(--accent);text-decoration:underline;">$1</a>')
    .replace(/\n/g, '<br>')
  || '<span style="color:var(--text-muted);">Nothing to preview</span>';
}

// Shared markdown toolbar handler
document.querySelectorAll('.md-toolbar').forEach(function(toolbar) {
  var ta = document.getElementById(toolbar.dataset.target);
  if (!ta) return;
  function wrap(before, after) {
    var start = ta.selectionStart, end = ta.selectionEnd;
    var sel = ta.value.substring(start, end);
    var rep = before + (sel || 'text') + after;
    ta.value = ta.value.substring(0, start) + rep + ta.value.substring(end);
    ta.focus();
    ta.selectionStart = start + before.length;
    ta.selectionEnd = start + before.length + (sel || 'text').length;
  }
  toolbar.addEventListener('click', function(e) {
    var btn = e.target.closest('[data-action]');
    if (!btn) return;
    var a = btn.dataset.action;
    if (a === 'bold') wrap('**', '**');
    else if (a === 'italic') wrap('*', '*');
    else if (a === 'strikethrough') wrap('~~', '~~');
    else if (a === 'code') wrap('`', '`');
    else if (a === 'link') {
      var start = ta.selectionStart, end = ta.selectionEnd;
      var sel = ta.value.substring(start, end);
      var url = prompt('Enter URL:', 'https://');
      if (url) {
        var label = sel || 'link text';
        ta.value = ta.value.substring(0, start) + '[' + label + '](' + url + ')' + ta.value.substring(end);
        ta.focus();
      }
    }
  });
  // Hover effect for toolbar buttons
  toolbar.querySelectorAll('button').forEach(function(btn) {
    btn.addEventListener('mouseenter', function() { this.style.background = 'var(--surface)'; this.style.borderColor = 'var(--border)'; });
    btn.addEventListener('mouseleave', function() { this.style.background = 'none'; this.style.borderColor = 'transparent'; });
  });
  // Keyboard shortcuts
  ta.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && !e.shiftKey) {
      if (e.key === 'b') { e.preventDefault(); wrap('**', '**'); }
      else if (e.key === 'i') { e.preventDefault(); wrap('*', '*'); }
      else if (e.key === 'k') { e.preventDefault(); toolbar.querySelector('[data-action="link"]').click(); }
    }
  });
  // Preview toggle
  var previewBtn = toolbar.querySelector('.md-preview-toggle');
  var previewDiv = document.getElementById(toolbar.dataset.target + '-preview');
  if (previewBtn && previewDiv) {
    var showing = false;
    previewBtn.addEventListener('click', function() {
      showing = !showing;
      if (showing) {
        previewDiv.innerHTML = renderMdPreview(ta.value);
        previewDiv.style.display = '';
        ta.style.display = 'none';
        previewBtn.style.color = 'var(--accent)';
        previewBtn.style.fontWeight = '600';
      } else {
        previewDiv.style.display = 'none';
        ta.style.display = '';
        previewBtn.style.color = 'var(--text-muted)';
        previewBtn.style.fontWeight = '';
        ta.focus();
      }
    });
  }
});
</script>
{% endblock %}
{% block footer %}{% endblock %}
{% block theme_toggle %}{% endblock %}
