import { Helmet } from "react-helmet";
import { useOutletContext } from "react-router-dom";
import { useEffect, useCallback } from "react";

import { useGameStore } from "../store/useGameStore";
import { formatNumber } from "../utils/formatNumber";
import { GeneratorShop } from "../components/GeneratorShop";
import { PrestigePanel } from "../components/PrestigePanel";
import { EvolutionTree } from "../components/EvolutionTree";
import { MilestoneBar } from "../components/MilestoneBar";
import "../scss/home.scss";

export default function Home() {
  const [toggleRain] = useOutletContext();
  const click = useGameStore((s) => s.click);
  const resources = useGameStore((s) => s.state.resources);
  const clickMultiplier = useGameStore((s) => s.state.clickMultiplier);

  const createParticle = useCallback((clientX, clientY) => {
    const particle = document.createElement("span");
    particle.className = "click-particle";
    particle.textContent = `+${formatNumber(clickMultiplier)}`;
    particle.style.left = `${clientX}px`;
    particle.style.top = `${clientY}px`;
    document.body.appendChild(particle);
    setTimeout(() => {
      if (particle.parentNode) particle.parentNode.removeChild(particle);
    }, 800);
  }, [clickMultiplier]);

  const handleIncrement = useCallback((e) => {
    click();
    createParticle(e.clientX, e.clientY);
  }, [click, createParticle]);

  // Rain effect (ambiance)
  useEffect(() => {
    const rain = {
      wind: 0, maxXrange: 40, minXrange: 20, maxSpeed: 1, minSpeed: 3,
      color: "#8ecae6", char: "~", maxSize: 32, minSize: 10,
      flakes: [], WIDTH: -10, HEIGHT: 0, running: false,
      init(nb) {
        const frag = document.createDocumentFragment();
        this.getSize();
        this.running = true;
        for (let i = 0; i < nb; i++) {
          const flake = {
            x: this.random(this.WIDTH), y: -this.maxSize,
            xrange: this.minXrange + this.random(this.maxXrange - this.minXrange),
            yspeed: this.minSpeed + this.random(this.maxSpeed - this.minSpeed, 100),
            life: 0, size: this.minSize + this.random(this.maxSize - this.minSize),
            html: document.createElement("span"),
          };
          Object.assign(flake.html.style, {
            position: "absolute", top: `${flake.y}px`, left: `${flake.x}px`,
            fontSize: `${flake.size}px`, color: this.color, userSelect: "none", overflow: "hidden",
          });
          flake.html.appendChild(document.createTextNode(this.char));
          frag.appendChild(flake.html);
          this.flakes.push(flake);
        }
        document.body.appendChild(frag);
        this.animate();
        window.onresize = () => this.getSize();
      },
      animate() {
        if (!this.running) return;
        for (const flake of this.flakes) {
          const top = flake.y + flake.yspeed;
          const left = flake.x + Math.sin(flake.life) * flake.xrange + this.wind;
          if (top < this.HEIGHT - flake.size - 10 && left < this.WIDTH - flake.size && left > 0) {
            flake.html.style.top = `${top}px`;
            flake.html.style.left = `${left}px`;
            flake.y = top;
            flake.x += this.wind;
            flake.life += 0.01;
          } else {
            flake.html.style.top = `${-this.maxSize}px`;
            flake.x = this.random(this.WIDTH);
            flake.y = -this.maxSize;
            flake.html.style.left = `${flake.x}px`;
            flake.life = 0;
          }
        }
        setTimeout(() => this.animate(), 20);
      },
      stop() {
        this.running = false;
        for (const flake of this.flakes) {
          if (flake.html.parentNode) flake.html.parentNode.removeChild(flake.html);
        }
        this.flakes = [];
      },
      random(range, num = 1) {
        return Math.floor(Math.random() * (range + 1) * num) / num;
      },
      getSize() {
        this.WIDTH = document.body.clientWidth || window.innerWidth;
        this.HEIGHT = document.body.clientHeight || window.innerHeight;
      },
    };

    if (toggleRain) rain.init(10);
    return () => rain.stop();
  }, [toggleRain]);

  return (
    <main className="game-cover">
      <Helmet>
        <meta name="description" content="Clickerz — Clicker idle dans le Tetard Universe." />
        <title>Clickerz — Tetard Universe</title>
      </Helmet>

      {/* Clicker area — centre */}
      <div className="click-zone" onClick={handleIncrement}>
        <div className="tadpole-sprite" />
        <div className="text-center text-3xl md:text-4xl font-bold text-white drop-shadow-lg font-[var(--font)] select-none pointer-events-none">
          {formatNumber(resources)}
        </div>
      </div>

      {/* Game panels — sidebar (right desktop, bottom mobile) */}
      <aside className="game-sidebar">
        <MilestoneBar />
        <GeneratorShop />
        <PrestigePanel />
        <EvolutionTree />
      </aside>
    </main>
  );
}
