document.addEventListener('DOMContentLoaded', () => {
  initNetworkCanvas();
  initSubnetCalculator();
  initTerminalSimulator();
  initProjectFilters();
  initModalHandlers();
  initContactForm();
  initNavbarScroll();
});

/* -------------------------------------------------------------
   1. Dynamic Background Network Canvas Animation
------------------------------------------------------------- */
function initNetworkCanvas() {
  const canvas = document.getElementById('network-canvas');
  if (!canvas) return;

  const ctx = canvas.getContext('2d');
  let width = (canvas.width = window.innerWidth);
  let height = (canvas.height = window.innerHeight);

  window.addEventListener('resize', () => {
    width = canvas.width = window.innerWidth;
    height = canvas.height = window.innerHeight;
  });

  const mouse = { x: null, y: null, radius: 150 };
  window.addEventListener('mousemove', (e) => {
    mouse.x = e.x;
    mouse.y = e.y;
  });

  const nodeCount = Math.floor((width * height) / 18000);
  const nodes = [];

  for (let i = 0; i < nodeCount; i++) {
    nodes.push({
      x: Math.random() * width,
      y: Math.random() * height,
      vx: (Math.random() - 0.5) * 0.8,
      vy: (Math.random() - 0.5) * 0.8,
      radius: Math.random() * 2 + 1,
    });
  }

  function animate() {
    ctx.clearRect(0, 0, width, height);

    for (let i = 0; i < nodes.length; i++) {
      let n = nodes[i];
      n.x += n.vx;
      n.y += n.vy;

      if (n.x < 0 || n.x > width) n.vx *= -1;
      if (n.y < 0 || n.y > height) n.vy *= -1;

      // Draw Node
      ctx.beginPath();
      ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
      ctx.fillStyle = '#00f2fe';
      ctx.shadowBlur = 8;
      ctx.shadowColor = '#00f2fe';
      ctx.fill();

      // Connect with mouse
      if (mouse.x && mouse.y) {
        let dx = mouse.x - n.x;
        let dy = mouse.y - n.y;
        let dist = Math.sqrt(dx * dx + dy * dy);
        if (dist < mouse.radius) {
          ctx.beginPath();
          ctx.moveTo(n.x, n.y);
          ctx.lineTo(mouse.x, mouse.y);
          ctx.strokeStyle = `rgba(0, 242, 254, ${1 - dist / mouse.radius})`;
          ctx.lineWidth = 0.8;
          ctx.stroke();
        }
      }

      // Connect near nodes
      for (let j = i + 1; j < nodes.length; j++) {
        let n2 = nodes[j];
        let dx = n.x - n2.x;
        let dy = n.y - n2.y;
        let dist = Math.sqrt(dx * dx + dy * dy);

        if (dist < 120) {
          ctx.beginPath();
          ctx.moveTo(n.x, n.y);
          ctx.lineTo(n2.x, n2.y);
          ctx.strokeStyle = `rgba(79, 172, 254, ${0.3 * (1 - dist / 120)})`;
          ctx.lineWidth = 0.5;
          ctx.stroke();
        }
      }
    }

    requestAnimationFrame(animate);
  }

  animate();
}

/* -------------------------------------------------------------
   2. Real-Time IPv4 Subnet / CIDR Calculator
------------------------------------------------------------- */
function initSubnetCalculator() {
  const ipInput = document.getElementById('calc-ip');
  const cidrInput = document.getElementById('calc-cidr');
  const calcBtn = document.getElementById('btn-calculate');

  if (!ipInput || !cidrInput || !calcBtn) return;

  function calculate() {
    const ipStr = ipInput.value.trim();
    const cidr = parseInt(cidrInput.value, 10);

    if (!validateIP(ipStr) || isNaN(cidr) || cidr < 0 || cidr > 32) {
      showToast('❌ Format IP Address atau CIDR Prefix tidak valid!', 'error');
      return;
    }

    const ipNum = ipToInt(ipStr);
    const maskNum = (0xffffffff << (32 - cidr)) >>> 0;
    const wildcardNum = (~maskNum) >>> 0;
    const netNum = (ipNum & maskNum) >>> 0;
    const bcastNum = (netNum | wildcardNum) >>> 0;

    const totalHosts = Math.pow(2, 32 - cidr);
    const usableHosts = cidr >= 31 ? (cidr === 31 ? 2 : 1) : totalHosts - 2;

    const netStr = intToIp(netNum);
    const maskStr = intToIp(maskNum);
    const wildcardStr = intToIp(wildcardNum);
    const bcastStr = intToIp(bcastNum);
    const firstUsable = cidr >= 31 ? netStr : intToIp(netNum + 1);
    const lastUsable = cidr >= 31 ? bcastStr : intToIp(bcastNum - 1);

    document.getElementById('res-network').textContent = `${netStr} /${cidr}`;
    document.getElementById('res-netmask').textContent = maskStr;
    document.getElementById('res-wildcard').textContent = wildcardStr;
    document.getElementById('res-broadcast').textContent = bcastStr;
    document.getElementById('res-usable-range').textContent = `${firstUsable} - ${lastUsable}`;
    document.getElementById('res-total-hosts').textContent = `${usableHosts.toLocaleString()} Host`;
  }

  calcBtn.addEventListener('click', calculate);
  ipInput.addEventListener('keyup', (e) => { if (e.key === 'Enter') calculate(); });
  cidrInput.addEventListener('change', calculate);

  // Initial Calculation
  calculate();
}

function validateIP(ip) {
  const parts = ip.split('.');
  if (parts.length !== 4) return false;
  return parts.every(p => {
    const n = Number(p);
    return !isNaN(n) && n >= 0 && n <= 255 && p === String(n);
  });
}

function ipToInt(ip) {
  return ip.split('.').reduce((acc, octet) => ((acc << 8) + parseInt(octet, 10)) >>> 0, 0);
}

function intToIp(int) {
  return [
    (int >>> 24) & 255,
    (int >>> 16) & 255,
    (int >>> 8) & 255,
    int & 255
  ].join('.');
}

/* -------------------------------------------------------------
   3. Interactive RouterOS & Ping Live Terminal Simulator
------------------------------------------------------------- */
function initTerminalSimulator() {
  const termBody = document.getElementById('terminal-body');
  const termBtns = document.querySelectorAll('.term-btn');
  if (!termBody) return;

  function appendLine(text, type = '') {
    const line = document.createElement('div');
    line.className = `term-line ${type}`;
    line.innerHTML = text;
    termBody.appendChild(line);
    termBody.scrollTop = termBody.scrollHeight;
  }

  function runCmd(cmd) {
    appendLine(`<span class="term-prompt">[admin@MikroTik-CCR2004] ></span> ${cmd}`, 'user-cmd');

    if (cmd === 'ping 8.8.8.8') {
      let count = 0;
      appendLine(`SEQ HOST                                     SIZE TTL TIME  STATUS`);
      const interval = setInterval(() => {
        count++;
        const rtt = (Math.random() * 8 + 10).toFixed(1);
        appendLine(`  ${count} 8.8.8.8                                  56  117 ${rtt}ms`);
        if (count >= 5) {
          clearInterval(interval);
          appendLine(`sent=5 received=5 packet-loss=0% min-rtt=${(10.2).toFixed(1)}ms avg-rtt=${(14.1).toFixed(1)}ms`, 'code-comment');
        }
      }, 500);
    } else if (cmd === 'ip route print') {
      setTimeout(() => {
        appendLine(`Flags: D - DYNAMIC; A - ACTIVE; c - CONNECTED, o - OSPF, b - BGP`);
        appendLine(`Columns: DST-ADDRESS, GATEWAY, DISTANCE`);
        appendLine(`DAo 0.0.0.0/0          10.100.1.1        110`);
        appendLine(`DAc 10.100.1.0/24      ether1-WAN          0`);
        appendLine(`DAc 192.168.10.0/24    bridge-LAN          0`);
        appendLine(`DAb 172.16.0.0/16      10.200.0.2         20`);
        appendLine(`DAo 10.254.0.1/32      wg-tunnel1        110`);
      }, 200);
    } else if (cmd === 'system resource print') {
      setTimeout(() => {
        appendLine(`          uptime: 142d 18h 42m 19s`);
        appendLine(`         version: 7.14.2 (stable)`);
        appendLine(`      build-time: Mar/18/2026 11:20:04`);
        appendLine(`     factory-software: 7.1.1`);
        appendLine(`     free-memory: 3.4GiB`);
        appendLine(`    total-memory: 4.0GiB`);
        appendLine(`             cpu: ARM64-4core`);
        appendLine(`       cpu-count: 4`);
        appendLine(`       cpu-frequency: 1200MHz`);
        appendLine(`        cpu-load: 3%`);
        appendLine(`  architecture-name: arm64`);
        appendLine(`      board-name: CCR2004-16G-2S+`);
      }, 200);
    } else if (cmd === 'interface print') {
      setTimeout(() => {
        appendLine(`Flags: R - RUNNING`);
        appendLine(` #   NAME             TYPE       ACTUAL-MTU  L2MTU`);
        appendLine(` 0 R ether1-WAN       ether            1500   1592`);
        appendLine(` 1 R ether2-LAN       ether            1500   1592`);
        appendLine(` 2 R sfp-sfpplus1     sfp-plus         1500   1592`);
        appendLine(` 3 R wireguard-vpn    wireguard        1420`);
      }, 200);
    } else if (cmd === 'clear') {
      termBody.innerHTML = '';
      appendLine(`<span class="code-comment"># Terminal cleared. Ready for commands...</span>`);
    }
  }

  termBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      const cmd = btn.getAttribute('data-cmd');
      if (cmd) runCmd(cmd);
    });
  });
}

/* -------------------------------------------------------------
   4. Category Filters for Topology Projects
------------------------------------------------------------- */
function initProjectFilters() {
  const filterBtns = document.querySelectorAll('.filter-btn');
  const projectCards = document.querySelectorAll('.project-card');

  filterBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      filterBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');

      const filter = btn.getAttribute('data-filter');

      projectCards.forEach(card => {
        if (filter === 'all' || card.getAttribute('data-category') === filter) {
          card.style.display = 'flex';
          card.style.animation = 'fadeIn 0.4s ease';
        } else {
          card.style.display = 'none';
        }
      });
    });
  });
}

/* -------------------------------------------------------------
   5. Modal Popup Handlers
------------------------------------------------------------- */
function initModalHandlers() {
  const modal = document.getElementById('cert-modal');
  const openBtns = document.querySelectorAll('.open-cert-modal');
  const closeBtn = document.querySelector('.modal-close');

  if (!modal) return;

  openBtns.forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      modal.classList.add('active');
    });
  });

  if (closeBtn) {
    closeBtn.addEventListener('click', () => {
      modal.classList.remove('active');
    });
  }

  window.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.classList.remove('active');
    }
  });
}

/* -------------------------------------------------------------
   6. Contact Form & Toast Notification System
------------------------------------------------------------- */
function initContactForm() {
  const form = document.getElementById('contact-form');
  if (!form) return;

  form.addEventListener('submit', (e) => {
    e.preventDefault();
    showToast('🚀 Pesan Anda berhasil dikirim! Salwa akan segera menghubungi Anda.', 'success');
    form.reset();
  });
}

function showToast(message, type = 'info') {
  let container = document.querySelector('.toast-container');
  if (!container) {
    container = document.createElement('div');
    container.className = 'toast-container';
    document.body.appendChild(container);
  }

  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.innerHTML = `<i class="fas fa-check-circle" style="color:#00f2fe"></i> <span>${message}</span>`;
  
  container.appendChild(toast);

  setTimeout(() => {
    toast.style.opacity = '0';
    toast.style.transform = 'translateX(100%)';
    toast.style.transition = 'all 0.3s ease';
    setTimeout(() => toast.remove(), 300);
  }, 4000);
}

/* -------------------------------------------------------------
   7. Navbar Scroll Effect & Active Section
------------------------------------------------------------- */
function initNavbarScroll() {
  const header = document.querySelector('.header');
  const mobileBtn = document.querySelector('.mobile-menu-btn');
  const navLinks = document.querySelector('.nav-links');

  window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
      header.classList.add('scrolled');
    } else {
      header.classList.remove('scrolled');
    }
  });

  if (mobileBtn && navLinks) {
    mobileBtn.addEventListener('click', () => {
      navLinks.classList.toggle('mobile-open');
    });
  }
}
