/**
 * PulseTab — HulyaPulse Live Dashboard for Chrome Extension Side Panel
 * Real-time 1.287 Hz frequency display, phase visualisation, waveform canvas.
 *
 * @version 1.287.5
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const PulseTab = (() => {
  'use strict';

  const HZ     = 1.287;
  const ZEQOND = 0.777;
  const ALPHA  = 0.00129;

  let container = null;
  let canvas = null;
  let ctx = null;
  let animId = null;
  let initialized = false;

  function init(containerId) {
    container = document.getElementById(containerId);
    if (!container) return;
    if (initialized) { _startAnimation(); return; }
    initialized = true;
    container.innerHTML = '';
    _buildHTML();
    _startAnimation();
  }

  function _buildHTML() {
    container.innerHTML = `
      <div style="flex:1;overflow-y:auto;padding:12px">
        <!-- Frequency Hero -->
        <div style="text-align:center;margin-bottom:16px">
          <div style="font-family:'Orbitron',sans-serif;font-size:28px;font-weight:700;color:#06b6d4;line-height:1" id="pt-freq">1.287</div>
          <div style="font-size:10px;color:#64748b;margin-top:2px">Hz — HulyaPulse Core Frequency</div>
        </div>

        <!-- Waveform Canvas -->
        <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;overflow:hidden;margin-bottom:12px">
          <canvas id="pt-waveform" width="260" height="80" style="width:100%;display:block"></canvas>
        </div>

        <!-- Live Metrics Grid -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px">
          <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:10px;text-align:center">
            <div style="font-size:9px;color:#64748b;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px">Phase</div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:16px;color:#22d3ee" id="pt-phase">0.0000</div>
          </div>
          <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:10px;text-align:center">
            <div style="font-size:9px;color:#64748b;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px">KO42 Tensor</div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:16px;color:#a78bfa" id="pt-ko42">0.000000</div>
          </div>
          <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:10px;text-align:center">
            <div style="font-size:9px;color:#64748b;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px">Zeqond</div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:16px;color:#22c55e" id="pt-zeqond">0.777 s</div>
          </div>
          <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:10px;text-align:center">
            <div style="font-size:9px;color:#64748b;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px">Zeqonds</div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:16px;color:#f97316" id="pt-zeqonds">0</div>
          </div>
        </div>

        <!-- Operator Summary -->
        <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:12px;margin-bottom:12px">
          <div style="font-size:10px;color:#06b6d4;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;font-weight:600">Operator Framework</div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Total Operators</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0">1,500+</span>
          </div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Categories</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0">64</span>
          </div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Core (QM/NM/GR/CS)</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0">42+</span>
          </div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Awareness (ON0→VX)</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0">16</span>
          </div>
        </div>

        <!-- Equations -->
        <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:12px;margin-bottom:12px">
          <div style="font-size:10px;color:#a78bfa;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;font-weight:600">Core Equations</div>
          <div style="font-size:10px;color:#94a3b8;line-height:1.6;font-family:'JetBrains Mono',monospace">
            <div>R(t) = S(t)[1 + α sin(2πft + φ₀)]</div>
            <div style="margin-top:4px">α ≈ 1.29×10⁻³ · f = 1.287 Hz</div>
            <div style="margin-top:4px">t_Zeq = t_Unix / 0.777 + φ_epoch</div>
          </div>
        </div>

        <!-- CKO Last Computation -->
        <div style="background:#0f172a;border:1px solid #334155;border-radius:8px;padding:12px">
          <div style="font-size:10px;color:#f97316;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;font-weight:600">Last CKO Computation</div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Time</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0" id="pt-cko-time">—</span>
          </div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Domain</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0" id="pt-cko-domain">—</span>
          </div>
          <div style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
            <span style="color:#64748b">Stability</span>
            <span style="font-family:'JetBrains Mono',monospace;color:#e2e8f0" id="pt-cko-stability">—</span>
          </div>
        </div>
      </div>
    `;

    canvas = container.querySelector('#pt-waveform');
    ctx = canvas?.getContext('2d');
  }

  function _startAnimation() {
    if (animId) cancelAnimationFrame(animId);
    function frame() {
      const now = Date.now() / 1000;
      const phase  = (now % ZEQOND) / ZEQOND;
      const ko42   = ALPHA * Math.sin(2 * Math.PI * HZ * now);
      const zeqonds = now / ZEQOND;

      // Update text values
      _setText('pt-phase', phase.toFixed(4));
      _setText('pt-ko42', ko42.toFixed(8));
      _setText('pt-zeqonds', Math.floor(zeqonds).toLocaleString());

      // Draw waveform
      _drawWaveform(now);

      // CKO metrics from page
      const ckoTime = document.getElementById('status-cko-time');
      if (ckoTime) _setText('pt-cko-time', ckoTime.textContent);
      const ckoDomain = document.getElementById('status-cko-domain');
      if (ckoDomain) _setText('pt-cko-domain', ckoDomain.textContent);
      const ckoStability = document.getElementById('status-cko-stability');
      if (ckoStability) _setText('pt-cko-stability', ckoStability.textContent);

      animId = requestAnimationFrame(frame);
    }
    frame();
  }

  function _drawWaveform(now) {
    if (!ctx || !canvas) return;
    const W = canvas.width;
    const H = canvas.height;
    ctx.clearRect(0, 0, W, H);

    // Background grid
    ctx.strokeStyle = 'rgba(51,65,85,0.4)';
    ctx.lineWidth = 0.5;
    for (let y = H / 4; y < H; y += H / 4) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(W, y);
      ctx.stroke();
    }

    // Main sine wave (1.287 Hz)
    ctx.strokeStyle = '#06b6d4';
    ctx.lineWidth = 2;
    ctx.beginPath();
    for (let x = 0; x < W; x++) {
      const t = now - (W - x) * 0.015;
      const y = H / 2 + (H / 3) * Math.sin(2 * Math.PI * HZ * t);
      x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
    }
    ctx.stroke();

    // KO42 modulation overlay
    ctx.strokeStyle = 'rgba(167,139,250,0.5)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    for (let x = 0; x < W; x++) {
      const t = now - (W - x) * 0.015;
      const base = Math.sin(2 * Math.PI * HZ * t);
      const mod = ALPHA * Math.sin(2 * Math.PI * HZ * t);
      const y = H / 2 + (H / 3) * (base + mod * 200);
      x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Phase marker
    const phase = (now % ZEQOND) / ZEQOND;
    const markerX = phase * W;
    ctx.strokeStyle = '#22c55e';
    ctx.lineWidth = 1;
    ctx.setLineDash([3, 3]);
    ctx.beginPath();
    ctx.moveTo(markerX, 0);
    ctx.lineTo(markerX, H);
    ctx.stroke();
    ctx.setLineDash([]);
  }

  function _setText(id, text) {
    const el = container?.querySelector('#' + id);
    if (el) el.textContent = text;
  }

  function destroy() {
    if (animId) cancelAnimationFrame(animId);
    animId = null;
    initialized = false;
    if (container) container.innerHTML = '';
  }

  return { init, destroy };
})();
