/**
 * Zeq CKO Widget — Waveform Visualization for Chrome Extension Side Panel
 * Renders CKO data: waveform canvas, metrics badges, spectral peaks, AGO harmonics.
 *
 * @version 1.287.27
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */

const CKOWidget = (() => {
  'use strict';

  const HZ     = 1.287;
  const ZEQOND = 0.777;

  // ── Render CKO widget into a container ────────────────────────────────
  function render(containerId, ckoData) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const metrics = CKOClient.extractMetrics(ckoData);
    if (!metrics) {
      container.innerHTML = '<div class="cko-empty">No waveform data available</div>';
      return;
    }

    const grade = CKOClient.stabilityGrade(metrics.stabilityIndex);

    container.innerHTML = `
      <div class="cko-widget" id="cko-widget-inner">
        <!-- Metrics Strip -->
        <div class="cko-metrics-strip">
          <div class="cko-metric">
            <span class="cko-metric-label">Stability</span>
            <span class="cko-metric-value" style="color:${grade.color}">${(metrics.stabilityIndex * 100).toFixed(1)}%</span>
          </div>
          <div class="cko-metric">
            <span class="cko-metric-label">Phase Lock</span>
            <span class="cko-metric-value">${(metrics.phaseLock * 100).toFixed(1)}%</span>
          </div>
          <div class="cko-metric">
            <span class="cko-metric-label">Energy Drift</span>
            <span class="cko-metric-value">${metrics.energyDrift.toFixed(2)}%</span>
          </div>
          <div class="cko-metric">
            <span class="cko-metric-label">Golden Ratio</span>
            <span class="cko-metric-value" style="color:${metrics.goldenRatio ? '#22c55e' : '#ef4444'}">${metrics.goldenRatio ? '✓ φ' : '✗'}</span>
          </div>
          <div class="cko-metric">
            <span class="cko-metric-label">Pipeline</span>
            <span class="cko-metric-value">${metrics.computationTime}ms</span>
          </div>
        </div>

        <!-- Waveform Canvas -->
        <div class="cko-canvas-wrap">
          <canvas id="cko-waveform-canvas" width="400" height="100"></canvas>
        </div>

        <!-- Spectral Peaks -->
        <div class="cko-spectral" id="cko-spectral-bars"></div>

        <!-- Domain & Operators -->
        <div class="cko-info-row">
          <span class="cko-domain-badge">${metrics.primaryDomain}</span>
          ${metrics.operatorsUsed.slice(0, 8).map(op =>
            `<span class="cko-op-badge">${op}</span>`
          ).join('')}
          ${metrics.operatorsUsed.length > 8 ? `<span class="cko-op-more">+${metrics.operatorsUsed.length - 8}</span>` : ''}
        </div>

        <!-- KO42 + AGO Status -->
        <div class="cko-info-row cko-status-row">
          <span class="cko-status-badge ${metrics.ko42Compliant ? 'cko-pass' : 'cko-fail'}">
            KO42 ${metrics.ko42Compliant ? '✓' : '✗'}
          </span>
          <span class="cko-status-badge ${metrics.goldenRatio ? 'cko-pass' : 'cko-fail'}">
            AGO φ ${metrics.goldenRatio ? 'VERIFIED' : 'UNVERIFIED'}
          </span>
          <span class="cko-status-badge ${metrics.waveformStable ? 'cko-pass' : 'cko-warn'}">
            ${grade.label}
          </span>
        </div>

        <!-- Interpretation -->
        ${metrics.interpretation ? `
          <div class="cko-interpretation">${metrics.interpretation}</div>
        ` : ''}

        <!-- HULYAS Parameters (collapsible) -->
        <details class="cko-details">
          <summary>HULYAS Parameters</summary>
          <div class="cko-params-grid">
            ${Object.entries(metrics.parameters).map(([k, v]) => `
              <div class="cko-param">
                <span class="cko-param-key">${_formatParamKey(k)}</span>
                <span class="cko-param-val">${typeof v === 'number' ? v.toFixed(4) : v}</span>
              </div>
            `).join('')}
          </div>
        </details>
      </div>
    `;

    // Draw waveform
    _drawWaveform('cko-waveform-canvas', metrics.spectralPeaks);

    // Draw spectral bars
    _drawSpectralBars('cko-spectral-bars', metrics.spectralPeaks);
  }

  // ── Render mini badge for interceptor ─────────────────────────────────
  function renderMiniBadge(ckoData) {
    const metrics = CKOClient.extractMetrics(ckoData);
    if (!metrics) return '';

    const grade = CKOClient.stabilityGrade(metrics.stabilityIndex);

    return `
      <span class="zeq-cko-mini" style="
        display:inline-flex; align-items:center; gap:4px;
        background:#0f172a; color:${grade.color}; padding:2px 8px;
        border-radius:4px; font-size:11px; font-family:monospace;
        border:1px solid ${grade.color}33;
      ">
        <span style="width:6px;height:6px;border-radius:50%;background:${grade.color};display:inline-block"></span>
        ${(metrics.stabilityIndex * 100).toFixed(0)}% · ${metrics.primaryDomain}
        ${metrics.ko42Compliant ? ' · KO42✓' : ''}
      </span>
    `;
  }

  // ── Draw waveform on canvas ───────────────────────────────────────────
  function _drawWaveform(canvasId, spectralPeaks) {
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    const w = canvas.clientWidth;
    const h = canvas.clientHeight;
    canvas.width  = w * dpr;
    canvas.height = h * dpr;
    ctx.scale(dpr, dpr);

    // Background
    ctx.fillStyle = '#0a0a0f';
    ctx.fillRect(0, 0, w, h);

    // Grid lines
    ctx.strokeStyle = '#1e293b';
    ctx.lineWidth = 0.5;
    for (let y = h * 0.25; y < h; y += h * 0.25) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);
      ctx.stroke();
    }

    // Synthesize waveform
    const { timestamps, amplitudes } = CKOClient.synthesizeWaveform(spectralPeaks, w);
    if (amplitudes.length === 0) return;

    const maxAmp = Math.max(...amplitudes.map(Math.abs), 0.001);

    // Draw waveform trace
    ctx.strokeStyle = '#00ff88';
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    for (let i = 0; i < amplitudes.length; i++) {
      const x = (i / amplitudes.length) * w;
      const y = h / 2 - (amplitudes[i] / maxAmp) * (h * 0.4);
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Glow effect
    ctx.strokeStyle = '#00ff8833';
    ctx.lineWidth = 4;
    ctx.beginPath();
    for (let i = 0; i < amplitudes.length; i++) {
      const x = (i / amplitudes.length) * w;
      const y = h / 2 - (amplitudes[i] / maxAmp) * (h * 0.4);
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Center line
    ctx.strokeStyle = '#334155';
    ctx.lineWidth = 0.5;
    ctx.beginPath();
    ctx.moveTo(0, h / 2);
    ctx.lineTo(w, h / 2);
    ctx.stroke();

    // HulyaPulse marker
    const phase = ((Date.now() / 1000) % ZEQOND) / ZEQOND;
    const px = phase * w;
    ctx.fillStyle = '#f97316';
    ctx.beginPath();
    ctx.arc(px, h / 2, 3, 0, Math.PI * 2);
    ctx.fill();
  }

  // ── Draw spectral bars ────────────────────────────────────────────────
  function _drawSpectralBars(containerId, peaks) {
    const container = document.getElementById(containerId);
    if (!container || !peaks || peaks.length === 0) return;

    const maxAmp = Math.max(...peaks.map(p => p.amplitude || p.amp || 0), 0.001);

    container.innerHTML = peaks.map(peak => {
      const freq = peak.frequency || peak.freq || 0;
      const amp  = peak.amplitude || peak.amp || 0;
      const pct  = (amp / maxAmp) * 100;
      const isAGO = Math.abs(freq - 1.287) < 0.05 || Math.abs(freq - 0.795) < 0.05 || Math.abs(freq - 2.082) < 0.05;
      const color = isAGO ? '#00ff88' : '#00ff88';

      return `
        <div class="cko-spectral-bar-group">
          <div class="cko-spectral-bar" style="height:${pct}%;background:${color}"></div>
          <span class="cko-spectral-label">${freq.toFixed(2)}</span>
        </div>
      `;
    }).join('');
  }

  // ── Format parameter key ──────────────────────────────────────────────
  function _formatParamKey(key) {
    const map = {
      alpha: 'α', mu2: 'μ²', lambda: 'λ', phi_c: 'ϕ_c',
      beta: 'β', J_ext: 'J_ext', f: 'f', phi0: 'φ₀',
    };
    return map[key] || key;
  }

  // ── CSS for the widget (inject once) ──────────────────────────────────
  function injectStyles() {
    if (document.getElementById('cko-widget-styles')) return;

    const style = document.createElement('style');
    style.id = 'cko-widget-styles';
    style.textContent = `
      .cko-widget {
        background: #000;
        border: 1px solid rgba(0,255,136,.18);
        border-left: 3px solid #00ff88;
        border-radius: 2px;
        padding: 12px;
        font-family: 'Inter', -apple-system, sans-serif;
        color: #fff;
        font-size: 12px;
        margin: 8px 0;
      }
      .cko-empty {
        color: #64748b;
        text-align: center;
        padding: 20px;
        font-style: italic;
      }
      .cko-metrics-strip {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
        flex-wrap: wrap;
      }
      .cko-metric {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        min-width: 60px;
      }
      .cko-metric-label {
        font-size: 9px;
        color: #64748b;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }
      .cko-metric-value {
        font-family: 'JetBrains Mono', monospace;
        font-size: 13px;
        font-weight: 600;
        color: #00ff88;
      }
      .cko-canvas-wrap {
        margin: 8px 0;
        border-radius: 4px;
        overflow: hidden;
      }
      .cko-canvas-wrap canvas {
        width: 100%;
        height: 80px;
        display: block;
      }
      .cko-spectral {
        display: flex;
        gap: 4px;
        align-items: flex-end;
        height: 40px;
        margin: 8px 0;
        padding: 4px 0;
        border-bottom: 1px solid #1e293b;
      }
      .cko-spectral-bar-group {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100%;
        justify-content: flex-end;
      }
      .cko-spectral-bar {
        width: 100%;
        max-width: 24px;
        border-radius: 2px 2px 0 0;
        min-height: 2px;
      }
      .cko-spectral-label {
        font-size: 8px;
        color: #64748b;
        font-family: 'JetBrains Mono', monospace;
        margin-top: 2px;
      }
      .cko-info-row {
        display: flex;
        gap: 4px;
        flex-wrap: wrap;
        margin: 6px 0;
      }
      .cko-domain-badge {
        background: #1e293b;
        color: #00ff88;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
        text-transform: capitalize;
      }
      .cko-op-badge {
        background: #1a1a2e;
        color: #00ff88;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 10px;
        font-family: 'JetBrains Mono', monospace;
      }
      .cko-op-more {
        color: #64748b;
        font-size: 10px;
        padding: 2px 4px;
      }
      .cko-status-row {
        margin-top: 4px;
      }
      .cko-status-badge {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }
      .cko-pass {
        background: #052e16;
        color: #22c55e;
        border: 1px solid #166534;
      }
      .cko-fail {
        background: #450a0a;
        color: #ef4444;
        border: 1px solid #991b1b;
      }
      .cko-warn {
        background: #422006;
        color: #f97316;
        border: 1px solid #9a3412;
      }
      .cko-interpretation {
        margin-top: 8px;
        padding: 8px;
        background: #1a1a2e;
        border-radius: 4px;
        color: #94a3b8;
        font-size: 11px;
        line-height: 1.4;
        border-left: 3px solid #00ff88;
      }
      .cko-details {
        margin-top: 8px;
      }
      .cko-details summary {
        cursor: pointer;
        color: #64748b;
        font-size: 11px;
        padding: 4px 0;
      }
      .cko-details summary:hover {
        color: #94a3b8;
      }
      .cko-params-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
        gap: 4px;
        padding: 8px 0;
      }
      .cko-param {
        display: flex;
        justify-content: space-between;
        padding: 2px 4px;
        background: #1a1a2e;
        border-radius: 3px;
      }
      .cko-param-key {
        color: #00ff88;
        font-family: 'JetBrains Mono', monospace;
        font-size: 11px;
      }
      .cko-param-val {
        color: #e2e8f0;
        font-family: 'JetBrains Mono', monospace;
        font-size: 11px;
      }
    `;
    document.head.appendChild(style);
  }

  // ── Public API ─────────────────────────────────────────────────────────
  return {
    render,
    renderMiniBadge,
    injectStyles,
  };
})();

if (typeof module !== 'undefined' && module.exports) {
  module.exports = CKOWidget;
}
