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

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

export default function InsiderMathModal({ isOpen, onClose }: InsiderMathModalProps) {
  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-purple-400 to-indigo-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-purple-400" /> Insider Activity - 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">3. Insider Activity Cluster Engine</h3>
              <p className="text-xs text-slate-400 mt-1">Identifies corporate alignment patterns by tracking Form 4 open market purchases.</p>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-purple-400 uppercase tracking-wider font-mono">A. Filings Parser Pipeline</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                Analyzes SEC Form 4 filings XML streams to detect corporate insider purchases:
              </p>
              <ul className="list-disc pl-5 text-xs text-slate-400 space-y-1 font-mono">
                <li><strong>Transaction Code filter</strong>: isolates code <code className="text-purple-400">P</code> (Open Market Purchase) and discards codes like <code className="text-slate-500">M</code> (option exercises).</li>
                <li><strong>Rule 10b5-1 filter</strong>: purges automatic pre-planned sales or purchases to identify purely discretionary trades.</li>
              </ul>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-purple-400 uppercase tracking-wider font-mono">B. Clustering Algorithm</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                Insiders have unique company information, but clusters yield highest significance. A cluster is registered if:
              </p>
              <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
                <BlockMath math="\text{Count}_{\text{insiders}} \ge 3 \quad \text{within a rolling 14-day window}" />
                <p className="text-[11px] text-slate-400 font-mono mt-2 text-center">
                  Insiders must represent distinct entities (e.g. CEO, CFO, and Directors trading concurrently).
                </p>
              </div>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-purple-400 uppercase tracking-wider font-mono">C. Insider Intensity Weighting</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                The Insider Intensity Score scales signals based on size, conviction value, and count of participants:
              </p>
              <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
                <BlockMath math="I_{score} = \ln\left(\sum_{k=1}^N \text{Volume}_{shares, k}\right) \times \left(\frac{\sum_{k=1}^N \text{Value}_{USD, k}}{\text{Market Cap}}\right) \times \text{Count}_{\text{insiders}}" />
              </div>
            </div>

            <div className="space-y-3">
              <h4 className="text-xs font-bold text-purple-400 uppercase tracking-wider font-mono">D. Overreaction Coupling</h4>
              <p className="text-xs leading-relaxed text-slate-400">
                The engine cross-references corporate clusters with the Overreaction Scanner, isolating stocks with the highest rebound probabilities:
              </p>
              <div className="bg-slate-950/40 p-4 rounded-xl border border-slate-800/60 my-2">
                <p className="text-xs leading-relaxed font-mono">
                  If <InlineMath math="\text{Alert} \in \text{Scanner}_{\text{Oversold}}" /> and <InlineMath math="\text{Cluster} \in \text{Insider}_{\text{Active}}" />:
                  <br/>
                  Prioritize tickers showing asymmetric insider buying during panic drops, suggesting fundamental divergence from market sentiment.
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
