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

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

export default function SandboxMathModal({ isOpen, onClose }: SandboxMathModalProps) {
  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/90 backdrop-blur-md p-4 sm:p-6 md:p-8">
      <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-350">
        
        {/* Modal Header */}
        <div className="flex justify-between items-center px-6 py-4 bg-slate-950/50 border-b border-slate-800/80">
          <div>
            <h2 className="text-base font-bold bg-gradient-to-r from-teal-400 to-emerald-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-teal-400" /> Portfolio Sandbox - Math & Sizing Handbook
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">Institutional Portfolio Construction & Allocation Spec</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">
          
          {/* Section A: Synthetic Portfolio Model & Asset Weightings */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <TrendingUp className="w-3.5 h-3.5" /> A. Synthetic Portfolio Model & Asset Weightings
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The sandbox constructs a continuous synthetic asset representing your active weight allocations and its daily return track:
            </p>
            <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2 space-y-4">
              <div>
                <p className="text-xs text-slate-400 mb-1">Active Percentage Weighting (<InlineMath math="w_i" />) Calculation:</p>
                <BlockMath math="w_i = \frac{\text{Shares}_i \times P_{\text{current}, i}}{\sum_{j} \text{Shares}_j \times P_{\text{current}, j}}" />
              </div>
              <div className="border-t border-slate-850 pt-3">
                <p className="text-xs text-slate-400 mb-1">Synthetic Portfolio Log Return (<InlineMath math="R_{pt}" />):</p>
                <BlockMath math="R_{pt} = \sum_{i} w_i \times \ln\left(\frac{P_{t, i}}{P_{t-1, i}}\right)" />
              </div>
            </div>
          </div>

          {/* Section B: Linear Mixed Effects Panel Regression (LMM) */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <BarChart2 className="w-3.5 h-3.5" /> B. Linear Mixed Effects Panel Regression (LMM)
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Solves the system-wide macro response model across all historical event instances <InlineMath math="j" /> using a Swamy-Arora GLS estimator:
            </p>
            <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
              <div>
                <p className="text-xs text-slate-400 mb-1">Panel Model Specification with VIX Controls:</p>
                <BlockMath math="R_{ptj} = \beta_0 + \beta_{\text{drift}} \text{Pre}_t + \beta_{\text{impact}} \text{Post}_t + \beta_{\text{VIX}} VIX_{tj} + u_j + e_{ptj}" />
                <p className="text-[10px] text-slate-500 mt-2 font-mono leading-relaxed">
                  where:
                  <br />
                  - <InlineMath math="t \in [-30, +30]" /> is the relative day offset from event date <InlineMath math="T_j" />.
                  <br />
                  - <InlineMath math="\text{Pre}_t = \mathbb{I}(t < 0)" /> and <InlineMath math="\text{Post}_t = \mathbb{I}(t > 0)" /> are relative phase indicators.
                  <br />
                  - <InlineMath math="VIX_{tj}" /> is the background market-wide volatility covariate.
                  <br />
                  - <InlineMath math="u_j \sim N(0, \sigma_u^2)" /> is the random group intercept (event instance shock).
                  <br />
                  - <InlineMath math="e_{ptj} \sim N(0, \sigma_e^2)" /> is the residual error.
                </p>
              </div>
            </div>
          </div>

          {/* Section C: Kelly Criterion & Fractional Betting Sizing */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <ShieldAlert className="w-3.5 h-3.5" /> C. Kelly Criterion & Fractional Betting Sizing
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The Kelly Criterion optimizes allocation sizing to maximize the expected value of the logarithm of wealth, balancing capital preservation with growth:
            </p>
            <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2 space-y-4">
              <div>
                <p className="text-xs text-slate-400 mb-1">Theoretical Kelly Fraction (<InlineMath math="f^*" />) Equation:</p>
                <BlockMath math="f^* = \frac{p \cdot b - (1 - p)}{b}" />
                <p className="text-[10px] text-slate-500 mt-2 font-mono leading-relaxed">
                  where:
                  <br />
                  - <InlineMath math="p" /> is the probability of a positive outcome (rebound or trade success).
                  <br />
                  - <InlineMath math="b" /> is the payout odds ratio (average win size divided by average loss size).
                </p>
              </div>
              <div className="border-t border-slate-850 pt-3">
                <p className="text-xs text-slate-400 mb-1">Fractional Kelly (Half-Kelly) Safety Buffer:</p>
                <BlockMath math="f_{\text{applied}} = \max\left(0, 0.5 \times f^*\right)" />
                <p className="text-xs text-slate-400 leading-relaxed mt-2">
                  To mitigate estimation variance and protect against catastrophic drawdown due to model error or fat-tailed market returns, the cockpit clips the suggested sizing to a **Half-Kelly** multiplier (<InlineMath math="0.5" />).
                </p>
              </div>
            </div>
          </div>

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