/**
 * UI Template - Design System Unificado BI-CCC
 * Header, Footer e estilos compartilhados
 */

// CSS Variables compartilhadas - Cores CambioReal
const cssVariables = `
  :root {
    --primary: #7600be;
    --primary-light: #9B2DE5;
    --primary-dark: #5A0091;
    --primary-bg: #F5EAFA;
    --admin-accent: #2E7D32;
    --admin-dark: #1B5E20;
    --admin-bg: #E8F5E9;
    --corporate-accent: #7600be;
    --corporate-dark: #5A0091;
    --corporate-bg: #F5EAFA;
    --bg: #F0F2F5;
    --card: #FFFFFF;
    --text: #1A1D23;
    --text-secondary: #5F6368;
    --text-muted: #9AA0A6;
    --border: #E8EAED;
    --green: #1E8E3E;
    --green-bg: #E6F4EA;
    --blue: #1A73E8;
    --blue-bg: #E8F0FE;
    --orange: #E8710A;
    --orange-bg: #FEF3E8;
    --red: #D93025;
    --red-bg: #FDE7E7;
    --purple: #7B1FA2;
    --purple-bg: #F3E5F5;
  }

  /* Dark Mode */
  [data-theme="dark"] {
    --bg: #0D1117;
    --card: #161B22;
    --text: #E6EDF3;
    --text-secondary: #B1BAC4;
    --text-muted: #6E7681;
    --border: #30363D;
    --primary-bg: #2D1B4E;
    --admin-bg: #0D2818;
    --corporate-bg: #2D1B4E;
    --green: #3FB950;
    --green-bg: #0D2818;
    --blue: #58A6FF;
    --blue-bg: #0D1D3A;
    --orange: #F0883E;
    --orange-bg: #2A1A0A;
    --red: #F85149;
    --red-bg: #3D1215;
    --purple: #BC8CFF;
    --purple-bg: #2D1B4E;
  }
  [data-theme="dark"] .app-header {
    box-shadow: 0 2px 8px rgba(0,0,0,0.4);
  }
  [data-theme="dark"] .app-footer {
    background: var(--card);
    border-top-color: var(--border);
  }
  [data-theme="dark"] input,
  [data-theme="dark"] select {
    background: var(--bg);
    color: var(--text);
    border-color: var(--border);
  }
  [data-theme="dark"] input:focus,
  [data-theme="dark"] select:focus {
    border-color: var(--blue);
  }
  [data-theme="dark"] tbody tr:hover { background: rgba(255,255,255,0.03); }
  [data-theme="dark"] tbody tr:nth-child(even) { background: rgba(255,255,255,0.02); }
  [data-theme="dark"] thead th { background: var(--bg); }
`;

// CSS do Header unificado
const headerCSS = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: var(--bg); color: var(--text); line-height: 1.5;
    -webkit-font-smoothing: antialiased;
  }

  /* Header Unificado */
  .app-header {
    background: linear-gradient(135deg, var(--header-color) 0%, var(--header-dark) 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  }
  .app-header.admin {
    --header-color: var(--admin-accent);
    --header-dark: var(--admin-dark);
  }
  .app-header.corporate {
    --header-color: var(--corporate-accent);
    --header-dark: var(--corporate-dark);
  }
  .app-header.agent {
    --header-color: var(--primary);
    --header-dark: var(--primary-dark);
  }
  .header-inner {
    max-width: 1600px;
    margin: 0 auto;
    padding: 0 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 64px;
  }

  .header-brand {
    display: flex;
    align-items: center;
    gap: 16px;
    text-decoration: none;
    color: white;
  }
  .header-brand:hover {
    opacity: 0.95;
  }
  .header-brand .logo {
    height: 36px;
    width: auto;
    background: white;
    padding: 6px 12px;
    border-radius: 8px;
  }
  .header-brand .app-name {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .header-brand .app-name-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 14px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 800;
    letter-spacing: 0.5px;
  }
  .header-brand .app-subtitle {
    font-size: 11px;
    opacity: 0.8;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 1px;
  }

  .header-nav {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  .header-nav a {
    color: white;
    text-decoration: none;
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.15s;
    opacity: 0.85;
  }
  .header-nav a:hover {
    background: rgba(255,255,255,0.15);
    opacity: 1;
  }
  .header-nav a.active {
    background: rgba(255,255,255,0.2);
    opacity: 1;
  }

  .header-user {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  .header-user .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    background: rgba(255,255,255,0.1);
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 500;
  }
  .header-user .user-avatar {
    width: 28px;
    height: 28px;
    background: rgba(255,255,255,0.25);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 700;
  }
  .header-user .user-role {
    font-size: 10px;
    background: rgba(255,255,255,0.2);
    padding: 2px 8px;
    border-radius: 10px;
    text-transform: uppercase;
    font-weight: 700;
    letter-spacing: 0.5px;
  }
  .header-user .btn-logout {
    background: rgba(255,255,255,0.15);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    font-family: inherit;
    transition: all 0.15s;
  }
  .header-user .btn-logout:hover {
    background: rgba(255,255,255,0.25);
  }

  /* Alert Bell */
  .alert-bell {
    position: relative; cursor: pointer; color: white;
    width: 36px; height: 36px; display: flex; align-items: center; justify-content: center;
    background: rgba(255,255,255,0.1); border-radius: 50%; transition: all 0.2s;
  }
  .alert-bell:hover { background: rgba(255,255,255,0.2); }
  .alert-badge {
    position: absolute; top: -2px; right: -2px; background: #D93025; color: white;
    font-size: 10px; font-weight: 700; min-width: 18px; height: 18px; line-height: 18px;
    text-align: center; border-radius: 9px; padding: 0 4px;
  }
  .alert-dropdown {
    position: absolute; top: 60px; right: 40px; width: 360px; max-height: 400px;
    background: var(--card); border: 1px solid var(--border); border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.2); z-index: 1000; overflow: hidden;
  }
  .alert-dropdown-header {
    display: flex; justify-content: space-between; align-items: center;
    padding: 12px 16px; border-bottom: 1px solid var(--border);
    font-size: 13px; color: var(--text);
  }
  .alert-dropdown-close { cursor: pointer; font-size: 18px; color: var(--text-muted); }
  .alert-dropdown-body {
    max-height: 340px; overflow-y: auto; padding: 8px;
  }
  .alert-item {
    padding: 10px 12px; border-radius: 8px; margin-bottom: 4px;
    font-size: 12px; line-height: 1.4; cursor: pointer; transition: background 0.15s;
  }
  .alert-item:hover { background: var(--bg); }
  .alert-item .alert-severity {
    display: inline-block; padding: 1px 6px; border-radius: 4px;
    font-size: 10px; font-weight: 700; margin-right: 6px;
  }
  .alert-item .alert-severity.P0 { background: var(--red-bg); color: var(--red); }
  .alert-item .alert-severity.P1 { background: var(--orange-bg); color: var(--orange); }
  .alert-item .alert-severity.P2 { background: var(--blue-bg); color: var(--blue); }
  .alert-item .alert-time { color: var(--text-muted); font-size: 10px; display: block; margin-top: 4px; }

  /* Theme Toggle */
  .btn-theme-toggle {
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.25);
    color: white;
    width: 36px; height: 36px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 16px; line-height: 1;
    transition: all 0.2s;
  }
  .btn-theme-toggle:hover {
    background: rgba(255,255,255,0.25);
    transform: scale(1.1);
  }

  /* Footer */
  .app-footer {
    text-align: center;
    padding: 20px;
    font-size: 12px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    background: var(--card);
    margin-top: auto;
  }

  /* Container padrão */
  .app-container {
    padding: 28px 40px;
    max-width: 1600px;
    margin: 0 auto;
  }

  /* Responsive */
  @media (max-width: 768px) {
    .header-inner {
      padding: 12px 16px;
      height: auto;
      flex-direction: column;
      gap: 10px;
    }
    .header-brand {
      gap: 10px;
    }
    .header-brand .logo {
      height: 28px;
      padding: 4px 8px;
    }
    .header-brand .app-name-badge {
      font-size: 12px;
      padding: 5px 10px;
    }
    .header-brand .app-subtitle {
      display: none;
    }
    .header-nav {
      width: 100%;
      justify-content: center;
      gap: 6px;
    }
    .header-nav a {
      font-size: 12px;
      padding: 8px 12px;
    }
    .header-user {
      width: 100%;
      justify-content: center;
      gap: 10px;
    }
    .header-user .user-info {
      font-size: 12px;
    }
    .header-user .avatar {
      width: 32px;
      height: 32px;
      font-size: 11px;
    }
    .header-user .btn-logout {
      font-size: 11px;
      padding: 6px 12px;
    }
    .app-container {
      padding: 16px;
    }
  }

  @media (max-width: 480px) {
    .header-inner {
      padding: 10px 12px;
    }
    .header-nav {
      flex-wrap: wrap;
    }
    .header-nav a {
      font-size: 11px;
      padding: 6px 10px;
    }
    .header-user .user-info {
      display: none;
    }
    .app-container {
      padding: 12px;
    }
  }
`;

/**
 * Gera o header HTML
 * @param {Object} options
 * @param {string} options.role - 'admin', 'corporate' ou 'agente'
 * @param {string} options.userName - Nome do usuário
 * @param {string} options.activePage - Página ativa para nav
 * @param {boolean} options.showNav - Mostrar navegação
 * @param {string[]} options.permissions - Paineis permitidos para o usuario
 */
function buildHeader(options = {}) {
  const { role = 'agente', userName = '', activePage = '', showNav = true, permissions = [] } = options;
  const { PANELS } = require('./panels');

  // Determine header class based on permissions
  const adminPanels = ['bi', 'cliente', 'providers', 'usuarios'];
  const hasAdminPanels = adminPanels.some(k => permissions.includes(k));
  let headerClass = 'agent';
  if (hasAdminPanels) headerClass = 'admin';
  else if (permissions.includes('corporate')) headerClass = 'corporate';

  const initials = userName
    .split(' ')
    .map(n => n[0])
    .slice(0, 2)
    .join('')
    .toUpperCase();

  // Build nav dynamically from permissions
  const activeMap = { 'dashboard': 'dashboard', 'corporate': 'dashboard', 'usuarios': 'users' };
  const navLinks = PANELS
    .filter(p => permissions.includes(p.key))
    .map(p => {
      const pageKey = activeMap[p.key] || p.key;
      const isActive = activePage === pageKey || activePage === p.key;
      return `<a href="${p.route}" class="${isActive ? 'active' : ''}">${p.label}</a>`;
    })
    .join('\n      ');
  const nav = `<nav class="header-nav">${navLinks}</nav>`;

  // Home URL: first permitted panel
  const firstPanel = PANELS.find(p => permissions.includes(p.key));
  const homeUrl = firstPanel ? firstPanel.route : '/login';

  // Show alert bell if user has BI permission
  const showAlerts = permissions.includes('bi');

  // Role label for display
  let roleLabel = 'Agente';
  if (role === 'admin') roleLabel = 'Admin';
  else if (role === 'corporate') roleLabel = 'Corporate';

  return `
    <header class="app-header ${headerClass}">
      <div class="header-inner">
        <a href="${homeUrl}" class="header-brand">
          <img src="/public/logo.png" alt="CambioReal" class="logo">
          <div class="app-name">
            <span class="app-name-badge">BI - CCC</span>
            <span class="app-subtitle">Central Command Center</span>
          </div>
        </a>
        ${showNav ? nav : ''}
        <div class="header-user">
          ${showAlerts ? `
          <div class="alert-bell" id="alertBell" onclick="toggleAlertDropdown()" title="Alerts">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>
            <span class="alert-badge" id="alertBadge" style="display:none">0</span>
          </div>
          <div class="alert-dropdown" id="alertDropdown" style="display:none">
            <div class="alert-dropdown-header">
              <strong>Alerts (24h)</strong>
              <span class="alert-dropdown-close" onclick="toggleAlertDropdown()">&times;</span>
            </div>
            <div class="alert-dropdown-body" id="alertDropdownBody">
              <span style="color:var(--text-muted);font-size:12px">Loading...</span>
            </div>
          </div>
          ` : ''}
          <div class="user-info">
            <span class="user-avatar">${initials}</span>
            <span>${userName}</span>
            <span class="user-role">${roleLabel}</span>
          </div>
          <button class="btn-theme-toggle" onclick="toggleTheme()" title="Alternar tema claro/escuro" aria-label="Alternar tema">
            <span id="themeIcon">\u263E</span>
          </button>
          <a href="/logout" class="btn-logout">Sair</a>
        </div>
      </div>
    </header>
  `;
}

/**
 * Gera o footer HTML
 */
function buildFooter() {
  const year = new Date().getFullYear();
  return `
    <footer class="app-footer">
      CambioReal &copy; ${year} &mdash; BI - CCC (Central Command Center)
    </footer>
  `;
}

/**
 * Gera o head HTML com estilos base
 * @param {string} title - Título da página
 * @param {string} additionalCSS - CSS adicional
 * @param {string} scripts - Scripts externos (opcional)
 */
// Theme JS - runs in <head> to prevent FOUC
const themeScript = `
  <script>
    (function(){
      var saved = localStorage.getItem('bi-theme');
      var theme = saved || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
      document.documentElement.setAttribute('data-theme', theme);
    })();
    function toggleTheme() {
      var current = document.documentElement.getAttribute('data-theme');
      var next = current === 'dark' ? 'light' : 'dark';
      document.documentElement.setAttribute('data-theme', next);
      localStorage.setItem('bi-theme', next);
      var icon = document.getElementById('themeIcon');
      if (icon) icon.textContent = next === 'dark' ? '\\u2600' : '\\u263E';
      window.dispatchEvent(new CustomEvent('themechange', {detail:{theme:next}}));
    }
    document.addEventListener('DOMContentLoaded', function() {
      var icon = document.getElementById('themeIcon');
      if (icon) icon.textContent = document.documentElement.getAttribute('data-theme') === 'dark' ? '\\u2600' : '\\u263E';
      // Load alert badge count
      if (document.getElementById('alertBell')) {
        fetch('/admin/api/alerts?unacked=1')
          .then(function(r){return r.json()})
          .then(function(d){
            var badge = document.getElementById('alertBadge');
            if (badge && d.unacked_count > 0) {
              badge.textContent = d.unacked_count > 99 ? '99+' : d.unacked_count;
              badge.style.display = 'block';
            }
          }).catch(function(){});
      }
    });
    function toggleAlertDropdown() {
      var dd = document.getElementById('alertDropdown');
      if (!dd) return;
      var visible = dd.style.display !== 'none';
      dd.style.display = visible ? 'none' : 'block';
      if (!visible) loadAlertDropdown();
    }
    function loadAlertDropdown() {
      var body = document.getElementById('alertDropdownBody');
      if (!body) return;
      fetch('/admin/api/alerts')
        .then(function(r){return r.json()})
        .then(function(d){
          if (!d.alerts || d.alerts.length === 0) {
            body.innerHTML = '<div style="padding:16px;text-align:center;color:var(--text-muted);font-size:12px">No alerts in last 24h</div>';
            return;
          }
          body.innerHTML = d.alerts.slice(0, 20).map(function(a){
            return '<div class="alert-item" onclick="ackAlert('+a.id+')">' +
              '<span class="alert-severity '+a.severity+'">'+a.severity+'</span>' +
              '<span>'+a.message.substring(0,120)+'</span>' +
              '<span class="alert-time">'+a.created_at+(a.acknowledged?' (acked)':'')+'</span></div>';
          }).join('');
        }).catch(function(e){ body.innerHTML = '<div style="padding:12px;color:var(--red);font-size:12px">Error loading alerts</div>'; });
    }
    function ackAlert(id) {
      fetch('/admin/api/alerts/'+id+'/ack', {method:'PUT'})
        .then(function(){ loadAlertDropdown(); })
        .catch(function(){});
      var badge = document.getElementById('alertBadge');
      if (badge) {
        var c = parseInt(badge.textContent) || 0;
        if (c > 1) { badge.textContent = c - 1; } else { badge.style.display = 'none'; }
      }
    }
    document.addEventListener('click', function(e) {
      var dd = document.getElementById('alertDropdown');
      var bell = document.getElementById('alertBell');
      if (dd && bell && dd.style.display !== 'none' && !dd.contains(e.target) && !bell.contains(e.target)) {
        dd.style.display = 'none';
      }
    });
  <\/script>
`;

function buildHead(title, additionalCSS = '', scripts = '') {
  return `
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title} | BI - CCC</title>
    ${themeScript}
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    ${scripts}
    <style>
      ${cssVariables}
      ${headerCSS}
      ${additionalCSS}
    </style>
  `;
}

// Inline Chart.js to avoid CDN/network loading issues
const _chartJsPath = require('path').join(__dirname, '../public/chart.umd.min.js');
let _chartJsInline = '';
try {
  _chartJsInline = require('fs').readFileSync(_chartJsPath, 'utf8');
} catch(e) { console.warn('Chart.js file not found at', _chartJsPath); }

function getChartJsScript() {
  if (_chartJsInline) {
    // Wrap in try/catch to prevent Chart.js errors from crashing the page
    return '<script>try{' + _chartJsInline + '}catch(_e){window._chartError=_e.message;}<\/script>';
  }
  return '<script src="/public/chart.umd.min.js"><\/script>';
}

module.exports = {
  buildHeader,
  buildFooter,
  buildHead,
  cssVariables,
  headerCSS,
  getChartJsScript
};
