import React from 'react';
import { BookOpen, X, Landmark, Percent, Activity, Coins, Home, ShieldAlert } from 'lucide-react';
import 'katex/dist/katex.min.css';
import { BlockMath, InlineMath } from 'react-katex';

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

export default function MacroMathModal({ isOpen, onClose }: MacroMathModalProps) {
  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-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-indigo-400 to-purple-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-indigo-400" /> English Quantitative Macroeconomic & Credit Handbook
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">Institutional Strategy & Asset Allocation 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 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 Summary */}
          <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">
              <Landmark className="w-4 h-4 text-indigo-400" /> Executive Overview
            </h3>
            <p className="text-xs leading-relaxed text-slate-400">
              This handbook serves as the mathematical and logical blueprint for the Macroeconomic & Credit Data Silo. It provides quantitative definitions and asset allocation rationale for the 21 indicators compiled in our hybrid engine. By tracking central bank balance sheets, sovereign yields, corporate credit spreads, consumer delinquency vectors, and housing credit velocity, the system constructs a multi-layered diagnostic scanner to forecast macroeconomic regime transitions and evaluate systemic market risk.
            </p>
          </div>

          {/* Section 1: The Buffett Indicator */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-indigo-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Percent className="w-3.5 h-3.5" /> 1. Equity Valuation & Macro Capacity (The Buffett Indicator)
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The Buffett Indicator measures the aggregate valuation of the corporate sector relative to the total economic output of the nation. It represents a top-down capacity gauge, evaluating whether financial markets have expanded beyond their structural macroeconomic foundation:
            </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">Buffett Ratio Equation:</p>
                <BlockMath math="\text{Buffett Ratio} = \frac{\text{Wilshire 5000 Total Market Index}}{\text{Gross Domestic Product}} \approx \frac{\text{S\&P 500} \times 1000}{\text{Gross Domestic Product}}" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  Where:
                  <br />
                  - <InlineMath math="\text{Wilshire 5000 Total Market Index}" /> (originally FRED Series ID: 'WILL5000PR') represents the price performance of all active US equities. Due to the discontinuation of Wilshire series on FRED in June 2024, the S&P 500 index ('SP500') scaled by 1000 serves as the active proxy.
                  <br />
                  - <InlineMath math="\text{Gross Domestic Product}" /> is nominal US GDP (FRED Series ID: 'GDPA').
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-indigo-300">Strategic Rationale:</strong> A Buffett Ratio exceeding <span className="text-rose-400 font-semibold font-mono">150%</span> indicates extreme historical overvaluation, signaling that corporate equity valuations are unsustainable compared to the real economic cash flows generated by the underlying economy. Under such conditions, long-term expected equity returns tend to compress towards zero or negative territory, prompting the system to lower equity beta weightings.
              </p>
            </div>
          </div>

          {/* Section 2: Federal Reserve Net Liquidity Proxy */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-indigo-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Coins className="w-3.5 h-3.5" /> 2. Monetary Liquidity & Central Bank Reserves
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              While the headline balance sheet represents raw central bank asset size, financial markets react Endogenously to the net volume of reserves circulating within the commercial banking system. We model this using the Net Fed Liquidity Proxy:
            </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">Net Liquidity Equation:</p>
                <BlockMath math="\text{Net Fed Liquidity}_t = A_{\text{Fed}, t} - \text{TGA}_t - \text{RRP}_t" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  Where:
                  <br />
                  - <InlineMath math="A_{\text{Fed}, t}" /> represents Total Federal Reserve Assets (the asset side of the Fed Balance Sheet).
                  <br />
                  - <InlineMath math="\text{TGA}_t" /> represents the Treasury General Account balance (the US Government's cash account held at the Federal Reserve).
                  <br />
                  - <InlineMath math="\text{RRP}_t" /> represents the Reverse Repurchase Agreement facility usage volume (liquidity parked overnight by money market funds at the Fed).
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-indigo-300">Liquidity Dynamics:</strong> 
                An increase in <InlineMath math="A_{\text{Fed}, t}" /> (Quantitative Easing) injects reserves into the banking system. Conversely, when the Treasury increases the <InlineMath math="\text{TGA}" /> balance or when money market funds park cash in the <InlineMath math="\text{RRP}" />, liquidity is drained from active circulation. A shrinking Net Fed Liquidity Proxy acts as a powerful brake on risk assets (Equities & Cryptocurrencies), whereas expanding liquidity acts as a tailwind.
              </p>
            </div>
          </div>

          {/* Section 3: Sovereign Yield Spreads */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-indigo-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Activity className="w-3.5 h-3.5" /> 3. Sovereign Yield Curves & Term Structures
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The sovereign yield curve reflects market expectations of economic growth, monetary policy, and risk premiums. The primary spread used to measure structural inversion is the 2S10S spread:
            </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">2S10S Spread Equation:</p>
                <BlockMath math="\text{Spread}_{2S10S} = Y_{10Y} - Y_{2Y}" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  Where:
                  <br />
                  - <InlineMath math="Y_{10Y}" /> is the nominal yield of the 10-Year United States Treasury Bond.
                  <br />
                  - <InlineMath math="Y_{2Y}" /> is the nominal yield of the 2-Year United States Treasury Note.
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-indigo-300">Inversion & Un-Inversion:</strong> A negative spread (<InlineMath math="\text{Spread}_{2S10S} < 0" />) represents an inverted yield curve, which has historically preceded US economic recessions. The "un-inversion" process, where the spread returns to positive territory, typically occurs during late-cycle phases or central bank pivot periods, signaling imminent macroeconomic contraction as short-term yields fall rapidly in anticipation of rate cuts.
              </p>
            </div>
          </div>

          {/* Section 4: Burry's Consumer Distress Mechanics */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-indigo-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <ShieldAlert className="w-3.5 h-3.5" /> 4. Consumer Credit Distress (Burry's Distress Mechanics)
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Popularized by macroeconomic analysts such as Michael Burry, the retail consumer distress engine evaluates the health of consumer balance sheets by measuring the rate of credit defaults relative to the liquid cushion of household savings:
            </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">Consumer Credit Distress Index (CDI):</p>
                <BlockMath math="\text{CDI}_t = \frac{\text{Credit Card Delinquency Rate}_t}{\text{Personal Savings Rate}_t}" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  Where:
                  <br />
                  - <InlineMath math="\text{Credit Card Delinquency Rate}_t" /> measures the delinquency rate on credit card loans at top 100 commercial banks (FRED Series ID: 'DRCCLACBS').
                  <br />
                  - <InlineMath math="\text{Personal Savings Rate}_t" /> represents personal savings as a percentage of disposable personal income (FRED Series ID: 'PSAVERT').
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-indigo-300">Macroeconomic Implications:</strong> 
                Personal savings act as the primary shock absorber for the consumer. When the Savings Rate collapses (depleting liquid assets) while Credit Card Delinquencies simultaneously spike, it indicates that households are using high-interest credit card debt to sustain normal consumption. This divergence leads to structural consumer exhaustion and credit defaults, forming a leading indicator of an economic downturn.
              </p>
            </div>
          </div>

          {/* Section 5: Real Estate & Housing Credit Layer */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-indigo-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Home className="w-3.5 h-3.5" /> 5. Real Estate & Housing Credit Velocity
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The real estate sector represents the most interest-rate-sensitive component of the economy. Credit cycles within this layer are monitored via three interconnected indicators:
            </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-indigo-300 block mb-1">I. Housing Starts (Baubeginne) [FRED: HOUST]:</strong>
                Measures the annualized number of new residential construction projects. Because home building requires significant upfront debt capital and permits, a decline in Housing Starts serves as a leading indicator of tightening bank credit and weakening capital investment.
              </div>
              <div>
                <strong className="text-indigo-300 block mb-1">II. Mortgage Applications Index Proxy [FRED: MORTGAGE30US]:</strong>
                Tracks the weekly demand for residential purchase mortgages. Because direct MBA applications index data is proprietary, the system computes a mortgage application index proxy derived from the 30-Year Fixed Rate Mortgage Average: <InlineMath math="\text{Mortgage Index Proxy} = \frac{1000}{\text{30-Year Mortgage Rate}}" />.
              </div>
              <div>
                <strong className="text-indigo-300 block mb-1">III. Case-Shiller Home Price Index [FRED: CSUSHPISA]:</strong>
                Measures US residential asset price appreciation. Housing represents the largest asset class on household balance sheets. A decline in the Case-Shiller index causes a negative wealth effect, lowering consumer confidence and eroding mortgage collateral backing bank assets.
              </div>
            </div>
          </div>

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