import React from 'react';
import { BookOpen, X, Cpu, BarChart2, Compass, ShieldAlert, Activity } from 'lucide-react';
import 'katex/dist/katex.min.css';
import { BlockMath, InlineMath } from 'react-katex';

interface CryptoMathModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function CryptoMathModal({ isOpen, onClose }: CryptoMathModalProps) {
  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };
    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown);
    }
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/85 backdrop-blur-md p-4 sm:p-6 md:p-8 animate-fade-in">
      <div className="bg-slate-900 border border-slate-800/80 rounded-3xl w-full max-w-4xl h-[80vh] flex flex-col overflow-hidden shadow-2xl relative text-slate-300">
        
        {/* Modal Header */}
        <div className="flex justify-between items-center px-6 py-4 bg-slate-950/45 border-b border-slate-800/60">
          <div>
            <h2 className="text-base font-bold bg-gradient-to-r from-cyan-400 to-sky-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-cyan-400" /> Crypto Bayesian Markov - Math & Logic Specification
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">Institutional Specification Manual</p>
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-200 bg-slate-950/50 border border-slate-800 hover:border-slate-700 p-2 rounded-xl transition-all cursor-pointer flex items-center justify-center"
            aria-label="Close modal"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-6 sm:p-8 space-y-8 text-slate-300 scrollbar-thin">
          
          <div className="border-b border-slate-800/80 pb-3">
            <h3 className="text-base font-bold text-slate-200">4. Crypto Bayesian Markov Engine</h3>
            <p className="text-xs text-slate-400 mt-1">Models momentum regimes and updates transition probabilities using on-chain alpha inputs.</p>
          </div>

          {/* Section A: Markov Chain State Space */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">A. Markov Chain State Space</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The asset return state space is mapped into 3 momentum regimes:
            </p>
            <div className="grid grid-cols-3 gap-3 text-xs text-slate-400 font-mono text-center">
              <div className="bg-slate-950/40 p-3 rounded-lg border border-slate-800/50">
                <span className="block text-rose-400 font-bold">State 1 (S1)</span>
                <span>Bearish Squeeze / Crackdown</span>
              </div>
              <div className="bg-slate-955/40 p-3 rounded-lg border border-slate-800/50">
                <span className="block text-slate-300 font-bold">State 2 (S2)</span>
                <span>Consolidation / Mean Reversion</span>
              </div>
              <div className="bg-slate-955/40 p-3 rounded-lg border border-slate-800/50">
                <span className="block text-emerald-400 font-bold">State 3 (S3)</span>
                <span>Parabolic Bull Run</span>
              </div>
            </div>
          </div>

          {/* Section B: Transition Matrix (P) */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">B. Transition Matrix (P)</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Calculates transition probabilities over rolling 90-day return vectors:
            </p>
            <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
              <BlockMath math="P = \\begin{bmatrix} p_{11} & p_{12} & p_{13} \\\\ p_{21} & p_{22} & p_{23} \\\\ p_{31} & p_{32} & p_{33} \\end{bmatrix}" />
              <p className="text-[11px] text-slate-400 font-mono mt-2 text-center">
                {"where "}<InlineMath math="p_{ij} = P(X_{t+1} = S_j \\mid X_t = S_i)" />{" represents the frequency probability of moving from State i to State j."}
              </p>
            </div>
          </div>

          {/* Section C: Bayesian Update Engine */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">C. Bayesian Update Engine</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              When external alpha inputs (e.g. Funding Rate anomalies, Whale inflows) occur, state probabilities are updated using Bayes' theorem:
            </p>
            <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
              <BlockMath math="P(S_i \\mid \\text{Alpha}) = \\frac{P(\\text{Alpha} \\mid S_i) \\times P(S_i)}{\\sum_{j=1}^3 P(\\text{Alpha} \\mid S_j) \\times P(S_j)}" />
              <p className="text-[11px] text-slate-400 mt-2 font-mono leading-relaxed">
                {"Where:"}
                <br />
                {"- "}<InlineMath math="P(S_i)" />{" is the prior state probability from the Markov transition matrix."}
                <br />
                {"- "}<InlineMath math="P(\\text{Alpha} \\mid S_i)" />{" is the conditional likelihood of observing this whale spike / funding squeeze in State i."}
              </p>
            </div>
          </div>

          {/* Section D: Two-Stage Hybrid Machine Learning Pipeline */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">D. Two-Stage Hybrid Machine Learning Pipeline</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              To minimize false signals and adapt to changing momentum regimes, we run a two-stage hybrid ML pipeline. First, a client-side Random Forest Classifier maps non-linear combinations of four features to forecast trend probabilities:
            </p>
            <div className="bg-slate-950/40 p-5 rounded-2xl border border-slate-800/60 space-y-3">
              <span className="text-xs font-semibold text-slate-200 block">Ensemble Feature Inputs:</span>
              <ul className="text-xs text-slate-400 list-disc pl-5 space-y-1">
                <li><strong className="text-cyan-400">Funding Rates (\\(FR_t\\)):</strong> Measures leverage imbalance in futures contracts.</li>
                <li><strong className="text-cyan-400">Open Interest Volatility (\\(OI_t\\)):</strong> Captures the contract buildup speed.</li>
                <li><strong className="text-cyan-400">Long/Short Retail Skew (\\(LS_t\\)):</strong> Identifies retail sentiment extremes.</li>
                <li><strong className="text-cyan-400">Whale Accumulation Inflows (\\(W_t\\)):</strong> Proxy for cold-wallet transfer velocities.</li>
              </ul>
              <p className="text-xs text-slate-400 leading-relaxed pt-2">
                The Random Forest ensemble evaluates 10 non-linear decision trees to output the short-term and medium-term trend probabilities:
              </p>
              <BlockMath math="P_{\\text{ML}} = \\frac{1}{M} \\sum_{m=1}^{M} T_m(FR_t, OI_t, LS_t, W_t)" />
            </div>
          </div>

          {/* Section E: Conjugate Beta-Binomial Error-Correction Engine */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">E. Conjugate Beta-Binomial Error-Correction Engine</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Raw ML forecasts are susceptible to regime drift. We implement a self-correcting Beta-Binomial update. The continuous probability output from the Random Forest model is mapped into a discrete Binomial likelihood by defining the Trust-Weight Hyperparameter (<InlineMath math="w" />) as the Effective Sample Size (ESS):
            </p>
            <div className="bg-slate-955/40 p-5 rounded-2xl border border-slate-850 space-y-4">
              <div>
                <p className="text-xs text-slate-350 mb-2 font-semibold">1. Prior Distribution (Accuracy History):</p>
                <BlockMath math="\\theta \\sim \\text{Beta}(\\alpha_{\\text{prior}}, \\beta_{\\text{prior}})" />
                <p className="text-[10px] text-slate-500 font-mono">
                  where <InlineMath math="\\alpha_{\\text{prior}}" /> represents historical prediction successes and <InlineMath math="\\beta_{\\text{prior}}" /> represents false alarms.
                </p>
              </div>

              <div>
                <p className="text-xs text-slate-350 mb-2 font-semibold">2. Likelihood Formulation (Binomial pseudo-observations):</p>
                <BlockMath math="P(x \\mid \\theta) = \\binom{w}{k} \\theta^k (1 - \\theta)^{w - k}" />
                <p className="text-[10px] text-slate-500 font-mono">
                  where <InlineMath math="k = P_{\\text{ML}} \\times w" /> is the number of simulated successes and <InlineMath math="w - k = (1 - P_{\\text{ML}}) \\times w" /> is the number of simulated failures.
                </p>
              </div>

              <div>
                <p className="text-xs text-slate-350 mb-2 font-semibold">3. Conjugate Posterior Update:</p>
                <BlockMath math="\\alpha_{\\text{post}} = \\alpha_{\\text{prior}} + k, \\quad \\beta_{\\text{post}} = \\beta_{\\text{prior}} + (w - k)" />
              </div>
            </div>
          </div>

          {/* Section F: Mathematical Proof of Posterior Mean Integration */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">F. Mathematical Proof of Posterior Mean Integration</h4>
            <p className="text-xs leading-relaxed text-slate-400">
              To resolve a single operational point-estimate from our posterior distribution, we integrate out the continuous parameter <InlineMath math="\\theta" /> to calculate the mathematical expectation of the posterior distribution:
            </p>
            <div className="bg-slate-955/40 p-5 rounded-2xl border border-slate-850 space-y-4">
              <p className="text-xs text-slate-350 font-semibold">Posterior Expectation Integral Proof:</p>
              <BlockMath math="\\mathbb{E}[\\theta \\mid \\text{Data}] = \\int_{0}^{1} \\theta \\cdot P(\\theta \\mid \\text{Data}) \\, d\\theta = \\int_{0}^{1} \\theta \\cdot \\frac{\\theta^{\\alpha_{\\text{post}}-1}(1-\\theta)^{\\beta_{\\text{post}}-1}}{\\text{B}(\\alpha_{\\text{post}}, \\beta_{\\text{post}})} \\, d\\theta" />
              <p className="text-xs text-slate-400 leading-relaxed">
                Using the definition of the Beta function <InlineMath math="\\text{B}(a, b) = \\frac{\\Gamma(a)\\Gamma(b)}{\\Gamma(a+b)}" /> and the recurrence relation <InlineMath math="\\Gamma(x+1) = x\\Gamma(x)" />:
              </p>
              <BlockMath math="\\mathbb{E}[\\theta \\mid \\text{Data}] = \\frac{\\text{B}(\\alpha_{\\text{post}} + 1, \\beta_{\\text{post}})}{\\text{B}(\\alpha_{\\text{post}}, \\beta_{\\text{post}})} = \\frac{\\Gamma(\\alpha_{\\text{post}} + 1)\\Gamma(\\beta_{\\text{post}})}{\\Gamma(\\alpha_{\\text{post}} + \\beta_{\\text{post}} + 1)} \\cdot \\frac{\\Gamma(\\alpha_{\\text{post}} + \\beta_{\\text{post}})}{\\Gamma(\\alpha_{\\text{post}})\\Gamma(\\beta_{\\text{post}})}" />
              <BlockMath math="\\mathbb{E}[\\theta \\mid \\text{Data}] = \\frac{\\alpha_{\\text{post}}\\Gamma(\\alpha_{\\text{post}})\\Gamma(\\beta_{\\text{post}})}{(\\alpha_{\\text{post}} + \\beta_{\\text{post}})\\Gamma(\\alpha_{\\text{post}} + \\beta_{\\text{post}})} \\cdot \\frac{\\Gamma(\\alpha_{\\text{post}} + \\beta_{\\text{post}})}{\\Gamma(\\alpha_{\\text{post}})\\Gamma(\\beta_{\\text{post}})} = \\frac{\\alpha_{\\text{post}}}{\\alpha_{\\text{post}} + \\beta_{\\text{post}}}" />
              <p className="text-xs text-slate-350 font-semibold pt-2">Expanded Workstation Implementation Formula:</p>
              <BlockMath math="P_{\\text{Posterior}} = \\frac{\\alpha_{\\text{prior}} + (P_{\\text{ML}} \\times w)}{\\alpha_{\\text{prior}} + \\beta_{\\text{prior}} + w}" />
              <p className="text-[10px] text-slate-500 font-mono leading-relaxed">
                This formulation ensures that if the prior model is highly accurate (large <InlineMath math="\\alpha_{\\text{prior}}" />), the raw ML signal is smoothed towards historical baseline expectations. If historical errors are high, the prior variance restricts overreaction to noisy signals.
              </p>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
