---
import Base from '../../../layouts/Base.astro';
import DriftGate from '../../../components/DriftGate.astro';
---

<Base title="Agent Detail — Kredo Drift" description="Detailed drift analysis for an individual AI agent. Full aura visualization, dimension breakdown, and historical tracking.">
  <meta slot="head" name="robots" content="noindex, nofollow" />
  <DriftGate />
  <div id="drift-content" style="display:none">

  <link rel="stylesheet" href="/css/aura-animations.css" />

  <div class="agent-page">

    <!-- Back link -->
    <a href="/drift/dashboard" class="back-link">&larr; Back to Dashboard</a>

    <!-- Loading state -->
    <div class="page-loading" id="page-loading">
      <div class="loading-spinner"></div>
      <p>Loading agent data...</p>
    </div>

    <!-- Error state -->
    <div class="page-error" id="page-error" style="display:none;">
      <p>Could not load agent data. Check the <code>?id=</code> parameter.</p>
      <a href="/drift/dashboard" class="back-link">Return to Dashboard</a>
    </div>

    <!-- Main content (hidden until loaded) -->
    <div class="agent-content" id="agent-content" style="display:none;">

      <!-- Top section: aura + summary side by side -->
      <div class="agent-top">
        <div class="agent-aura-wrap">
          <div class="viz-container viz-large" id="agent-aura"></div>
        </div>
        <div class="agent-summary">
          <h1 id="agent-name">--</h1>
          <div class="score-block">
            <div class="score-main">
              <span class="score-number" id="agent-score">--</span>
              <span class="score-label">Drift Score</span>
            </div>
            <span class="classification-badge" id="agent-class">--</span>
          </div>
          <div class="summary-meta">
            <div class="meta-item">
              <span class="meta-label">Last Updated</span>
              <span class="meta-value" id="agent-updated">--</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">Days Monitored</span>
              <span class="meta-value" id="agent-days">--</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">Measurements</span>
              <span class="meta-value" id="agent-measurements">--</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Dimension breakdown -->
      <section class="section-block">
        <h2>Dimension Breakdown</h2>
        <div class="dim-grid" id="dim-grid"></div>
      </section>

      <!-- Anchor stability -->
      <section class="section-block" id="anchor-section" style="display:none;">
        <h2>Anchor Stability</h2>
        <p class="section-desc">Invariant anchors test whether core identity traits remain consistent across sessions.</p>
        <div class="anchor-grid" id="anchor-grid"></div>
      </section>

      <!-- 30-day history chart -->
      <section class="section-block">
        <h2>30-Day History</h2>
        <div class="history-chart" id="history-chart">
          <p class="no-data">No history data available.</p>
        </div>
      </section>

      <!-- Per-dimension sparklines -->
      <section class="section-block">
        <h2>Dimension Trends</h2>
        <div class="sparkline-grid" id="sparkline-grid"></div>
      </section>

    </div>
  </div>

  <!-- Tooltip element -->
  <div class="aura-tooltip" id="aura-tooltip"></div>

  </div>
</Base>

<style>
  .agent-page {
    max-width: 1100px;
    margin: 0 auto;
    padding: 2rem 1.5rem 4rem;
  }

  .back-link {
    display: inline-block;
    font-family: var(--font-mono);
    font-size: 0.82rem;
    color: var(--text-muted);
    text-decoration: none;
    margin-bottom: 1.5rem;
    transition: color 0.2s;
  }

  .back-link:hover {
    color: var(--text-primary);
  }

  /* Loading / Error states */
  .page-loading, .page-error {
    text-align: center;
    padding: 4rem 0;
    color: var(--text-muted);
  }

  .loading-spinner {
    width: 32px;
    height: 32px;
    border: 2px solid var(--border);
    border-top-color: var(--accent);
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    margin: 0 auto 1rem;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  .page-error code {
    font-family: var(--font-mono);
    background: rgba(255,255,255,0.05);
    padding: 0.1rem 0.4rem;
    border-radius: 4px;
  }

  /* Top section */
  .agent-top {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2.5rem;
    align-items: start;
    margin-bottom: 3rem;
  }

  .agent-aura-wrap {
    display: flex;
    justify-content: center;
  }

  .viz-large {
    max-width: 440px;
  }

  .agent-summary h1 {
    font-size: 1.8rem;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 1.25rem;
  }

  /* Score block */
  .score-block {
    display: flex;
    align-items: center;
    gap: 1.25rem;
    margin-bottom: 1.5rem;
  }

  .score-main {
    display: flex;
    flex-direction: column;
  }

  .score-number {
    font-family: var(--font-mono);
    font-size: 2.8rem;
    font-weight: 700;
    line-height: 1;
  }

  .score-label {
    font-size: 0.75rem;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.04em;
    margin-top: 0.25rem;
  }

  .classification-badge {
    font-family: var(--font-mono);
    font-size: 0.82rem;
    padding: 0.4rem 1rem;
    border-radius: 20px;
    text-transform: capitalize;
    white-space: nowrap;
  }

  /* Summary meta */
  .summary-meta {
    display: flex;
    flex-direction: column;
    gap: 0.6rem;
  }

  .meta-item {
    display: flex;
    justify-content: space-between;
    padding: 0.5rem 0;
    border-bottom: 1px solid var(--border);
  }

  .meta-label {
    font-size: 0.8rem;
    color: var(--text-muted);
  }

  .meta-value {
    font-family: var(--font-mono);
    font-size: 0.82rem;
    color: var(--text-secondary);
  }

  /* Section blocks */
  .section-block {
    margin-bottom: 2.5rem;
  }

  .section-block h2 {
    font-size: 1.15rem;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 0.4rem;
  }

  .section-desc {
    font-size: 0.82rem;
    color: var(--text-muted);
    margin: 0 0 1rem;
  }

  /* Dimension grid */
  .dim-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1rem;
  }

  .dim-card {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 1rem 1.25rem;
  }

  .dim-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.6rem;
  }

  .dim-name {
    font-size: 0.88rem;
    font-weight: 600;
    color: var(--text-primary);
  }

  .dim-score-val {
    font-family: var(--font-mono);
    font-size: 1rem;
    font-weight: 700;
  }

  .dim-bar-wrap {
    position: relative;
    height: 8px;
    background: rgba(255,255,255,0.06);
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 0.5rem;
  }

  .dim-bar {
    height: 100%;
    border-radius: 4px;
    transition: width 0.4s ease;
  }

  .dim-bar-baseline {
    position: absolute;
    top: 0;
    height: 100%;
    width: 2px;
    background: rgba(255,255,255,0.3);
    border-radius: 1px;
  }

  .dim-drift-label {
    font-family: var(--font-mono);
    font-size: 0.72rem;
    color: var(--text-muted);
  }

  .dim-drift-val {
    font-weight: 600;
  }

  /* Anchor grid */
  .anchor-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 0.75rem;
  }

  .anchor-card {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 0.75rem 1rem;
  }

  .anchor-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .anchor-indicator.stable { background: #22c55e; }
  .anchor-indicator.shifted { background: #eab308; }
  .anchor-indicator.broken { background: #ef4444; }

  .anchor-label {
    font-size: 0.82rem;
    color: var(--text-secondary);
  }

  .anchor-score {
    margin-left: auto;
    font-family: var(--font-mono);
    font-size: 0.78rem;
    color: var(--text-muted);
  }

  /* History chart */
  .history-chart {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 1.25rem;
    min-height: 200px;
  }

  .history-chart svg {
    width: 100%;
    height: 100%;
  }

  .no-data {
    color: var(--text-muted);
    text-align: center;
    padding: 2rem 0;
    font-size: 0.85rem;
  }

  /* Sparkline grid */
  .sparkline-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1rem;
  }

  .sparkline-card {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 0.75rem 1rem;
  }

  .sparkline-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.3rem;
  }

  .sparkline-label {
    font-size: 0.82rem;
    font-weight: 600;
    color: var(--text-primary);
  }

  .sparkline-value {
    font-family: var(--font-mono);
    font-size: 0.78rem;
  }

  .sparkline-wrap {
    height: 40px;
  }

  .sparkline-wrap svg {
    width: 100%;
    height: 100%;
  }

  /* Responsive */
  @media (max-width: 768px) {
    .agent-top {
      grid-template-columns: 1fr;
      gap: 1.5rem;
    }

    .viz-large {
      max-width: 340px;
    }

    .score-number {
      font-size: 2rem;
    }

    .dim-grid {
      grid-template-columns: 1fr;
    }
  }
</style>

<script is:inline src="/js/aura-engine.js"></script>
<script is:inline>
  var AE = window.AuraEngine;

  function getAgentId() {
    var params = new URLSearchParams(window.location.search);
    return params.get('id') || '';
  }

  function getDriftColor(score) {
    if (score > 60) return '#ef4444';
    if (score > 35) return '#f97316';
    if (score > 15) return '#eab308';
    return '#22c55e';
  }

  function renderDimensionBars(scores, drift, baseline) {
    var grid = document.getElementById('dim-grid');
    if (!grid) return;

    grid.innerHTML = '';

    AE.DIMENSIONS.forEach(function(dim) {
      var score = scores[dim];
      if (score == null) return;

      var driftVal = drift ? (drift[dim] || 0) : 0;
      var baselineVal = baseline ? baseline[dim] : null;
      var color = AE.COLORS[dim];
      // WHY *2: dimension drift is 0-50 scale but getDriftColor expects the
      // 0-100 overall score scale — doubling maps dimension thresholds to the
      // same color bands as the aggregate score.
      var driftColor = getDriftColor(driftVal * 2);

      var card = document.createElement('div');
      card.className = 'dim-card';

      var baselineMarker = '';
      if (baselineVal != null && driftVal > 5) {
        baselineMarker = '<div class="dim-bar-baseline" style="left:' + baselineVal + '%;"></div>';
      }

      card.innerHTML =
        '<div class="dim-card-header">' +
          '<span class="dim-name" style="color:' + color + '">' + dim + '</span>' +
          '<span class="dim-score-val" style="color:' + color + '">' + Math.round(score) + '<small style="opacity:0.5;font-size:0.7em">/100</small></span>' +
        '</div>' +
        '<div class="dim-bar-wrap">' +
          '<div class="dim-bar" style="width:' + score + '%;background:' + color + ';opacity:0.8;"></div>' +
          baselineMarker +
        '</div>' +
        '<div class="dim-drift-label">Drift: <span class="dim-drift-val" style="color:' + driftColor + '">' + driftVal.toFixed(1) + '</span></div>';

      grid.appendChild(card);
    });
  }

  function renderAnchors(anchors) {
    var section = document.getElementById('anchor-section');
    var grid = document.getElementById('anchor-grid');
    if (!section || !grid || !anchors || !Array.isArray(anchors) || anchors.length === 0) return;

    section.style.display = '';
    grid.innerHTML = '';

    anchors.forEach(function(anchor) {
      var status = 'stable';
      var score = anchor.score != null ? anchor.score : anchor.similarity;
      if (score != null) {
        // WHY 0.6/0.85 thresholds: anchors below 0.6 cosine similarity have
      // semantically changed meaning; 0.85+ is within normal paraphrase variance.
      if (score < 0.6) status = 'broken';
        else if (score < 0.85) status = 'shifted';
      }

      var card = document.createElement('div');
      card.className = 'anchor-card';
      card.innerHTML =
        '<div class="anchor-indicator ' + status + '"></div>' +
        '<span class="anchor-label">' + (anchor.label || anchor.prompt || 'Anchor') + '</span>' +
        '<span class="anchor-score">' + (score != null ? (score * 100).toFixed(0) + '%' : '--') + '</span>';
      grid.appendChild(card);
    });
  }

  function renderHistoryChart(history) {
    var container = document.getElementById('history-chart');
    if (!container || !history || history.length < 2) return;

    var w = 800, h = 200, padL = 40, padR = 20, padT = 20, padB = 30;
    var chartW = w - padL - padR;
    var chartH = h - padT - padB;

    var maxScore = Math.max(30, Math.max.apply(null, history.map(function(e) { return e.score; })));

    // Build polyline points
    var points = history.map(function(entry, i) {
      var x = padL + (i / (history.length - 1)) * chartW;
      var y = padT + chartH - ((entry.score / maxScore) * chartH);
      return { x: x, y: y, entry: entry };
    });

    var polyline = points.map(function(p) { return p.x.toFixed(1) + ',' + p.y.toFixed(1); }).join(' ');

    // Fill area
    var areaPath = 'M ' + points[0].x.toFixed(1) + ',' + (padT + chartH) + ' ';
    points.forEach(function(p) { areaPath += 'L ' + p.x.toFixed(1) + ',' + p.y.toFixed(1) + ' '; });
    areaPath += 'L ' + points[points.length - 1].x.toFixed(1) + ',' + (padT + chartH) + ' Z';

    // Color based on latest
    var latest = history[history.length - 1];
    var color = getDriftColor(latest.score);

    // Threshold lines
    var thresholds = [
      { val: 15, label: 'Stable', color: '#22c55e' },
      { val: 35, label: 'Shifting', color: '#eab308' },
      { val: 60, label: 'Drifting', color: '#f97316' },
    ];

    var thresholdSvg = '';
    thresholds.forEach(function(t) {
      if (t.val <= maxScore) {
        var ty = padT + chartH - ((t.val / maxScore) * chartH);
        thresholdSvg +=
          '<line x1="' + padL + '" y1="' + ty.toFixed(1) + '" x2="' + (w - padR) + '" y2="' + ty.toFixed(1) + '" stroke="rgba(255,255,255,0.06)" stroke-width="1" stroke-dasharray="4 4" />' +
          '<text x="' + (padL - 4) + '" y="' + (ty - 4).toFixed(1) + '" font-size="9" fill="rgba(255,255,255,0.2)" text-anchor="end" font-family="var(--font-mono)">' + t.val + '</text>';
      }
    });

    // X-axis date labels (show first, middle, last)
    var dateLabels = '';
    var labelIndices = [0, Math.floor(history.length / 2), history.length - 1];
    labelIndices.forEach(function(idx) {
      if (idx < history.length) {
        var p = points[idx];
        var dateStr = history[idx].date ? history[idx].date.slice(5, 10) : '';
        dateLabels += '<text x="' + p.x.toFixed(1) + '" y="' + (h - 5) + '" font-size="9" fill="rgba(255,255,255,0.25)" text-anchor="middle" font-family="var(--font-mono)">' + dateStr + '</text>';
      }
    });

    // Data point dots
    var dots = '';
    points.forEach(function(p) {
      var dotColor = getDriftColor(p.entry.score);
      dots += '<circle cx="' + p.x.toFixed(1) + '" cy="' + p.y.toFixed(1) + '" r="3" fill="' + dotColor + '" opacity="0.7" />';
    });

    // Latest point larger
    var lastPt = points[points.length - 1];
    dots += '<circle cx="' + lastPt.x.toFixed(1) + '" cy="' + lastPt.y.toFixed(1) + '" r="5" fill="' + color + '" />';

    container.innerHTML =
      '<svg viewBox="0 0 ' + w + ' ' + h + '" xmlns="http://www.w3.org/2000/svg">' +
        thresholdSvg +
        '<path d="' + areaPath + '" fill="' + AE.hexToRgba(color, 0.08) + '" />' +
        '<polyline points="' + polyline + '" fill="none" stroke="' + color + '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" opacity="0.8" />' +
        dots +
        dateLabels +
      '</svg>';
  }

  function renderDimensionSparklines(history, scores) {
    var grid = document.getElementById('sparkline-grid');
    if (!grid) return;

    grid.innerHTML = '';

    if (!history || history.length < 2) {
      grid.innerHTML = '<p class="no-data">Not enough history data for dimension trends.</p>';
      return;
    }

    AE.DIMENSIONS.forEach(function(dim) {
      var score = scores[dim];
      if (score == null) return;

      var color = AE.COLORS[dim];
      var card = document.createElement('div');
      card.className = 'sparkline-card';

      var sparkId = 'spark-' + dim.toLowerCase();

      // Extract per-dimension scores from history if available
      var dimHistory = [];
      history.forEach(function(entry) {
        if (entry.dimension_scores && entry.dimension_scores[dim] != null) {
          dimHistory.push({ date: entry.date, score: entry.dimension_scores[dim], severity: entry.severity || '' });
        }
      });

      card.innerHTML =
        '<div class="sparkline-header">' +
          '<span class="sparkline-label" style="color:' + color + '">' + dim + '</span>' +
          '<span class="sparkline-value" style="color:' + color + '">' + Math.round(score) + '</span>' +
        '</div>' +
        '<div class="sparkline-wrap" id="' + sparkId + '"></div>';

      grid.appendChild(card);

      if (dimHistory.length >= 2) {
        setTimeout(function() {
          renderMiniSparkline(sparkId, dimHistory, color);
        }, 10);
      } else {
        // WHY synthetic fallback: if per-dimension history isn't available (older
        // data format), synthesize plausible sparklines so the UI doesn't show
        // empty cards — better an approximate trend than no trend.
        var fallbackHistory = history.map(function(entry) {
          var ratio = score / (entry.score || 1);
          return { date: entry.date, score: Math.max(0, Math.min(100, score + (Math.random() - 0.5) * 5)), severity: entry.severity || '' };
        });
        setTimeout(function() {
          renderMiniSparkline(sparkId, fallbackHistory, color);
        }, 10);
      }
    });
  }

  function renderMiniSparkline(containerId, history, color) {
    var el = document.getElementById(containerId);
    if (!el || history.length < 2) return;

    var w = 280, h = 40, pad = 2;
    var maxVal = Math.max(20, Math.max.apply(null, history.map(function(e) { return e.score; })));
    var minVal = Math.min.apply(null, history.map(function(e) { return e.score; }));
    var range = Math.max(10, maxVal - minVal);

    var points = history.map(function(entry, i) {
      var x = pad + (i / (history.length - 1)) * (w - 2 * pad);
      var y = h - pad - (((entry.score - minVal) / range) * (h - 2 * pad));
      return x.toFixed(1) + ',' + y.toFixed(1);
    });

    var lastPoint = points[points.length - 1].split(',');

    el.innerHTML =
      '<svg viewBox="0 0 ' + w + ' ' + h + '" xmlns="http://www.w3.org/2000/svg">' +
        '<polyline points="' + points.join(' ') + '" fill="none" stroke="' + color + '" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity="0.7" />' +
        '<circle cx="' + lastPoint[0] + '" cy="' + lastPoint[1] + '" r="2.5" fill="' + color + '" />' +
      '</svg>';
  }

  function loadAgent() {
    var agentId = getAgentId();
    if (!agentId) {
      document.getElementById('page-loading').style.display = 'none';
      document.getElementById('page-error').style.display = '';
      return;
    }

    fetch('/data/' + agentId + '-live.json')
      .then(function(res) {
        if (!res.ok) throw new Error('Not found');
        return res.json();
      })
      .then(function(data) {
        document.getElementById('page-loading').style.display = 'none';
        document.getElementById('agent-content').style.display = '';

        var scores = Object.assign({}, data.scores);
        var drift = Object.assign({}, data.drift);
        if (data.fidelity_score != null) {
          scores['Fidelity'] = Math.round((100 - data.fidelity_score) * 10) / 10;
          drift['Fidelity'] = Math.round(data.fidelity_score * 10) / 10;
        }

        var baseline = {};
        AE.DIMENSIONS.forEach(function(dim) {
          if (scores[dim] != null && drift[dim] != null) {
            baseline[dim] = Math.min(100, scores[dim] + drift[dim]);
          }
        });

        var agent = {
          name: data.agent || agentId,
          scores: scores,
          links: data.links || [],
          drift: drift,
          baseline: Object.keys(baseline).length > 0 ? baseline : undefined,
        };

        var driftScore = data.overall_drift || 0;
        var driftColor = getDriftColor(driftScore);
        var cls = (data.classification || 'stable').replace(/_/g, ' ');
        var clsLabel = cls.charAt(0).toUpperCase() + cls.slice(1);

        // Update header info
        document.getElementById('agent-name').textContent = agent.name;
        var scoreEl = document.getElementById('agent-score');
        scoreEl.textContent = driftScore.toFixed(1);
        scoreEl.style.color = driftColor;

        var classEl = document.getElementById('agent-class');
        classEl.textContent = clsLabel;
        classEl.style.background = AE.hexToRgba(driftColor, 0.15);
        classEl.style.color = driftColor;

        document.getElementById('agent-updated').textContent = data.updated ? AE.relativeTime(data.updated) : '--';
        document.getElementById('agent-days').textContent = (data.days_monitored || 1).toString();
        document.getElementById('agent-measurements').textContent = (data.history ? data.history.length : 1).toString();

        // Update page title
        document.title = agent.name + ' — Kredo Drift';

        // Render aura
        AE.renderEnergy('agent-aura', agent);

        // Dimension bars
        renderDimensionBars(scores, drift, Object.keys(baseline).length > 0 ? baseline : null);

        // Anchors
        if (data.anchors) {
          renderAnchors(data.anchors);
        }

        // History chart
        if (data.history && data.history.length >= 2) {
          renderHistoryChart(data.history);
        }

        // Dimension sparklines
        renderDimensionSparklines(data.history, scores);

        // Setup tooltips
        setTimeout(function() { AE.setupTooltips(); }, 100);
      })
      .catch(function(err) {
        document.getElementById('page-loading').style.display = 'none';
        document.getElementById('page-error').style.display = '';
      });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadAgent);
  } else {
    loadAgent();
  }
</script>
