/**
 * Savit Cross-Engine Project Persistence
 *
 * Stores the currently selected project in localStorage so the same
 * project stays selected as the user navigates between engines.
 *
 * Usage: include this script in each engine's layout header.
 * Each engine reads `window.savitProject` on load and pre-selects the project.
 *
 * Storage key: 'savit_project' → { id: number, name: string, domain: string }
 */
(function () {
  'use strict';

  const STORAGE_KEY = 'savit_project';

  // ── Read / Write ──────────────────────────────────────────────────────────
  window.savitProject = {
    get() {
      try {
        const raw = localStorage.getItem(STORAGE_KEY);
        return raw ? JSON.parse(raw) : null;
      } catch (_) { return null; }
    },

    set(id, name, domain) {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify({ id: +id, name: String(name), domain: String(domain || '') }));
      } catch (_) {}
    },

    clear() {
      localStorage.removeItem(STORAGE_KEY);
    },
  };

  // ── Sidebar project chip ───────────────────────────────────────────────────
  // Injects an "active project" chip into the sidebar after the brand block.
  // Each engine must have <div id="sidebar-project-slot"> placeholder OR
  // we inject it dynamically after .sidebar-brand.
  function renderChip() {
    const project = window.savitProject.get();
    const existing = document.getElementById('active-project-chip');
    if (existing) existing.remove();

    const brand = document.querySelector('.sidebar-brand');
    if (!brand) return;

    if (!project) return;

    const chip = document.createElement('div');
    chip.id = 'active-project-chip';
    chip.style.cssText = 'margin: 0 10px 4px; padding: 6px 10px; background: rgba(255,255,255,.07); border-radius: 6px; cursor: pointer;';
    chip.innerHTML = `
      <div style="font-size:.65rem;color:#94a3b8;text-transform:uppercase;letter-spacing:.05em;margin-bottom:2px;">Active Project</div>
      <div style="display:flex;align-items:center;justify-content:space-between;gap:4px;">
        <span style="font-size:.8rem;font-weight:600;color:#e2e8f0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px;" title="${escapeHtml(project.name)}">${escapeHtml(project.name)}</span>
        <span id="project-chip-change" style="font-size:.65rem;color:#60a5fa;flex-shrink:0;white-space:nowrap;">change</span>
      </div>
      ${project.domain ? `<div style="font-size:.65rem;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${escapeHtml(project.domain)}</div>` : ''}
    `;

    brand.insertAdjacentElement('afterend', chip);

    // "change" link: opens a mini dropdown from all projects if the engine has a project selector,
    // otherwise navigates to the dashboard
    chip.addEventListener('click', (e) => {
      if (e.target.id === 'project-chip-change' || e.target.closest('#project-chip-change')) {
        // Navigate to dashboard to switch project
        const dashUrl = computeDashboardUrl();
        if (dashUrl) window.location.href = dashUrl;
        return;
      }
      // Clicking the chip itself = open this project's performance view
      const dashUrl = computeDashboardUrl();
      if (dashUrl) window.location.href = dashUrl;
    });
  }

  function computeDashboardUrl() {
    // Walk up from the script's location to find /Savit/
    const scripts = document.querySelectorAll('script[src*="project-persistence"]');
    for (const s of scripts) {
      const m = s.src.match(/^(.*?\/Savit)\//i);
      if (m) return m[1] + '/';
    }
    // Fallback: look for meta[name="base-url"]
    const base = (document.querySelector('meta[name="base-url"]') || {}).content || '';
    if (base.includes('/Audit/')) return base.replace(/\/Audit\/.*/, '/');
    if (base.includes('/Content')) return base.replace(/\/Content.*/, '/');
    return null;
  }

  function escapeHtml(s) {
    return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  // Render chip once DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', renderChip);
  } else {
    renderChip();
  }
})();
