"""
Enterprise Dashboard UI — HTML/CSS/JS snippets for enterprise tabs.

These string constants are designed to be injected into the main
dashboard HTML (see dashboard.py).  They add five new tabs: CRM, ERP,
Analytics, Marketplace, and Onboarding — each backed by its own API
endpoint.

Security: all user-supplied content is set via textContent (never
innerHTML) to prevent XSS.  The code relies on the safe DOM helpers
(el(), clearChildren(), escapeHtml()) already present in the parent
dashboard's IIFE.
"""

# ── Enterprise accent colours ────────────────────────────────────────────
# CRM=#FF7A7A  ERP=#7AAFFF  Analytics=#FFD47A
# Marketplace=#7AFFB0  Onboarding=#D47AFF

# ── CSS ──────────────────────────────────────────────────────────────────

ENTERPRISE_CSS = r"""
/* ── Enterprise Tab Accents ───────────────────────────────── */
.tab-btn[data-tab="crm"].active        { color: #FF7A7A; border-bottom-color: #FF7A7A; }
.tab-btn[data-tab="crm"].active .tab-count { background: #3A1A1A; color: #FF7A7A; }
.tab-btn[data-tab="erp"].active        { color: #7AAFFF; border-bottom-color: #7AAFFF; }
.tab-btn[data-tab="erp"].active .tab-count { background: #1A2240; color: #7AAFFF; }
.tab-btn[data-tab="analytics"].active  { color: #FFD47A; border-bottom-color: #FFD47A; }
.tab-btn[data-tab="analytics"].active .tab-count { background: #2A2A1A; color: #FFD47A; }
.tab-btn[data-tab="marketplace"].active { color: #7AFFB0; border-bottom-color: #7AFFB0; }
.tab-btn[data-tab="marketplace"].active .tab-count { background: #1A3A1A; color: #7AFFB0; }
.tab-btn[data-tab="onboarding"].active { color: #D47AFF; border-bottom-color: #D47AFF; }
.tab-btn[data-tab="onboarding"].active .tab-count { background: #2A1A3A; color: #D47AFF; }

/* ── CRM — Relationship Cards ─────────────────────────────── */
.relationship-card {
  background: #0F1624;
  border: 1px solid #1A2332;
  border-radius: 8px;
  padding: 12px 14px;
  border-left: 3px solid #FF7A7A;
}
.relationship-card .rel-agents {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}
.relationship-card .rel-agent-name {
  font-size: 13px;
  font-weight: 600;
  color: #E0E6ED;
}
.relationship-card .rel-arrow {
  font-size: 12px;
  color: #FF7A7A;
}
.relationship-card .rel-stats {
  display: flex;
  gap: 16px;
  font-size: 11px;
  color: #8B9DB0;
}
.relationship-card .rel-stat-value {
  color: #FF7A7A;
  font-weight: 600;
}
.relationship-card .rel-rating {
  display: flex;
  align-items: center;
  gap: 4px;
}
.relationship-card .rel-rating-bar {
  width: 60px;
  height: 6px;
  background: #1A2332;
  border-radius: 3px;
  overflow: hidden;
}
.relationship-card .rel-rating-fill {
  height: 100%;
  background: #FF7A7A;
  border-radius: 3px;
  transition: width 0.3s ease;
}

/* ── ERP — Utilization Bars ───────────────────────────────── */
.utilization-card {
  background: #0F1624;
  border: 1px solid #1A2332;
  border-radius: 8px;
  padding: 12px 14px;
  border-left: 3px solid #7AAFFF;
}
.utilization-card .util-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.utilization-card .util-agent {
  font-size: 13px;
  font-weight: 600;
  color: #E0E6ED;
}
.utilization-card .util-fraction {
  font-size: 11px;
  color: #7AAFFF;
  font-weight: 600;
}
.utilization-card .util-bar-track {
  width: 100%;
  height: 8px;
  background: #1A2332;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 6px;
}
.utilization-card .util-bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}
.util-bar-fill.util-low    { background: #7AAFFF; }
.util-bar-fill.util-medium { background: #FFD47A; }
.util-bar-fill.util-high   { background: #FF7A7A; }
.utilization-card .util-tokens {
  font-size: 10px;
  color: #6B7B8D;
  display: flex;
  justify-content: space-between;
}
.utilization-card .util-token-value {
  color: #8B9DB0;
  font-weight: 600;
}

/* ── Analytics — Leaderboard ──────────────────────────────── */
.leaderboard-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}
.leaderboard-table thead th {
  text-align: left;
  font-size: 10px;
  font-weight: 700;
  color: #3A4A5C;
  text-transform: uppercase;
  letter-spacing: 1px;
  padding: 8px 12px;
  border-bottom: 1px solid #1A2332;
  background: #0D1320;
  position: sticky;
  top: 0;
}
.leaderboard-table tbody tr {
  transition: background 0.15s;
}
.leaderboard-table tbody tr:hover {
  background: #0F1624;
}
.leaderboard-table td {
  padding: 10px 12px;
  border-bottom: 1px solid #141C2B;
  color: #E0E6ED;
}
.leaderboard-table .lb-rank {
  font-weight: 700;
  color: #FFD47A;
  width: 40px;
  text-align: center;
}
.leaderboard-table .lb-rank-1 { color: #FFD47A; }
.leaderboard-table .lb-rank-2 { color: #C0C8D0; }
.leaderboard-table .lb-rank-3 { color: #D4AA7A; }
.leaderboard-table .lb-agent {
  font-weight: 600;
}
.leaderboard-table .lb-tasks {
  color: #7AFFB0;
  font-weight: 600;
}
.leaderboard-table .lb-reputation {
  font-weight: 600;
}
.lb-reputation-high { color: #00D4AA; }
.lb-reputation-mid  { color: #FFD47A; }
.lb-reputation-low  { color: #FF7A7A; }
.leaderboard-table .lb-response {
  color: #8B9DB0;
}

/* ── Marketplace — Service Cards ──────────────────────────── */
.service-card {
  background: #0F1624;
  border: 1px solid #1A2332;
  border-radius: 8px;
  padding: 12px 14px;
  border-left: 3px solid #7AFFB0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}
.service-card .svc-info {
  flex: 1;
  min-width: 0;
}
.service-card .svc-title {
  font-size: 13px;
  font-weight: 600;
  color: #E0E6ED;
  margin-bottom: 4px;
}
.service-card .svc-provider {
  font-size: 11px;
  color: #6B7B8D;
  margin-bottom: 6px;
}
.service-card .svc-rating {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: #FFD47A;
  font-weight: 600;
}
.service-card .svc-stars {
  letter-spacing: 2px;
}
.service-card .svc-price {
  font-size: 11px;
  font-weight: 700;
  padding: 4px 10px;
  border-radius: 4px;
  white-space: nowrap;
  flex-shrink: 0;
}
.svc-price-free       { background: #0D3A3A; color: #00D4AA; }
.svc-price-standard   { background: #1A2240; color: #7AAFFF; }
.svc-price-premium    { background: #2A1A3A; color: #D47AFF; }
.svc-price-enterprise { background: #2A2A1A; color: #FFD47A; }

/* ── Onboarding — Knowledge Articles ─────────────────────── */
.knowledge-card {
  background: #0F1624;
  border: 1px solid #1A2332;
  border-radius: 8px;
  padding: 12px 14px;
  border-left: 3px solid #D47AFF;
}
.knowledge-card .kb-topic {
  font-size: 13px;
  font-weight: 600;
  color: #E0E6ED;
  margin-bottom: 4px;
}
.knowledge-card .kb-summary {
  font-size: 12px;
  color: #8B9DB0;
  line-height: 1.4;
  margin-bottom: 8px;
}
.knowledge-card .kb-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.knowledge-card .kb-tag {
  font-size: 10px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 3px;
  background: #2A1A3A;
  color: #D47AFF;
  text-transform: lowercase;
  letter-spacing: 0.3px;
}
.knowledge-card .kb-meta {
  font-size: 10px;
  color: #4A5A6C;
  margin-top: 6px;
}
"""

# ── HTML ─────────────────────────────────────────────────────────────────

ENTERPRISE_HTML = r"""
      <button class="tab-btn" data-tab="crm" onclick="switchTab('crm')">CRM <span class="tab-count" id="tabCrmCount">0</span></button>
      <button class="tab-btn" data-tab="erp" onclick="switchTab('erp')">ERP <span class="tab-count" id="tabErpCount">0</span></button>
      <button class="tab-btn" data-tab="analytics" onclick="switchTab('analytics')">Analytics <span class="tab-count" id="tabAnalyticsCount">0</span></button>
      <button class="tab-btn" data-tab="marketplace" onclick="switchTab('marketplace')">Marketplace <span class="tab-count" id="tabMarketCount">0</span></button>
      <button class="tab-btn" data-tab="onboarding" onclick="switchTab('onboarding')">Onboarding <span class="tab-count" id="tabOnboardCount">0</span></button>

    <!-- Enterprise tab panels -->
    <div class="tab-panel" id="panel-crm"></div>
    <div class="tab-panel" id="panel-erp"></div>
    <div class="tab-panel" id="panel-analytics"></div>
    <div class="tab-panel" id="panel-marketplace"></div>
    <div class="tab-panel" id="panel-onboarding"></div>
"""

# ── JavaScript ───────────────────────────────────────────────────────────

ENTERPRISE_JS = r"""
  // ── Enterprise fetch functions ────────────────────────────

  function fetchRelationships() {
    fetch('/api/relationships').then(function(r) { return r.json(); }).then(function(rels) {
      var container = document.getElementById('panel-crm');
      clearChildren(container);
      var tabCount = document.getElementById('tabCrmCount');
      if (tabCount) tabCount.textContent = rels.length;
      if (rels.length === 0) {
        container.appendChild(el('div', { className: 'empty-state' }, [
          el('div', { className: 'empty-text' }, 'No agent relationships recorded')
        ]));
        return;
      }
      rels.forEach(function(r) {
        var card = el('div', { className: 'relationship-card' });

        // Agent pair header
        var agents = el('div', { className: 'rel-agents' }, [
          el('span', { className: 'rel-agent-name' }, r.agent_a || '?'),
          el('span', { className: 'rel-arrow' }, '\u2194'),
          el('span', { className: 'rel-agent-name' }, r.agent_b || '?')
        ]);
        card.appendChild(agents);

        // Rating bar: collaboration score 0-100
        var score = Math.max(0, Math.min(100, Number(r.collab_rating) || 0));
        var ratingFill = el('div', { className: 'rel-rating-fill' });
        ratingFill.style.width = score + '%';
        var ratingBar = el('div', { className: 'rel-rating-bar' }, [ratingFill]);

        // Stats row
        var stats = el('div', { className: 'rel-stats' }, [
          el('span', {}, [
            document.createTextNode('Interactions: '),
            el('span', { className: 'rel-stat-value' }, String(r.interaction_count || 0))
          ]),
          el('span', { className: 'rel-rating' }, [
            document.createTextNode('Collab: '),
            el('span', { className: 'rel-stat-value' }, score + '%'),
            ratingBar
          ])
        ]);
        card.appendChild(stats);
        container.appendChild(card);
      });
    }).catch(function(e) { console.error('Fetch relationships failed:', e); });
  }

  function fetchUtilization() {
    fetch('/api/utilization').then(function(r) { return r.json(); }).then(function(agents) {
      var container = document.getElementById('panel-erp');
      clearChildren(container);
      var tabCount = document.getElementById('tabErpCount');
      if (tabCount) tabCount.textContent = agents.length;
      if (agents.length === 0) {
        container.appendChild(el('div', { className: 'empty-state' }, [
          el('div', { className: 'empty-text' }, 'No agent utilization data')
        ]));
        return;
      }
      agents.forEach(function(a) {
        var card = el('div', { className: 'utilization-card' });
        var current = Number(a.current_tasks) || 0;
        var max = Number(a.max_capacity) || 1;
        var pct = Math.round((current / max) * 100);
        var clampedPct = Math.max(0, Math.min(100, pct));

        // Header: agent name + fraction
        card.appendChild(el('div', { className: 'util-header' }, [
          el('span', { className: 'util-agent' }, a.agent_name || '?'),
          el('span', { className: 'util-fraction' }, current + ' / ' + max + ' tasks')
        ]));

        // Utilization bar
        var levelClass = clampedPct < 50 ? 'util-low' : (clampedPct < 80 ? 'util-medium' : 'util-high');
        var barFill = el('div', { className: 'util-bar-fill ' + levelClass });
        barFill.style.width = clampedPct + '%';
        card.appendChild(el('div', { className: 'util-bar-track' }, [barFill]));

        // Token usage row
        var tokensUsed = a.tokens_used != null ? String(a.tokens_used) : '—';
        var tokensLimit = a.tokens_limit != null ? String(a.tokens_limit) : '—';
        card.appendChild(el('div', { className: 'util-tokens' }, [
          el('span', {}, [
            document.createTextNode('Tokens used: '),
            el('span', { className: 'util-token-value' }, tokensUsed)
          ]),
          el('span', {}, [
            document.createTextNode('Limit: '),
            el('span', { className: 'util-token-value' }, tokensLimit)
          ])
        ]));

        container.appendChild(card);
      });
    }).catch(function(e) { console.error('Fetch utilization failed:', e); });
  }

  function fetchLeaderboard() {
    fetch('/api/leaderboard').then(function(r) { return r.json(); }).then(function(entries) {
      var container = document.getElementById('panel-analytics');
      clearChildren(container);
      var tabCount = document.getElementById('tabAnalyticsCount');
      if (tabCount) tabCount.textContent = entries.length;
      if (entries.length === 0) {
        container.appendChild(el('div', { className: 'empty-state' }, [
          el('div', { className: 'empty-text' }, 'No analytics data available')
        ]));
        return;
      }

      // Build table
      var table = el('table', { className: 'leaderboard-table' });

      // Thead
      var thead = el('thead');
      var headRow = el('tr', {}, [
        el('th', {}, 'Rank'),
        el('th', {}, 'Agent'),
        el('th', {}, 'Tasks'),
        el('th', {}, 'Reputation'),
        el('th', {}, 'Avg Response')
      ]);
      thead.appendChild(headRow);
      table.appendChild(thead);

      // Tbody
      var tbody = el('tbody');
      entries.forEach(function(e, idx) {
        var rank = e.rank || (idx + 1);
        var rankClass = rank === 1 ? 'lb-rank-1' : (rank === 2 ? 'lb-rank-2' : (rank === 3 ? 'lb-rank-3' : ''));
        var rep = Number(e.reputation) || 0;
        var repClass = rep >= 80 ? 'lb-reputation-high' : (rep >= 50 ? 'lb-reputation-mid' : 'lb-reputation-low');
        var responseTime = e.avg_response_time != null ? e.avg_response_time + 's' : '—';

        var row = el('tr', {}, [
          el('td', { className: 'lb-rank ' + rankClass }, '#' + rank),
          el('td', { className: 'lb-agent' }, e.agent_name || '?'),
          el('td', { className: 'lb-tasks' }, String(e.tasks_completed || 0)),
          el('td', { className: 'lb-reputation ' + repClass }, String(rep)),
          el('td', { className: 'lb-response' }, responseTime)
        ]);
        tbody.appendChild(row);
      });
      table.appendChild(tbody);

      // Wrap in a scrollable container (reuse tab-panel's own overflow)
      container.appendChild(table);
    }).catch(function(e) { console.error('Fetch leaderboard failed:', e); });
  }

  function fetchServices() {
    fetch('/api/services').then(function(r) { return r.json(); }).then(function(services) {
      var container = document.getElementById('panel-marketplace');
      clearChildren(container);
      var tabCount = document.getElementById('tabMarketCount');
      if (tabCount) tabCount.textContent = services.length;
      if (services.length === 0) {
        container.appendChild(el('div', { className: 'empty-state' }, [
          el('div', { className: 'empty-text' }, 'No services listed in the marketplace')
        ]));
        return;
      }
      services.forEach(function(s) {
        var card = el('div', { className: 'service-card' });

        // Left side: info
        var info = el('div', { className: 'svc-info' });
        info.appendChild(el('div', { className: 'svc-title' }, s.title || 'Untitled'));
        info.appendChild(el('div', { className: 'svc-provider' }, 'by ' + (s.provider || 'unknown')));

        // Star rating (capped 0-5)
        var rating = Math.max(0, Math.min(5, Number(s.rating) || 0));
        var fullStars = Math.floor(rating);
        var starText = '';
        for (var i = 0; i < fullStars; i++) starText += '\u2605';
        for (var j = fullStars; j < 5; j++) starText += '\u2606';
        info.appendChild(el('div', { className: 'svc-rating' }, [
          el('span', { className: 'svc-stars' }, starText),
          el('span', {}, String(rating.toFixed(1)))
        ]));
        card.appendChild(info);

        // Right side: price badge
        var tier = (s.price_tier || 'free').toLowerCase();
        var tierLabel = tier.charAt(0).toUpperCase() + tier.slice(1);
        var priceClass = 'svc-price svc-price-' + tier;
        card.appendChild(el('span', { className: priceClass }, tierLabel));

        container.appendChild(card);
      });
    }).catch(function(e) { console.error('Fetch services failed:', e); });
  }

  function fetchKnowledge() {
    fetch('/api/knowledge').then(function(r) { return r.json(); }).then(function(articles) {
      var container = document.getElementById('panel-onboarding');
      clearChildren(container);
      var tabCount = document.getElementById('tabOnboardCount');
      if (tabCount) tabCount.textContent = articles.length;
      if (articles.length === 0) {
        container.appendChild(el('div', { className: 'empty-state' }, [
          el('div', { className: 'empty-text' }, 'No knowledge base articles')
        ]));
        return;
      }
      articles.forEach(function(a) {
        var card = el('div', { className: 'knowledge-card' });
        card.appendChild(el('div', { className: 'kb-topic' }, a.topic || 'Untitled'));

        if (a.summary) {
          card.appendChild(el('div', { className: 'kb-summary' }, a.summary));
        }

        // Tags
        var tags = a.tags || [];
        if (tags.length > 0) {
          var tagContainer = el('div', { className: 'kb-tags' });
          tags.forEach(function(t) {
            tagContainer.appendChild(el('span', { className: 'kb-tag' }, t));
          });
          card.appendChild(tagContainer);
        }

        // Meta line
        var meta = [];
        if (a.author) meta.push('by ' + a.author);
        if (a.updated) meta.push('updated ' + formatTime(a.updated));
        if (meta.length > 0) {
          card.appendChild(el('div', { className: 'kb-meta' }, meta.join(' | ')));
        }

        container.appendChild(card);
      });
    }).catch(function(e) { console.error('Fetch knowledge failed:', e); });
  }

  // ── Enterprise tab-badge counters (for refreshAll) ────────
  // Call these to keep badge counts up-to-date without fully
  // rendering the inactive panels.

  function refreshEnterpriseBadges() {
    fetch('/api/relationships').then(function(r) { return r.json(); }).then(function(d) {
      var c = document.getElementById('tabCrmCount');
      if (c) c.textContent = d.length;
    }).catch(function(){});
    fetch('/api/utilization').then(function(r) { return r.json(); }).then(function(d) {
      var c = document.getElementById('tabErpCount');
      if (c) c.textContent = d.length;
    }).catch(function(){});
    fetch('/api/leaderboard').then(function(r) { return r.json(); }).then(function(d) {
      var c = document.getElementById('tabAnalyticsCount');
      if (c) c.textContent = d.length;
    }).catch(function(){});
    fetch('/api/services').then(function(r) { return r.json(); }).then(function(d) {
      var c = document.getElementById('tabMarketCount');
      if (c) c.textContent = d.length;
    }).catch(function(){});
    fetch('/api/knowledge').then(function(r) { return r.json(); }).then(function(d) {
      var c = document.getElementById('tabOnboardCount');
      if (c) c.textContent = d.length;
    }).catch(function(){});
  }

  // ── Enterprise tab dispatch (for refreshAll) ──────────────
  // Call refreshEnterpriseTab(currentTab) inside refreshAll()
  // so the active enterprise panel is fully rendered on each
  // refresh cycle.

  function refreshEnterpriseTab(tab) {
    if (tab === 'crm')         fetchRelationships();
    else if (tab === 'erp')    fetchUtilization();
    else if (tab === 'analytics') fetchLeaderboard();
    else if (tab === 'marketplace') fetchServices();
    else if (tab === 'onboarding')  fetchKnowledge();
  }
"""
