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

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

export default function WhaleMathModal({ isOpen, onClose }: WhaleMathModalProps) {
  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-5xl h-[85vh] flex flex-col overflow-hidden shadow-2xl relative text-slate-355">
        
        {/* 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-blue-400 to-teal-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-blue-400" /> English Quantitative Whale Screener & Conviction Handbook
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">13F Institutional Filing Tracking & Velocity of Conviction Matrix</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">
          
          {/* Executive Overview */}
          <div className="bg-slate-950/30 rounded-2xl p-5 border border-slate-850 space-y-2">
            <h3 className="text-sm font-bold text-slate-100 flex items-center gap-2">
              <ShieldAlert className="w-4 h-4 text-blue-400" /> Executive Overview
            </h3>
            <p className="text-xs leading-relaxed text-slate-400">
              The Whale Satellite Screener isolates high-conviction adjustments in portfolios managed by elite long-term value and small-cap investment firms (such as Michael Burry's Scion Asset Management and Chuck Akre's Akre Capital). By calculating the quarter-over-quarter relative portfolio weight adjustments, the system tracks the directional commitment ("Velocity of Conviction") of smart capital while adjusting for reporting lags and sector clustering.
            </p>
          </div>

          {/* Section 1: The 45-Day 13F Reporting Lag */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-blue-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <BarChart2 className="w-3.5 h-3.5" /> 1. The 13F Reporting Lag Constraint
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Institutional investment managers with over $100 million in Assets Under Management (AUM) are legally mandated by the SEC to submit Form 13F within 45 days after the end of each calendar quarter. This lag presents a structural challenge for quantitative models, as holdings data represents historical positions:
            </p>
            <div className="bg-slate-950/40 p-5 rounded-2xl border border-slate-850 my-2 text-xs space-y-3 text-slate-400 leading-relaxed">
              <div>
                <strong className="text-blue-300 block mb-1">I. Retrospective Analysis:</strong>
                Positions disclosed on day <InlineMath math="T + 45" /> reflect the portfolio state at day <InlineMath math="T" />. As a result, short-term momentum models cannot directly trade 13F filings.
              </div>
              <div>
                <strong className="text-blue-300 block mb-1">II. Informational Asymmetry:</strong>
                Because holdings are backward-looking, the screener is optimized for long-term fundamental tracking (holding periods exceeding 12 months) where the 45-day lag does not dilute the underlying investment thesis.
              </div>
            </div>
          </div>

          {/* Section 2: Velocity of Conviction Formula */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-blue-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <TrendingUp className="w-3.5 h-3.5" /> 2. Velocity of Conviction (VoC) Weighting
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Rather than tracking the absolute number of shares bought or sold, the screener measures changes in the relative portfolio weight of each asset. This normalizes for AUM changes caused by overall market movements:
            </p>
            <div className="bg-slate-950/40 p-5 rounded-2xl border border-slate-850 my-2 space-y-4">
              <div>
                <p className="text-xs text-slate-300 mb-2 font-semibold">Velocity of Conviction (VoC) Delta:</p>
                <BlockMath math="\text{VoC}_{i} = w_{i, t} - w_{i, t-1}" />
                <p className="text-xs text-slate-300 my-2 font-semibold">Asset Portfolio Weight Calculation:</p>
                <BlockMath math="w_{i, t} = \frac{V_{i, t}}{\sum_{j} V_{j, t}} \times 100" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  Where:
                  <br />
                  - <InlineMath math="w_{i, t}" /> is the portfolio weight of asset <InlineMath math="i" /> at the end of the current quarter <InlineMath math="t" /> (expressed as a percentage).
                  <br />
                  - <InlineMath math="w_{i, t-1}" /> is the portfolio weight of asset <InlineMath math="i" /> at the end of the previous quarter <InlineMath math="t-1" />.
                  <br />
                  - <InlineMath math="V_{i, t}" /> is the market value of the position in asset <InlineMath math="i" /> as reported in the 13F filing for quarter <InlineMath math="t" />.
                  <br />
                  - <InlineMath math="\sum_{j} V_{j, t}" /> represents the total market value of all reported equity holdings in the filing for quarter <InlineMath math="t" /> (AUM proxy).
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-blue-300">Strategic Rationale:</strong> A positive VoC delta <InlineMath math="\text{VoC}_i > 0" /> indicates that the manager has actively allocated capital to the asset relative to other holdings, suggesting high-conviction buying. Conversely, a negative delta <InlineMath math="\text{VoC}_i < 0" /> indicates relative allocation decreases, showing active selling or profit-taking.
              </p>
            </div>
          </div>

          {/* Section 3: Institutional Clustering */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-blue-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <DollarSign className="w-3.5 h-3.5" /> 3. Institutional Clustering
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Institutional clustering occurs when multiple high-conviction managers establish positions in the same security during the same period. The screener tracks cross-ownership patterns to detect when elite managers converge on specific investment clusters, which historically serves as a strong signal of structural undervaluation.
            </p>
          </div>

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