
import { GoogleGenAI } from "@google/genai";

// -- CONFIG & CONSTANTS --
const CONTRACT_ADDRESS = "0x096EB5552E9E451804a538a23960730fD3c251c9";
const EPOCH_DATE = new Date("January 1, 2026 00:00:00").getTime();

// -- INITIALIZE INTERFACE --
window.addEventListener('DOMContentLoaded', () => {
  // @ts-ignore
  lucide.createIcons();
  startBootSequence();
  initNeuralBackground();
  updateCountdown();
  setInterval(updateCountdown, 1000);
  fetchBalance();
  setInterval(fetchBalance, 30000);
});

// -- BOOT SEQUENCE SIMULATION --
async function startBootSequence() {
  const logEl = document.getElementById('boot-log');
  const overlay = document.getElementById('boot-screen');
  const logs = [
    "> INITIATING NEOYEAR BOOTLOADER...",
    "> CONNECTING TO BNB_MAINNET...",
    "> LOADING NEURAL_ORACLE.v3...",
    "> DECRYPTING 2026_GENESIS_BLOCK...",
    "> CALIBRATING TIME_VECTOR...",
    "> STATUS: 100% OPERATIONAL.",
    "> ACCESS GRANTED."
  ];

  for (const line of logs) {
    if (logEl) {
      const lineEl = document.createElement('div');
      lineEl.className = 'mb-1';
      lineEl.innerText = line;
      logEl.appendChild(lineEl);
      await new Promise(r => setTimeout(r, 400));
    }
  }

  setTimeout(() => {
    if (overlay) overlay.style.opacity = '0';
    setTimeout(() => overlay?.remove(), 1000);
  }, 1000);
}

// -- NEURAL NETWORK BACKGROUND --
function initNeuralBackground() {
  const canvas = document.getElementById('neural-bg') as HTMLCanvasElement;
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  let particles: any[] = [];
  const particleCount = 100;

  const resize = () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  };

  window.addEventListener('resize', resize);
  resize();

  class Particle {
    x: number; y: number; vx: number; vy: number;
    constructor() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;
      this.vx = (Math.random() - 0.5) * 0.5;
      this.vy = (Math.random() - 0.5) * 0.5;
    }
    update() {
      this.x += this.vx;
      this.y += this.vy;
      if (this.x < 0 || this.x > canvas.width) this.vx *= -1;
      if (this.y < 0 || this.y > canvas.height) this.vy *= -1;
    }
  }

  for (let i = 0; i < particleCount; i++) particles.push(new Particle());

  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = '#00ffff';
    ctx.lineWidth = 0.2;

    particles.forEach((p, i) => {
      p.update();
      ctx.beginPath();
      ctx.arc(p.x, p.y, 1, 0, Math.PI * 2);
      ctx.fill();

      for (let j = i + 1; j < particles.length; j++) {
        const p2 = particles[j];
        const dist = Math.hypot(p.x - p2.x, p.y - p2.y);
        if (dist < 150) {
          ctx.globalAlpha = 1 - (dist / 150);
          ctx.beginPath();
          ctx.moveTo(p.x, p.y);
          ctx.lineTo(p2.x, p2.y);
          ctx.stroke();
        }
      }
    });
    requestAnimationFrame(animate);
  }
  animate();
}

// -- COUNTDOWN LOGIC --
function updateCountdown() {
  const now = new Date().getTime();
  const diff = EPOCH_DATE - now;

  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const s = Math.floor((diff % (1000 * 60)) / 1000);

  const updateEl = (id: string, val: number) => {
    const el = document.getElementById(id);
    if (el) el.innerText = val < 10 ? `0${val}` : `${val}`;
  };

  updateEl('days', d);
  updateEl('hours', h);
  updateEl('mins', m);
  updateEl('secs', s);
}

// -- BALANCE FETCH --
async function fetchBalance() {
  const el = document.getElementById('bnb-balance');
  try {
    const res = await fetch('https://bsc-dataseed.binance.org/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        jsonrpc: '2.0',
        method: 'eth_getBalance',
        params: [CONTRACT_ADDRESS, 'latest'],
        id: 1,
      }),
    });
    const data = await res.json();
    if (data.result && el) {
      const ethVal = (parseInt(data.result, 16) / 1e18).toFixed(4);
      el.innerText = ethVal;
    }
  } catch (e) {
    console.error("RPC Error:", e);
  }
}

// -- NEO-ORACLE (GEMINI) --
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const chatBox = document.getElementById('chat-box');
const inputEl = document.getElementById('oracle-input') as HTMLInputElement;
const sendBtn = document.getElementById('send-btn');

const appendMessage = (role: string, text: string) => {
  if (!chatBox) return;
  const div = document.createElement('div');
  div.className = 'flex gap-4';
  const label = role === 'user' ? 'USR' : 'AI';
  const color = role === 'user' ? 'text-magenta-500' : 'text-cyan-400';
  div.innerHTML = `
    <div class="w-6 h-6 border border-current ${color} flex items-center justify-center shrink-0 font-bold text-[10px]">${label}</div>
    <div class="${role === 'user' ? 'text-white/60' : color + '/80'}">${text}</div>
  `;
  chatBox.appendChild(div);
  chatBox.scrollTop = chatBox.scrollHeight;
};

async function handleOracleQuery() {
  const query = inputEl.value.trim();
  if (!query) return;

  appendMessage('user', query);
  inputEl.value = '';

  try {
    const response = await ai.models.generateContent({
      model: 'gemini-3-flash-preview',
      contents: query,
      config: {
        systemInstruction: "You are the NeoYear 2026 Oracle, a highly advanced cyberpunk AI from the near future. Your purpose is to provide cryptic but optimistic predictions about the year 2026. Use technical, cyber-noir language. Keep responses concise and focused on decentralization, new beginnings, and digital evolution.",
        temperature: 0.9,
      }
    });

    const text = response.text || "Connection lost. Protocol interrupted.";
    appendMessage('oracle', text);
  } catch (error) {
    appendMessage('oracle', "ERROR: Neural link saturated. Try again later.");
  }
}

sendBtn?.addEventListener('click', handleOracleQuery);
inputEl?.addEventListener('keypress', (e) => {
  if (e.key === 'Enter') handleOracleQuery();
});

// -- UTILS --
(window as any).copyAddress = () => {
  navigator.clipboard.writeText(CONTRACT_ADDRESS);
  const btn = document.querySelector('[onclick="window.copyAddress()"]');
  if (btn) {
    const original = btn.innerHTML;
    btn.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i>';
    // @ts-ignore
    lucide.createIcons();
    setTimeout(() => {
      btn.innerHTML = original;
      // @ts-ignore
      lucide.createIcons();
    }, 2000);
  }
};
