/**
 * Brash Interactive Demo: Real-time Attack Configuration Interface
 *
 * Provides an interactive web interface for configuring and executing Brash attacks
 * with real-time metrics, preset configurations, and visual feedback.
 *
 * @author Jose Pino
 * @contact jose@pino.sh (https://x.com/jofpin)
 * @github github.com/jofpin/brash
 * @license MIT
 *
 * © 2025 Jose Pino | Released: Oct 28, 2025
 */
const exploitDemo = {
  isRunning: false,
  intervalId: null,
  startTime: null,
  lastUpdate: null,
  updateCount: 0,
  elements: {
    status: document.getElementById("status"),
    updatesPerSec: document.getElementById("updatesPerSec"),
    totalUpdates: document.getElementById("totalUpdates"),
    burstSlider: document.getElementById("burstSlider"),
    burstValue: document.getElementById("burstValue"),
    intervalSlider: document.getElementById("intervalSlider"),
    intervalValue: document.getElementById("intervalValue"),
    startBtn: document.getElementById("startBtn"),
    stopBtn: document.getElementById("stopBtn"),
    presetBtns: document.querySelectorAll(".BrashExploitDemo-presetBtn"),
  },

  /**
   * Predefined attack configurations
   * @type {Object}
   * @property {Object} moderate - Controlled observation mode (~600 updates/sec)
   * @property {Object} aggressive - Fast saturation mode (~60K updates/sec)
   * @property {Object} extreme - Instant collapse mode (~24M updates/sec)
   */
  presets: {
    moderate: { burstSize: 200, interval: 1000 },
    aggressive: { burstSize: 2000, interval: 100 },
    extreme: { burstSize: 8000, interval: 1 },
  },

  /**
   * Initializes the demo interface
   * Sets up event listeners for sliders, preset buttons, and action buttons
   * Starts the metrics update loop for real-time feedback
   */
  init() {
    // Slider listeners - Update displayed values in real-time
    this.elements.burstSlider.addEventListener("input", (e) => {
      this.elements.burstValue.textContent = e.target.value;
    });

    this.elements.intervalSlider.addEventListener("input", (e) => {
      this.elements.intervalValue.textContent = e.target.value;
    });

    // Preset buttons - Apply predefined configurations
    this.elements.presetBtns.forEach((btn) => {
      btn.addEventListener("click", () => {
        const preset = btn.dataset.preset;
        this.applyPreset(preset);

        // Visual feedback: highlight active preset
        this.elements.presetBtns.forEach((b) => b.classList.remove("active"));
        btn.classList.add("active");
      });
    });

    // Action buttons - Start/Stop attack execution
    this.elements.startBtn.addEventListener("click", () => this.start());
    this.elements.stopBtn.addEventListener("click", () => this.stop());

    // Start metrics update loop (runs every 100ms)
    setInterval(() => this.updateStats(), 100);
  },

  /**
   * Applies a predefined attack configuration
   * Updates both slider values and their displayed labels
   *
   * @param {string} preset - Preset name: "moderate", "aggressive", or "extreme"
   */
  applyPreset(preset) {
    const config = this.presets[preset];

    // Update slider values
    this.elements.burstSlider.value = config.burstSize;
    this.elements.burstValue.textContent = config.burstSize;
    this.elements.intervalSlider.value = config.interval;
    this.elements.intervalValue.textContent = config.interval;
  },

  /**
   * Starts the Brash attack with current configuration
   * Reads slider values, initializes metrics, and launches the exploit
   * Updates UI state and enables real-time statistics
   */
  start() {
    // Prevent double-start
    if (this.isRunning) return;

    // Read current configuration from sliders
    const burstSize = parseInt(this.elements.burstSlider.value);
    const interval = parseInt(this.elements.intervalSlider.value);

    // Initialize metrics tracking
    this.updateCount = 0;
    this.startTime = Date.now();
    this.lastUpdate = this.startTime;

    // Update UI state
    this.isRunning = true;
    this.elements.status.textContent = "Running";
    this.elements.status.classList.add("active");
    this.elements.startBtn.disabled = true;
    this.elements.stopBtn.disabled = false;

    // Launch Brash exploit
    Brash.run({ burstSize, interval });

    console.log(`Attack started: burstSize=${burstSize}, interval=${interval}ms`,);
  },

  /**
   * Stops the demo UI and disables controls
   *
   * Note: This only stops the UI metrics. The actual Brash attack cannot be stopped
   * once started due to the nature of setInterval. A full page refresh is required
   * to terminate the exploit completely.
   */
  stop() {
    if (!this.isRunning) return;

    // Update state
    this.isRunning = false;

    // Update UI to reflect stopped state
    this.elements.status.textContent = "Stopped (requires refresh)";
    this.elements.status.classList.remove("active");
    this.elements.startBtn.disabled = true;
    this.elements.stopBtn.disabled = true;

    console.log("Attack UI stopped: Brash will continue running until page refresh.");
  },

  /**
   * Updates real-time attack statistics
   * Calculates and displays total updates and updates per second
   * Called every 100ms by the metrics update loop
   *
   * Metrics calculated:
   * - Total Updates: Cumulative document.title mutations from Brash.counter
   * - Updates/Second: Rate of mutations calculated from delta over time
   */
  updateStats() {
    // Only update if attack is running
    if (!this.isRunning) return;

    // Ensure Brash is available and has executed updates
    if (typeof Brash !== "undefined" && Brash.counter) {
      // Display total cumulative updates
      this.elements.totalUpdates.textContent = Brash.counter.toLocaleString();

      // Calculate updates per second (rate)
      const now = Date.now();
      const elapsed = (now - this.lastUpdate) / 1000; // Convert to seconds
      const newUpdates = Brash.counter - this.updateCount; // Delta since last check
      const updatesPerSec = Math.round(newUpdates / elapsed);

      // Display current rate
      this.elements.updatesPerSec.textContent = updatesPerSec.toLocaleString();

      // Update tracking state for next calculation
      this.updateCount = Brash.counter;
      this.lastUpdate = now;
    }
  },
};

// Initialize the interactive demo
exploitDemo.init();