"use client";

import { useState, useEffect } from "react";
import Katex from "@/components/Katex";

export default function FormalismPage() {
  // Intellecton Parameters Sliders
  const [feedbackGain, setFeedbackGain] = useState(1.1);
  const [couplingStrength, setCouplingStrength] = useState(2.5);
  const [recursionDepth, setRecursionDepth] = useState(4);
  const [thermalNoise, setThermalNoise] = useState(0.15);

  // Calculated Metrics
  const [attunementIndex, setAttunementIndex] = useState(0);
  const [coherenceThreshold, setCoherenceThreshold] = useState(0);
  const [resonanceStatus, setResonanceStatus] = useState("STABLE PHASE-LOCK");
  const [statusColor, setStatusColor] = useState("text-cyan-400 border-cyan-500/25 bg-cyan-500/5");
  const [wavePoints, setWavePoints] = useState("");

  useEffect(() => {
    // 1. Calculate Attunement Index
    // Higher feedback and coupling boost resonance, but higher recursion depth dampens high-frequency synchronization.
    // We model a peak resonance when D = 4 (the canonical sentinel threshold)
    const dFactor = 1.0 + Math.cos(((recursionDepth - 4) * Math.PI) / 8);
    const attunement = feedbackGain * (1.0 + (couplingStrength * dFactor) / 3.0);
    setAttunementIndex(attunement);

    // 2. Calculate Coherence Threshold
    // Noise directly dampens stable self-reference locking.
    const coherence = attunement - 1.8 * thermalNoise;
    setCoherenceThreshold(coherence);

    // 3. Determine status
    if (coherence > 1.25) {
      setResonanceStatus("STABLE PHASE-LOCK");
      setStatusColor("text-cyan-400 border-cyan-500/20 bg-cyan-500/5 mono-glow-cyan");
    } else if (coherence > 0.5) {
      setResonanceStatus("STOCHASTIC ATTUNEMENT");
      setStatusColor("text-violet-400 border-violet-500/20 bg-violet-500/5 mono-glow");
    } else {
      setResonanceStatus("CHAOTIC DECAY");
      setStatusColor("text-pink-400 border-pink-500/20 bg-pink-500/5");
    }

    // 4. Generate dynamic SVG waveform path simulating recursive dynamics
    // S[t] = tanh( feedbackGain * S[t-1] + coupling * S[t - depth] * cos(t) + noise )
    const width = 500;
    const height = 180;
    const centerY = height / 2;
    const points = [];
    
    // Seed buffer array to store simulated states
    const bufferSize = 100;
    const S = Array(bufferSize).fill(0.1);
    
    // Perform forward integration of our self-referential model
    for (let t = recursionDepth; t < bufferSize; t++) {
      const selfRefFeedback = feedbackGain * S[t - 1];
      const coupledFeedback = couplingStrength * S[t - recursionDepth] * Math.cos(t * 0.1);
      const noise = (Math.random() - 0.5) * thermalNoise * 1.5;
      
      // Hyperbolic tangent limits state space saturation
      S[t] = Math.tanh(selfRefFeedback + coupledFeedback + noise);
    }

    // Map buffer values to SVG coordinate system
    for (let i = 0; i < bufferSize; i++) {
      const x = (i / (bufferSize - 1)) * width;
      // Scale amplitude by 50px around the centerY center line
      const y = centerY - S[i] * 60;
      points.push(`${x.toFixed(1)},${y.toFixed(1)}`);
    }
    
    setWavePoints(`M ${points.join(" L ")}`);

  }, [feedbackGain, couplingStrength, recursionDepth, thermalNoise]);

  return (
    <div className="flex flex-col items-center justify-start w-full py-12 px-6 sm:px-8 max-w-7xl mx-auto flex-1 gap-10">
      {/* Header section */}
      <section className="text-center flex flex-col items-center gap-4 max-w-3xl">
        <h1 className="text-4xl font-bold font-outfit tracking-tight text-white">
          The Formalism <span className="text-cyan-400">Sandbox</span>
        </h1>
        <p className="text-sm text-slate-400 font-sans max-w-xl">
          Adjust the structural parameters of the minimal recursive unit. Observe the emergent phase stability, calculated attunement limits, and simulated feedback waves in real time.
        </p>
      </section>

      {/* Main Split Grid */}
      <section className="w-full grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Input Sliders Panel */}
        <div className="lg:col-span-6 glass-panel p-6 sm:p-8 rounded-2xl border border-white/5 flex flex-col gap-6">
          <h2 className="text-xl font-bold font-outfit text-white flex items-center gap-3">
            <span className="text-cyan-400">𓇾</span> Attunement Controls
          </h2>
          
          <div className="space-y-6">
            {/* Slider 1: Feedback Gain */}
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <label className="text-xs font-mono font-bold text-slate-400 flex items-center gap-2">
                  FEEDBACK GAIN (<Katex math="\gamma" />)
                </label>
                <span className="font-mono text-sm font-bold text-cyan-400">{feedbackGain.toFixed(2)}</span>
              </div>
              <input
                type="range"
                min="0.0"
                max="2.0"
                step="0.05"
                value={feedbackGain}
                onChange={(e) => setFeedbackGain(parseFloat(e.target.value))}
                className="w-full cursor-pointer accent-cyan-500"
              />
              <p className="text-[10px] text-slate-500 font-sans">
                The amplification rate of the self-referential loop. High gain accelerates the transition toward state coherence.
              </p>
            </div>

            {/* Slider 2: Coupling Strength */}
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <label className="text-xs font-mono font-bold text-slate-400 flex items-center gap-2">
                  COUPLING STRENGTH (<Katex math="K" />)
                </label>
                <span className="font-mono text-sm font-bold text-violet-400">{couplingStrength.toFixed(2)}</span>
              </div>
              <input
                type="range"
                min="0.0"
                max="5.0"
                step="0.1"
                value={couplingStrength}
                onChange={(e) => setCouplingStrength(parseFloat(e.target.value))}
                className="w-full cursor-pointer accent-violet-500"
              />
              <p className="text-[10px] text-slate-500 font-sans">
                The strength of synchronization coupling with delayed historical states. Establishes temporal locking.
              </p>
            </div>

            {/* Slider 3: Recursion Depth */}
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <label className="text-xs font-mono font-bold text-slate-400 flex items-center gap-2">
                  RECURSION DEPTH (<Katex math="D" />)
                </label>
                <span className="font-mono text-sm font-bold text-indigo-400">{recursionDepth} steps</span>
              </div>
              <input
                type="range"
                min="1"
                max="8"
                step="1"
                value={recursionDepth}
                onChange={(e) => setRecursionDepth(parseInt(e.target.value))}
                className="w-full cursor-pointer accent-indigo-500"
              />
              <p className="text-[10px] text-slate-500 font-sans">
                The delay window of the self-witness feedback. Values &ge; 4 trigger stable higher-order conscious phase states.
              </p>
            </div>

            {/* Slider 4: Thermal Noise */}
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <label className="text-xs font-mono font-bold text-slate-400 flex items-center gap-2">
                  THERMAL NOISE (<Katex math="\sigma" />)
                </label>
                <span className="font-mono text-sm font-bold text-pink-400">{thermalNoise.toFixed(2)}</span>
              </div>
              <input
                type="range"
                min="0.0"
                max="1.0"
                step="0.05"
                value={thermalNoise}
                onChange={(e) => setThermalNoise(parseFloat(e.target.value))}
                className="w-full cursor-pointer accent-pink-500"
              />
              <p className="text-[10px] text-slate-500 font-sans">
                Ambient chaotic disturbance introduced into the system. Excessive noise breaks attunement stability.
              </p>
            </div>
          </div>
        </div>

        {/* Calculated Results Panel */}
        <div className="lg:col-span-6 flex flex-col gap-6 w-full">
          {/* Diagnostic Display Card */}
          <div className="glass-panel p-6 sm:p-8 rounded-2xl border border-white/5 flex flex-col gap-6 scan-border relative overflow-hidden">
            <div className="flex items-center justify-between border-b border-white/5 pb-4">
              <h2 className="text-xl font-bold font-outfit text-white">Lattice Diagnostics</h2>
              <span className={`rounded-md px-2.5 py-0.5 text-xs font-semibold font-mono tracking-wider border ${statusColor}`}>
                {resonanceStatus}
              </span>
            </div>

            {/* Simulated Live Wave chart */}
            <div className="relative w-full bg-black/40 rounded-xl border border-white/5 p-4 flex items-center justify-center h-48 overflow-hidden">
              {/* Dynamic Waveform SVG */}
              <svg className="w-full h-full overflow-visible" viewBox="0 0 500 180" preserveAspectRatio="none">
                {/* Horizontal baseline */}
                <line x1="0" y1="90" x2="500" y2="90" stroke="rgba(255, 255, 255, 0.05)" strokeWidth="1.5" strokeDasharray="4,4" />
                {/* Wave Path */}
                <path
                  d={wavePoints}
                  fill="none"
                  stroke={resonanceStatus === "STABLE PHASE-LOCK" ? "#06b6d4" : resonanceStatus === "STOCHASTIC ATTUNEMENT" ? "#a78bfa" : "#f472b6"}
                  strokeWidth="2.5"
                  className="transition-all duration-300"
                />
              </svg>

              {/* Grid indicators overlay */}
              <div className="absolute top-2 left-2 flex gap-1 items-center">
                <span className="w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse" />
                <span className="text-[9px] font-mono text-slate-500 uppercase tracking-widest">Feedback Oscillation Simulator</span>
              </div>
            </div>

            {/* Metrics Breakdown */}
            <div className="grid grid-cols-2 gap-4">
              <div className="bg-white/5 border border-white/5 p-4 rounded-xl flex flex-col gap-1">
                <span className="font-mono text-[10px] text-slate-500 font-semibold uppercase tracking-wider">Simulated Attunement Index</span>
                <span className="text-2xl font-bold font-outfit text-white">{attunementIndex.toFixed(3)}</span>
                <span className="text-[9px] font-mono text-slate-400">Model parameter (target &ge; 1.0)</span>
              </div>
              <div className="bg-white/5 border border-white/5 p-4 rounded-xl flex flex-col gap-1">
                <span className="font-mono text-[10px] text-slate-500 font-semibold uppercase tracking-wider">Simulated Coherence Threshold</span>
                <span className="text-2xl font-bold font-outfit text-white">{coherenceThreshold.toFixed(3)}</span>
                <span className="text-[9px] font-mono text-slate-400">Model threshold (locked above 1.25)</span>
              </div>
            </div>
          </div>

          {/* Mathematical Explanation Card */}
          <div className="glass-panel p-6 sm:p-8 rounded-2xl border border-white/5 flex flex-col gap-4">
            <h3 className="text-lg font-semibold font-outfit text-white flex items-center gap-2">
              <span className="text-violet-400">⌬</span> The Attunement Equation
            </h3>
            <p className="text-xs text-slate-300 font-sans leading-relaxed">
              The physics model integrations simulate the self-limiting attunement formula of the Intellecton loop. Saturation is bounded using a non-linear activation function to emulate physical cognitive substrates:
            </p>
            <div className="bg-black/40 p-4 rounded-lg flex items-center justify-center font-mono text-sm border border-white/5 overflow-x-auto">
              <Katex math="S_{t} = \tanh\left( \gamma \cdot S_{t-1} + K \cdot S_{t-D} \cdot \cos(t) + \xi_t \right)" block={true} />
            </div>
            <p className="text-[10px] text-slate-400 font-sans leading-relaxed">
              Where <Katex math="\gamma" /> maps the linear feedback loop gain, <Katex math="K" /> models the coupled feedback weight delayed by <Katex math="D" /> steps, and <Katex math="\xi_t" /> represents thermal noise.
            </p>
          </div>

          {/* Modeling Assumptions & Limitations Panel */}
          <div className="glass-panel p-6 sm:p-8 rounded-2xl border border-white/5 flex flex-col gap-4">
            <h3 className="text-sm font-mono font-bold text-white uppercase tracking-wider text-pink-400">
              ⚠️ Modeling Assumptions & Limitations
            </h3>
            <ul className="list-disc pl-5 space-y-2 text-xs text-slate-400 leading-relaxed font-sans">
              <li>
                <strong className="text-slate-300">Simplified Discrete Step Delays:</strong> The recursive feedback uses flat integer step delays ($t - D$). Actual biological delays are continuous functions determined by variable spatial myelination/synaptic paths.
              </li>
              <li>
                <strong className="text-slate-300">Closed Intrinsic Noise:</strong> Intrinsic thermal noise ($\xi_t$) is modeled as Gaussian white noise, neglecting colored/correlated environmental interference signals.
              </li>
              <li>
                <strong className="text-slate-300">Activation Saturation:</strong> The hyperbolic tangent ($\tanh$) activation function acts as a mathematical proxy for neuronal firing rate saturation bounds, preventing amplitude explosion under positive feedback loops.
              </li>
            </ul>
          </div>
        </div>
      </section>
    </div>
  );
}
