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

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

export default function PortfolioMathModal({ isOpen, onClose }: PortfolioMathModalProps) {
  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">
      <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/40 border-b border-slate-800/60">
          <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 & 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 px-3 py-1.5 rounded-lg text-xs font-semibold font-mono transition-all cursor-pointer"
          >
            Schließen (ESC)
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-6 sm:p-8 space-y-6 text-slate-300 scrollbar-thin">
          <div className="space-y-6">
            <div className="border-b border-slate-800/80 pb-3">
              <h3 className="text-base font-bold text-slate-200">5. Portfolio Sandbox & Rebalancing Engine</h3>
              <p className="text-xs text-slate-400 mt-1">Estimates aggregate portfolio drawdowns and controls covariance drift boundaries.</p>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono">A. Synthetic Portfolio Model & Asset Weightings</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                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>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono">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 space-y-4">
                <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 className="border-t border-slate-850 pt-3">
                  <p className="text-xs text-slate-400 mb-1">Optimal Kelly Criterion Position Sizing:</p>
                  <BlockMath math="f^* = \\frac{p \\times b - (1 - p)}{b}" />
                </div>
              </div>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono">C. Reinvestment & Optimization Generation</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                Integrates signals across three engines: Scanner (underpriced value), Econometrics (macro event post-event betas), and Insiders (corporate buying).
                Ranks candidates and suggests target reallocations.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
