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

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

export default function TechMathModal({ isOpen, onClose }: TechMathModalProps) {
  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-955/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-teal-400 to-indigo-400 bg-clip-text text-transparent flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-teal-400" /> English Quantitative AI & Tech Hyper-Leverage Handbook
            </h2>
            <p className="text-[10px] text-slate-500 font-mono">Infrastructure Investment & Overcapacity Early Warning System</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">
              <Cpu className="w-4 h-4 text-teal-400" /> Executive Overview
            </h3>
            <p className="text-xs leading-relaxed text-slate-400">
              The AI Special Silo serves as a diagnostic matrix designed to evaluate structural imbalances in the artificial intelligence value chain. By monitoring capital expenditure (CapEx) intensity, tracking buyer-supplier inventories, and examining balance sheet debt dynamics, this quantitative handbook establishes the mathematical formulas used to detect the peak of the CapEx-Overinvestment Cycle in Big Tech before it manifests in broader market volatility.
            </p>
          </div>

          {/* Section 1: Monetization Gap */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Percent className="w-3.5 h-3.5" /> 1. The Monetization Gap & ROI-to-CapEx Ratio
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              When technology companies deploy huge amounts of capital for AI clusters and computing nodes, standard revenue metrics may hide margin pressure. The Monetization Gap and ROI-to-CapEx metrics track this by isolating the growth of targeted cloud/AI segments against the velocity of capital investments:
            </p>
            <div className="bg-slate-955/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">
                  {"Formula for Monetization Gap (\\(G_{\\text{monetization}}\\)):"}
                </p>
                <BlockMath math="G_{\\text{monetization}, i, t} = \\Delta \\text{Rev}_{\\text{segment}, i, t} - \\Delta \\text{CapEx}_{i, t}" />
                <p className="text-xs text-slate-300 my-2 font-semibold">
                  {"Formula for ROI-to-CapEx Ratio (\\(R_{\\text{ROI}}\\)):"}
                </p>
                <BlockMath math="R_{\\text{ROI}, i, t} = \\frac{\\text{Rev}_{\\text{segment}, i, t} - \\text{Rev}_{\\text{segment}, i, t-1}}{\\text{CapEx}_{i, t}} \\times 100" />
                <p className="text-[10px] text-slate-500 mt-3 font-mono leading-relaxed">
                  {"Where:"}
                  <br />
                  {"- "}<InlineMath math="\\Delta \\text{Rev}_{\\text{segment}, i, t}" />{" is the quarter-over-quarter percentage growth rate of isolated Cloud/Segment revenue (e.g., Azure for MSFT, Google Cloud for GOOGL, Data Center for NVDA/AMD, Family of Apps for META)."}
                  <br />
                  {"- "}<InlineMath math="\\Delta \\text{CapEx}_{i, t}" />{" is the quarter-over-quarter percentage growth rate of Capital Expenditures."}
                  <br />
                  {"- "}<InlineMath math="\\text{CapEx}_{i, t}" />{" is the absolute quarterly capital expenditure of the firm in millions."}
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-teal-300">Strategic Rationale:</strong>{" A negative Monetization Gap (\\(G_{\\text{monetization}} < 0\\)) indicates that capital spending is growing faster than segment monetization, suggesting diminishing marginal returns. A collapsing ROI-to-CapEx ratio signals that the capital investment is failing to spark immediate segment growth, leading to eventual asset write-downs."}
              </p>
            </div>
          </div>

          {/* Section 2: Supply-Chain Velocity */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Coins className="w-3.5 h-3.5" /> 2. Nvidia Supply-Chain Velocity Index
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Supply-chain stress is a reliable leading indicator of demand contraction. We monitor the relationship between the key hardware supplier (Nvidia) and the primary cloud buyers (MSFT, GOOGL, META) by comparing buyers' future purchase commitments with the supplier's inventory speeds:
            </p>
            <div className="bg-slate-955/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">Nvidia Inventory Turnover (Annualized):</p>
                <BlockMath math="\\text{Turnover}_{\\text{NVDA}, t} = \\frac{\\text{COGS}_{\\text{NVDA}, t}}{\\text{Inventory}_{\\text{NVDA}, t}} \\times 4" />
                <p className="text-xs text-slate-300 my-2 font-semibold">
                  {"Supply-Chain Velocity Index (\\(V_{\\text{sc}}\\)):"}
                </p>
                <BlockMath math="V_{\\text{sc}, t} = \\frac{\\sum_{j \\in \\text{Buyers}} \\text{Purchase Obligations}_{j, t}}{\\text{Inventory}_{\\text{NVDA}, t}}" />
                <p className="text-[10px] text-slate-555 mt-3 font-mono leading-relaxed">
                  {"Where:"}
                  <br />
                  {"- "}<InlineMath math="\\text{COGS}_{\\text{NVDA}, t}" />{" is Nvidia's quarterly Cost of Goods Sold."}
                  <br />
                  {"- "}<InlineMath math="\\text{Inventory}_{\\text{NVDA}, t}" />{" is Nvidia's total inventory value on its balance sheet."}
                  <br />
                  {"- "}<InlineMath math="\\text{Purchase Obligations}_{j, t}" />{" represents the forward purchase commitments disclosed in the notes of 10-Q filing reports by the buyers (MSFT, GOOGL, META)."}
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-teal-300">Supply-Chain Dynamics:</strong>{" A rising Velocity Index indicates tight capacity, where buyers' future orders are highly backed by cash-like commitments. If buyers start cutting purchase obligations or if NVDA's inventory builds up relative to COGS (declining turnover), the Velocity Index collapses, signaling a sharp correction in hardware demand 3-6 months before it impacts NVDA's reported revenues."}
              </p>
            </div>
          </div>

          {/* Section 3: Tech Infrastructure Leverage */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Activity className="w-3.5 h-3.5" /> 3. Tech Infrastructure Leverage & Cluster Expansion
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Aggressive cluster construction requires significant debt or capital consumption. We measure the balance sheet risk of massive computing nodes using the Debt-to-Equity (D/E) and CapEx-to-Depreciation ratios:
            </p>
            <div className="bg-slate-955/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">Debt-to-Equity Shift Ratio:</p>
                <BlockMath math="\\text{D/E}_{i, t} = \\frac{\\text{Total Debt}_{i, t}}{\\text{Shareholders' Equity}_{i, t}}" />
                <p className="text-xs text-slate-300 my-2 font-semibold">
                  {"CapEx-to-Depreciation Ratio (\\(R_{\\text{capex-dep}}\\)):"}
                </p>
                <BlockMath math="R_{\\text{capex-dep}, i, t} = \\frac{\\text{CapEx}_{i, t}}{\\text{Depreciation}_{i, t}}" />
                <p className="text-[10px] text-slate-555 mt-3 font-mono leading-relaxed">
                  {"Where:"}
                  <br />
                  {"- "}<InlineMath math="\\text{Total Debt}_{i, t}" />{" represents short-term and long-term interest-bearing debt."}
                  <br />
                  {"- "}<InlineMath math="\\text{Depreciation}_{i, t}" />{" represents the quarterly depreciation expense, reflecting the wear-and-tear of existing physical server arrays."}
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-teal-300">Investment Health:</strong>{" A CapEx-to-Depreciation ratio exceeding 3.0x highlights hyper-aggressive server capacity expansion. When this occurs alongside rising Debt-to-Equity ratios, it indicates that the AI cluster construction is being funded by structural leverage, leaving the firm exposed to massive amortization expenses if monetization fails."}
              </p>
            </div>
          </div>

          {/* Section 4: Asymmetric Tech-Beta Expansions */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <ShieldAlert className="w-3.5 h-3.5" /> 4. Asymmetric Tech-Beta Expansion Equation
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              Investment hyper-leverage creates systematic feedback loops in equity markets. We model the amplification of tech sector risk (asymmetric beta expansion) using a non-linear scaling model:
            </p>
            <div className="bg-slate-955/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">Systemic Tech Beta Model:</p>
                <BlockMath math="\\beta_{\\text{tech}, t} = \\beta_{0} \\times \\left(1 + \\gamma \\times \\frac{\\sum_{i} \\text{CapEx}_{i, t}}{\\sum_{i} \\text{Depreciation}_{i, t}}\\right) \\times e^{\\lambda \\times (1 - V_{\\text{sc}, t})}" />
                <p className="text-[10px] text-slate-555 mt-3 font-mono leading-relaxed">
                  {"Where:"}
                  <br />
                  {"- "}<InlineMath math="\\beta_{0}" />{" is the baseline systematic tech beta (historically ~1.10)."}
                  <br />
                  {"- "}<InlineMath math="\\gamma" />{" represents the investment intensity multiplier (e.g. 0.05)."}
                  <br />
                  {"- "}<InlineMath math="\\lambda" />{" represents the supply-chain velocity damping constant (e.g. 0.12)."}
                  <br />
                  {"- "}<InlineMath math="V_{\\text{sc}, t}" />{" is the Supply-Chain Velocity Index calculated in Section 2."}
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-teal-300">Economic Rationale:</strong>{" This equation demonstrates that tech equity risk is not static. As CapEx outstrips depreciation (building massive infrastructure) and the Supply-Chain Velocity Index collapses (build-up of unsellable inventory), the systemic beta "}<InlineMath math="\\beta_{\\text{tech}, t}" />{" expands exponentially. Under these parameters, any minor disappointment in earnings results in an asymmetric downward repricing."}
              </p>
            </div>
          </div>

          {/* Section 5: Sloan Accrual Radar */}
          <div className="space-y-3">
            <h4 className="text-xs font-bold text-teal-400 uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Percent className="w-3.5 h-3.5" /> 5. Sloan Earnings Quality Accrual Radar
            </h4>
            <p className="text-xs leading-relaxed text-slate-400">
              The Sloan Ratio identifies discrepancies between reported net income and actual cash flows. A high proportion of non-cash accruals signals low earnings quality and is a historically proven accounting anomaly predictor:
            </p>
            <div className="bg-slate-955/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">
                  {"Formula for Accruals (\\(\\text{Accruals}\\)):"}
                </p>
                <BlockMath math="\\text{Accruals}_{t} = \\text{Net Income}_{t} - (\\text{CFO}_{t} + \\text{CFI}_{t})" />
                <p className="text-xs text-slate-300 my-2 font-semibold">
                  {"Formula for Sloan Ratio (\\(\\text{Sloan Ratio}\\)):"}
                </p>
                <BlockMath math="\\text{Sloan Ratio}_{t} = \\frac{\\text{Accruals}_{t}}{\\text{Total Assets}_{t}} \\times 100" />
                <p className="text-[10px] text-slate-555 mt-3 font-mono leading-relaxed">
                  {"Where:"}
                  <br />
                  {"- "}<InlineMath math="\\text{Net Income}_{t}" />{" is the company's net income for the fiscal period."}
                  <br />
                  {"- "}<InlineMath math="\\text{CFO}_{t}" />{" is Cash Flow from Operations (operating cash flow)."}
                  <br />
                  {"- "}<InlineMath math="\\text{CFI}_{t}" />{" is Cash Flow from Investing activities."}
                  <br />
                  {"- "}<InlineMath math="\\text{Total Assets}_{t}" />{" is the total assets reported on the balance sheet at the end of the period."}
                </p>
              </div>
              <p className="text-xs leading-relaxed text-slate-400">
                <strong className="text-teal-300">Regime Classifications:</strong>
                <br />
                {"- "}<strong className="text-emerald-400">Safe Regime (-10% to +10%):</strong>{" High earnings quality, where profits are strongly supported by actual cash flows."}
                <br />
                {"- "}<strong className="text-rose-400 font-bold">Anomaly Regime (&gt; +10% or &lt; -10%):</strong>{" Aggressive accounting or accrual expansion, indicating high earnings manipulation risk."}
              </p>
            </div>
          </div>

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