import React from 'react';
import { Settings, X } from 'lucide-react';

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

export default function CryptoBlueprintModal({ isOpen, onClose }: CryptoBlueprintModalProps) {
  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-900/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-350">
        
        {/* 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">
              <Settings className="w-5 h-5 text-cyan-400" /> Crypto Bayes Module - Operational Blueprint
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">System User Manual &amp; Interface Mechanics</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-350 scrollbar-thin">
          
          <div className="border-b border-slate-800/80 pb-3">
            <h3 className="text-base font-bold text-slate-200">System Inputs &amp; Signals</h3>
            <p className="text-xs text-slate-400 mt-1">Operational breakdown of key indicators used by the multi-model pipeline.</p>
          </div>

          {/* Core Indicators */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="p-4 rounded-xl border border-slate-800/60 bg-slate-950/40 space-y-2">
              <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">1. Funding Rates (Leverage Skew)</h4>
              <p className="text-xs text-slate-400 leading-relaxed">
                Reflects periodic payments exchanged between long and short traders. Extremely positive funding rates signal retail over-leverage and high risk of long liquidation squeezes (bearish indicators). Negative rates signal retail panic and potential short squeezes (bullish indicators).
              </p>
            </div>
            
            <div className="p-4 rounded-xl border border-slate-800/60 bg-slate-950/40 space-y-2">
              <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">2. Open Interest Change (Capital Velocity)</h4>
              <p className="text-xs text-slate-400 leading-relaxed">
                Measures the net speed at which new contracts are being opened or closed. A sharp increase in Open Interest accompanied by price moves confirms a strong momentum transition, indicating institutional volume entry.
              </p>
            </div>

            <div className="p-4 rounded-xl border border-slate-800/60 bg-slate-950/40 space-y-2">
              <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">3. Retail Skew (Contrarian Filter)</h4>
              <p className="text-xs text-slate-400 leading-relaxed">
                Calculates the proportion of long contracts held by retail accounts. The system operates under a contrarian framework: when retail long positioning is at extreme bullishness (e.g. Retail Skew &gt; 1.50), the system dampens bullish forecast probabilities.
              </p>
            </div>

            <div className="p-4 rounded-xl border border-slate-800/60 bg-slate-950/40 space-y-2">
              <h4 className="text-xs font-bold text-cyan-400 uppercase tracking-wider font-mono">4. Whale Inflows (Accumulation Vectors)</h4>
              <p className="text-xs text-slate-400 leading-relaxed">
                Tracks large volume transactions moving from spot exchanges to private cold storage. Accumulation inflows decrease available supply on exchanges, establishing a spot-supply mismatch that supports upward spot pricing pressure.
              </p>
            </div>
          </div>

          {/* Interface Legend */}
          <div className="space-y-3">
            <h3 className="text-sm font-bold text-slate-200 border-b border-slate-800 pb-2">Interface Layout &amp; Metrics Legend</h3>
            <div className="bg-slate-950/40 p-5 rounded-2xl border border-slate-800/60 space-y-4 text-xs">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <strong className="text-slate-200 block mb-1">Expected Value (E: %)</strong>
                  <p className="text-slate-400 leading-relaxed">
                    Calculated as the Posterior Expected Value E = alpha / (alpha + beta) based on successes (alpha) and failures (beta). A value of e.g. **E: 85.5%** suggests that the estimator-horizon combination is highly calibrated.
                  </p>
                </div>
                <div>
                  <strong className="text-slate-200 block mb-1">Raw Trackers ("62/14")</strong>
                  <p className="text-slate-400 leading-relaxed">
                    Represents the absolute counts of success and failure outcomes: **62** successfully resolved direction predictions (alpha) and **14** false alarms or incorrect directional forecasts (beta).
                  </p>
                </div>
                <div>
                  <strong className="text-slate-200 block mb-1">Horizon Forecasts</strong>
                  <p className="text-slate-400 leading-relaxed">
                    Displays direction (▲ UP / ▼ DOWN) and probability forecast for BTC, ETH, or SOL at horizons T+1 (24h), T+5 (5d), and T+10 (10d).
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Operational Dynamics */}
          <div className="space-y-3">
            <h3 className="text-sm font-bold text-slate-200 border-b border-slate-800 pb-2">Simulator &amp; Ingestion Loops</h3>
            <div className="text-xs text-slate-400 space-y-3 leading-relaxed">
              <p>
                <strong className="text-cyan-400">Posterior Calibration Simulator:</strong> Clicking **"+1 Success (All)"** or **"+1 False Alarm (All)"** simulates model feedback loops. It increments the success or failure count across all 15 independent trackers, storing updated states immediately in `localStorage` to evaluate how expected accuracies drift when models perform well or poorly.
              </p>
              <p>
                <strong className="text-cyan-400">Background Evaluation Loop:</strong> When a user logs a manual forecast, the app registers predictions for all 15 trackers. In dev mode, the targets resolve quickly: T+1 in 60 seconds, T+5 in 5 minutes, and T+10 in 10 minutes. A background worker queries `/api/finance?region=crypto` to resolve the actual price change, updates the trackers in `localStorage`, and displays the success rates.
              </p>
            </div>
          </div>

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