import { useState, useEffect } from "react";
import ParticleCanvas from "./components/ParticleCanvas";
import SettingsPanel from "./components/SettingsPanel";
import Navbar from "./components/Navbar";
import CustomCursor from "./components/CustomCursor";
import { type AppSettings, DEFAULT_SETTINGS } from "./types";

const shapesMetadata = [
  "Synaptic Brain",
  "Innovating Lightbulb",
  "DNA Double Helix",
  "Nebula Spindle Star",
  "Structured Octahedron",
  "Geometric Cube",
  "Intersecting Aegis",
  "Flowing Torus",
  "Torus Trefoil Knot",
  "Nova Spire Lattice",
  "Astroid Star",
  "Email Envelope",
  "Quantum Dual Shell",
  "Geodesic Icosahedron",
  "Hyperboloid",
  "Klein Bottle",
  "Holistic Sphere",
  "Cosmic Scattered",
];

const shapeDescriptions = [
  "A neural network simulation representing cognitive synapse firing and complex cerebral connections.",
  "A glowing outline of human invention, mapping creative energy into structured particles.",
  "The genetic blueprint of life, represented as dual-entwined spirals in continuous rotation.",
  "A cosmic star structure resembling a nebula spindle, composed of twelve radiating stellated peaks radiating from a golden-ratio core.",
  "An eight-faced regular solid mapping symmetrical spatial geometry in three dimensions.",
  "A foundational three-dimensional shape demonstrating rigid linear perspective and vertex structures.",
  "A protective self-intersecting grid of overlapping pentagonal shields, creating a complex cage of intersecting planes.",
  "A smooth ring-shaped mathematical surface showcasing continuous particle flow along its contours.",
  "An intricate mathematical knot representing advanced topological looping in 3D space.",
  "A dramatic spike solid capturing the moment of a stellar supernova, mapping intense geometric spires in all directions.",
  "A sharp, four-cusped hypocycloid curve forming a star-shaped generative particle grid.",
  "A digital communication icon modeled as a planar net projected into three-dimensional coordinates.",
  "An inner and outer nested stargate construct, mapping golden-ratio symmetries in concentric multi-colored energy bands.",
  "A twenty-faced platonic solid built from golden-ratio vertices — nature’s most sphere-like polyhedron.",
  "An architectural cooling-tower surface generated by rotating a hyperbola around its conjugate axis.",
  "A non-orientable closed surface with no distinct interior or exterior — topology’s most famous paradox.",
  "A perfect three-dimensional sphere rendered as alternating latitude and longitude orbital outlines.",
  "A chaotic dispersion of stellar dust transitioning into a beautiful entropy-driven cloud."
];

const layoutClasses = [
  "layout-left",   // 0:  Brain
  "layout-right",  // 1:  Lightbulb
  "layout-left",   // 2:  DNA
  "layout-right",  // 3:  SSD (Nebula Spindle Star)
  "layout-left",   // 4:  Octahedron
  "layout-right",  // 5:  Cube
  "layout-left",   // 6:  GD (Intersecting Aegis)
  "layout-right",  // 7:  Torus
  "layout-left",   // 8:  Trefoil Knot
  "layout-right",  // 9:  GSD (Nova Spire Lattice)
  "layout-left",   // 10: Astroid
  "layout-right",  // 11: Envelope
  "layout-left",   // 12: GI (Quantum Dual Shell)
  "layout-right",  // 13: Icosahedron
  "layout-left",   // 14: Hyperboloid
  "layout-right",  // 15: Klein Bottle
  "layout-center", // 16: Sphere
  "layout-center"  // 17: Scattered
];

export default function App() {
  const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const [activeSection, setActiveSection] = useState(0);

  // Sync settings (theme and scroll snapping) to HTML root classes & theme-color meta tag
  useEffect(() => {
    const root = document.documentElement;
    root.classList.toggle("theme-white", settings.theme === "white");
    root.classList.toggle("scroll-snap", settings.scrollSnapEnabled);

    // Update meta theme-color tag dynamically based on the active theme
    const metaTheme = document.querySelector('meta[name="theme-color"]');
    if (metaTheme) {
      metaTheme.setAttribute("content", settings.theme === "white" ? "#ffffff" : "#0d9488");
    }
  }, [settings.theme, settings.scrollSnapEnabled]);

  // Track scroll position to update active dot indicator
  useEffect(() => {
    const handleScroll = () => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
      const ratio = scrollHeight > 0 ? scrollTop / scrollHeight : 0;
      
      const N = 17; // shapes count - 1 (18 shapes total)
      const index = Math.min(Math.round(ratio * N), N);
      setActiveSection(index);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    // Run once initially to capture load state
    handleScroll();

    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // Handle URL hash on initial load
  useEffect(() => {
    const handleInitialHash = () => {
      const hash = window.location.hash.slice(1);
      if (!hash) return;
      
      const index = shapesMetadata.findIndex(
        (name) => name.toLowerCase().replace(/ /g, "-") === hash
      );
      
      if (index !== -1) {
        setTimeout(() => {
          scrollToSection(index);
        }, 100);
      }
    };

    handleInitialHash();
  }, []);

  // Dynamically update document title, meta description, and URL hash as user scrolls
  useEffect(() => {
    const activeShape = shapesMetadata[activeSection];
    const activeDesc = shapeDescriptions[activeSection] || "";
    const hash = activeShape.toLowerCase().replace(/ /g, "-");

    // Dynamic Title
    document.title = `${activeShape} - 3D Constructs`;

    // Dynamic Description
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) {
      metaDesc.setAttribute("content", activeDesc);
    }

    // Bidirectional Hash Sync
    if (window.location.hash !== `#${hash}`) {
      const url = new URL(window.location.href);
      url.hash = hash;
      window.history.replaceState(null, "", url.toString());
    }
  }, [activeSection]);

  const scrollToSection = (index: number) => {
    const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
    const targetScroll = (index / 17) * scrollHeight;
    window.scrollTo({
      top: targetScroll,
      behavior: "smooth",
    });
  };

  return (
    <div style={{ minHeight: "1800vh", position: "relative" }}>
      {/* Visually hidden H1 for Document Heading Structure */}
      <h1 className="sr-only">3D Constructs - Interactive Particle Visualizer</h1>

      {/* Premium Custom Cursor */}
      <CustomCursor />

      {/* Background Interactive Canvas */}
      <ParticleCanvas settings={settings} />

      {/* Left Sidebar Navigation */}
      <Navbar
        activeSection={activeSection}
        onNavigate={scrollToSection}
        onOpenSettings={() => setIsSettingsOpen(true)}
        colors={settings.colors}
      />

      {/* Scroll Indicators Sidebar */}
      <div className="scroll-indicator-bar" role="navigation" aria-label="Section Quick Jump">
        {shapesMetadata.map((shapeName, index) => (
          <div
            key={index}
            role="button"
            tabIndex={0}
            aria-label={`Scroll to ${shapeName}`}
            aria-current={activeSection === index ? "true" : undefined}
            className={`scroll-dot ${activeSection === index ? "active" : ""}`}
            onClick={() => scrollToSection(index)}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                scrollToSection(index);
              }
            }}
            title={`Scroll to ${shapeName}`}
          />
        ))}
      </div>

      {/* Floating Settings panel overlay */}
      <SettingsPanel
        settings={settings}
        onChange={setSettings}
        isOpen={isSettingsOpen}
        onToggle={() => setIsSettingsOpen(false)}
      />

      {/* Semantic Sections containing Headings and Descriptions */}
      {shapesMetadata.map((shapeName, index) => (
        <section
          key={index}
          id={shapeName.toLowerCase().replace(/ /g, "-")}
          className={`section ${layoutClasses[index]}`}
          style={{ pointerEvents: "none" }}
        >
          <div 
            className={`section-content ${activeSection === index ? "active" : ""}`}
            style={{ pointerEvents: "auto" }}
          >
            {activeSection === index ? (
              <h1>{shapeName}</h1>
            ) : (
              <h2>{shapeName}</h2>
            )}
            <p>{shapeDescriptions[index]}</p>
          </div>
        </section>
      ))}
    </div>
  );
}
