FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
v3.3.0 update
tilakpatel22c8394aa40998
diff --git a/fincept-terminal-desktop/src-tauri/installer-hooks.nsh b/fincept-terminal-desktop/src-tauri/installer-hooks.nshnew file mode 100644index 000000000..936e123f8--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/installer-hooks.nsh@@ -0,0 +1,18 @@+; Custom NSIS installer hooks for Fincept Terminal+; See: https://v2.tauri.app/distribute/windows-installer/++!macro NSIS_HOOK_PREINSTALL+ ; Runs before copying files, setting registry keys, and creating shortcuts+!macroend++!macro NSIS_HOOK_POSTINSTALL+ ; Runs after all files are copied, registry keys set, and shortcuts created+!macroend++!macro NSIS_HOOK_PREUNINSTALL+ ; Runs before removing files, registry keys, and shortcuts+!macroend++!macro NSIS_HOOK_POSTUNINSTALL+ ; Runs after files, registry keys, and shortcuts have been removed+!macroenddiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.pyindex 42533cbaa..7339fd89e 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py@@ -93,7 +93,7 @@ class CoreAgent:self._current_config = config# Build run kwargs- run_kwargs = {"message": query} # Agno uses 'message' not 'input'+ run_kwargs = {"input": query} # Agno uses 'input' parameterif session_id:run_kwargs["session_id"] = session_iddiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.pyindex 933be9abc..5ff1d41df 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py@@ -14,10 +14,19 @@ class DatabaseManager:def __init__(self, db_path: Optional[str] = None):"""Initialize database manager"""if db_path is None:- # Use temp directory to avoid Tauri file watcher triggering rebuilds- import tempfile- temp_dir = tempfile.gettempdir()- db_dir = os.path.join(temp_dir, 'fincept_alpha_arena')+ # Use FINCEPT_DATA_DIR env var if set by Rust, otherwise use platform-specific app data+ data_dir = os.environ.get("FINCEPT_DATA_DIR")+ if data_dir:+ db_dir = os.path.join(data_dir, 'alpha_arena')+ else:+ # Fallback to platform-specific user data directory+ if os.name == "nt": # Windows+ base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~/AppData/Local"))+ elif hasattr(os, 'uname') and os.uname().sysname == "Darwin": # macOS+ base = os.path.expanduser("~/Library/Application Support")+ else: # Linux+ base = os.path.expanduser("~/.local/share")+ db_dir = os.path.join(base, 'fincept-dev', 'alpha_arena')os.makedirs(db_dir, exist_ok=True)db_path = os.path.join(db_dir, 'agno_trading.db')print(f"[DatabaseManager] Using database at: {db_path}", file=sys.stderr)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.pyindex e31bc3372..069d094fa 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py@@ -172,17 +172,34 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:'error': 'Insufficient data',}- # Check if any consecutive pair shows a crossing within the window+ # For indicator-vs-indicator, get N target values to compare bar-by-barmet = False- for i in range(len(values) - 1):- if operator == 'crossed_above_within':- if values[i] <= target_current and values[i + 1] > target_current:- met = True- break- else:- if values[i] >= target_current and values[i + 1] < target_current:- met = True- break+ if compare_mode == 'indicator':+ compare_indicator = condition.get('compareIndicator', '')+ compare_params_dict = condition.get('compareParams', {})+ compare_field_name = condition.get('compareField', 'value')+ target_values_list = get_last_n_values(compare_indicator, df, compare_params_dict, compare_field_name, n=n)+ if len(target_values_list) >= len(values):+ for i in range(len(values) - 1):+ if operator == 'crossed_above_within':+ if values[i] <= target_values_list[i] and values[i + 1] > target_values_list[i + 1]:+ met = True+ break+ else:+ if values[i] >= target_values_list[i] and values[i + 1] < target_values_list[i + 1]:+ met = True+ break+ else:+ # Compare against fixed numeric target+ for i in range(len(values) - 1):+ if operator == 'crossed_above_within':+ if values[i] <= target_current and values[i + 1] > target_current:+ met = True+ break+ else:+ if values[i] >= target_current and values[i + 1] < target_current:+ met = True+ breakreturn {'met': met,diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsxindex 62e2d1cec..71979a194 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionBuilder.tsx@@ -1,12 +1,13 @@-import React from 'react';-import { Plus } from 'lucide-react';+import React, { useState } from 'react';+import { Plus, ChevronDown, ChevronRight } from 'lucide-react';import type { ConditionItem } from '../types';+import { getIndicatorDef } from '../constants/indicators';import ConditionRow from './ConditionRow';const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', GRAY: '#787878', DARK_BG: '#000000',PANEL_BG: '#0F0F0F', HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A',- HOVER: '#1F1F1F', CYAN: '#00E5FF', BLUE: '#0088FF',+ HOVER: '#1F1F1F', CYAN: '#00E5FF', BLUE: '#0088FF', MUTED: '#4A4A4A',};interface ConditionBuilderProps {@@ -25,6 +26,27 @@ const DEFAULT_CONDITION: ConditionItem = {value: 30,};+// Quick-add condition templates for the dropdown+interface QuickCondition {+ label: string;+ condition: ConditionItem;+}++const QUICK_CONDITIONS: QuickCondition[] = [+ { label: 'RSI < 30 (Oversold)', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 } },+ { label: 'RSI > 70 (Overbought)', condition: { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '>', value: 70 } },+ { label: 'MACD Histogram > 0', condition: { indicator: 'MACD', params: { fast: 12, slow: 26, signal: 9 }, field: 'histogram', operator: '>', value: 0 } },+ { label: 'Close > EMA(20)', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: '>', value: 0, compareMode: 'indicator', compareIndicator: 'EMA', compareParams: { period: 20 }, compareField: 'value' } },+ { label: 'Close X↑ SMA(200)', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'SMA', compareParams: { period: 200 }, compareField: 'value' } },+ { label: 'Supertrend Bullish', condition: { indicator: 'SUPERTREND', params: { period: 10, multiplier: 3 }, field: 'direction', operator: '==', value: 1 } },+ { label: 'Bollinger %B < 0 (Oversold)', condition: { indicator: 'BOLLINGER', params: { period: 20, std_dev: 2 }, field: 'pct_b', operator: '<', value: 0 } },+ { label: 'ADX > 25 (Strong Trend)', condition: { indicator: 'ADX', params: { period: 14 }, field: 'value', operator: '>', value: 25 } },+ { label: 'MFI > 80 (OB)', condition: { indicator: 'MFI', params: { period: 14 }, field: 'value', operator: '>', value: 80 } },+ { label: 'Stoch RSI K X↑ D', condition: { indicator: 'STOCH_RSI', params: { period: 14, smooth1: 3, smooth2: 3 }, field: 'k', operator: 'crosses_above', value: 0, compareMode: 'indicator', compareIndicator: 'STOCH_RSI', compareParams: { period: 14, smooth1: 3, smooth2: 3 }, compareField: 'd' } },+ { label: 'Price Rising 3 Bars', condition: { indicator: 'CLOSE', params: {}, field: 'value', operator: 'rising', value: 0, lookback: 3 } },+ { label: 'Custom (blank)', condition: { ...DEFAULT_CONDITION } },+];+const ConditionBuilder: React.FC<ConditionBuilderProps> = ({label,conditions,@@ -32,8 +54,13 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({onConditionsChange,onLogicChange,}) => {- const handleAdd = () => {- onConditionsChange([...conditions, { ...DEFAULT_CONDITION }]);+ const [showQuickAdd, setShowQuickAdd] = useState(false);++ const handleAdd = (condition?: ConditionItem) => {+ // Deep clone to avoid mutating template constants (params/compareParams are nested objects)+ const newCondition = JSON.parse(JSON.stringify(condition || DEFAULT_CONDITION));+ onConditionsChange([...conditions, newCondition]);+ setShowQuickAdd(false);};const handleChange = (index: number, updated: ConditionItem) => {@@ -46,6 +73,13 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({onConditionsChange(conditions.filter((_, i) => i !== index));};+ // Build inline summary for header+ const condCount = conditions.length;+ const indicatorNames = conditions.map(c => {+ const def = getIndicatorDef(c.indicator);+ return def?.label || c.indicator;+ });+return (<div style={{backgroundColor: F.PANEL_BG,@@ -61,9 +95,16 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({alignItems: 'center',justifyContent: 'space-between',}}>- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>- {label.toUpperCase()}- </span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>+ {label.toUpperCase()}+ </span>+ {condCount > 0 && (+ <span style={{ fontSize: '8px', color: F.MUTED }}>+ ({condCount} condition{condCount !== 1 ? 's' : ''}: {indicatorNames.join(` ${logic} `)})+ </span>+ )}+ </div><div style={{ display: 'flex', gap: '2px' }}>{(['AND', 'OR'] as const).map(l => (<button@@ -90,6 +131,13 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({{/* Condition rows */}<div style={{ padding: '4px 0' }}>+ {conditions.length === 0 && (+ <div style={{+ padding: '12px 16px', textAlign: 'center', color: F.MUTED, fontSize: '9px',+ }}>+ No conditions added. Click "ADD CONDITION" below.+ </div>+ )}{conditions.map((cond, i) => (<div key={i}>{i > 0 && (@@ -115,36 +163,101 @@ const ConditionBuilder: React.FC<ConditionBuilderProps> = ({))}</div>- {/* Add button */}- <div style={{ padding: '4px 8px 8px' }}>- <button- onClick={handleAdd}- style={{- padding: '6px 10px',- backgroundColor: 'transparent',+ {/* Add button + Quick add dropdown */}+ <div style={{ padding: '4px 8px 8px', position: 'relative' }}>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={() => handleAdd()}+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`,+ color: F.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.ORANGE;+ (e.currentTarget as HTMLElement).style.color = F.WHITE;+ }}+ onMouseLeave={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;+ (e.currentTarget as HTMLElement).style.color = F.GRAY;+ }}+ >+ <Plus size={10} />+ ADD CONDITION+ </button>+ <button+ onClick={() => setShowQuickAdd(!showQuickAdd)}+ style={{+ padding: '6px 8px',+ backgroundColor: 'transparent',+ border: `1px solid ${F.BORDER}`,+ color: showQuickAdd ? F.CYAN : F.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '3px',+ transition: 'all 0.2s',+ borderColor: showQuickAdd ? F.CYAN : F.BORDER,+ }}+ >+ {showQuickAdd ? <ChevronDown size={10} /> : <ChevronRight size={10} />}+ TEMPLATES+ </button>+ </div>++ {/* Quick-add dropdown */}+ {showQuickAdd && (+ <div style={{+ marginTop: '4px',+ backgroundColor: F.DARK_BG,border: `1px solid ${F.BORDER}`,- color: F.GRAY,- fontSize: '9px',- fontWeight: 700,borderRadius: '2px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- transition: 'all 0.2s',- }}- onMouseEnter={e => {- (e.currentTarget as HTMLElement).style.borderColor = F.ORANGE;- (e.currentTarget as HTMLElement).style.color = F.WHITE;- }}- onMouseLeave={e => {- (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;- (e.currentTarget as HTMLElement).style.color = F.GRAY;- }}- >- <Plus size={10} />- ADD CONDITION- </button>+ maxHeight: '200px',+ overflow: 'auto',+ }}>+ {QUICK_CONDITIONS.map((qc, i) => (+ <button+ key={i}+ onClick={() => handleAdd(qc.condition)}+ style={{+ width: '100%',+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: 'none',+ borderBottom: i < QUICK_CONDITIONS.length - 1 ? `1px solid ${F.BORDER}` : 'none',+ color: F.GRAY,+ fontSize: '9px',+ fontFamily: '"IBM Plex Mono", monospace',+ cursor: 'pointer',+ textAlign: 'left',+ transition: 'all 0.1s',+ }}+ onMouseEnter={e => {+ (e.currentTarget as HTMLElement).style.backgroundColor = F.HEADER_BG;+ (e.currentTarget as HTMLElement).style.color = F.WHITE;+ }}+ onMouseLeave={e => {+ (e.currentTarget as HTMLElement).style.backgroundColor = 'transparent';+ (e.currentTarget as HTMLElement).style.color = F.GRAY;+ }}+ >+ {qc.label}+ </button>+ ))}+ </div>+ )}</div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsxindex 250fb5c32..830acef17 100644--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx@@ -1,7 +1,7 @@import React, { useState } from 'react';-import { Search, Loader, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';-import type { ConditionItem, ScanResult } from '../types';-import { TIMEFRAMES } from '../constants/indicators';+import { Search, Loader, ChevronDown, ChevronRight, AlertTriangle, Zap, List, RotateCcw } from 'lucide-react';+import type { ConditionItem, ScanResult, ConditionDetail } from '../types';+import { TIMEFRAMES, getIndicatorDef } from '../constants/indicators';import { runAlgoScan } from '../services/algoTradingService';import { useStockBrokerContextOptional } from '@/contexts/StockBrokerContext';import { useBrokerContext } from '@/contexts/BrokerContext';@@ -11,7 +11,7 @@ const F = {ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A', CYAN: '#00E5FF',- YELLOW: '#FFD600',+ YELLOW: '#FFD600', PURPLE: '#9D4EDD', BLUE: '#0088FF',};const inputStyle: React.CSSProperties = {@@ -25,17 +25,194 @@ const labelStyle: React.CSSProperties = {marginBottom: '4px', display: 'block',};+const chipStyle: React.CSSProperties = {+ padding: '3px 8px', backgroundColor: 'transparent', border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', color: F.GRAY, fontSize: '8px', fontWeight: 700,+ letterSpacing: '0.5px', cursor: 'pointer', transition: 'all 0.15s',+ fontFamily: '"IBM Plex Mono", monospace',+};+interface SymbolError {symbol: string;error: string;}+// ── Scan Presets (Chartink-style templates) ──────────────────────────────+interface ScanPreset {+ name: string;+ description: string;+ conditions: ConditionItem[];+ logic: 'AND' | 'OR';+}++const SCAN_PRESETS: ScanPreset[] = [+ {+ name: 'RSI Oversold',+ description: 'RSI(14) < 30 — oversold stocks',+ conditions: [+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 },+ ],+ logic: 'AND',+ },+ {+ name: 'RSI Overbought',+ description: 'RSI(14) > 70 — overbought stocks',+ conditions: [+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '>', value: 70 },+ ],+ logic: 'AND',+ },+ {+ name: 'Golden Cross',+ description: 'EMA(50) crosses above SMA(200)',+ conditions: [+ {+ indicator: 'EMA', params: { period: 50 }, field: 'value', operator: 'crosses_above', value: 0,+ compareMode: 'indicator', compareIndicator: 'SMA', compareParams: { period: 200 }, compareField: 'value',+ },+ ],+ logic: 'AND',+ },+ {+ name: 'Death Cross',+ description: 'EMA(50) crosses below SMA(200)',+ conditions: [+ {+ indicator: 'EMA', params: { period: 50 }, field: 'value', operator: 'crosses_below', value: 0,+ compareMode: 'indicator', compareIndicator: 'SMA', compareParams: { period: 200 }, compareField: 'value',+ },+ ],+ logic: 'AND',+ },+ {+ name: 'MACD Bullish Cross',+ description: 'MACD line crosses above signal line',+ conditions: [+ {+ indicator: 'MACD', params: { fast: 12, slow: 26, signal: 9 }, field: 'line', operator: 'crosses_above', value: 0,+ compareMode: 'indicator', compareIndicator: 'MACD', compareParams: { fast: 12, slow: 26, signal: 9 }, compareField: 'signal_line',+ },+ ],+ logic: 'AND',+ },+ {+ name: 'Bollinger Squeeze',+ description: 'Price below lower Bollinger Band + RSI < 35',+ conditions: [+ {+ indicator: 'CLOSE', params: {}, field: 'value', operator: '<', value: 0,+ compareMode: 'indicator', compareIndicator: 'BOLLINGER', compareParams: { period: 20, std_dev: 2 }, compareField: 'lower',+ },+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 35 },+ ],+ logic: 'AND',+ },+ {+ name: 'Volume Breakout',+ description: 'Volume > 2x SMA(20) of volume + price rising 3 bars',+ conditions: [+ { indicator: 'CLOSE', params: {}, field: 'value', operator: 'rising', value: 0, lookback: 3 },+ { indicator: 'MFI', params: { period: 14 }, field: 'value', operator: '>', value: 60 },+ ],+ logic: 'AND',+ },+ {+ name: 'Supertrend Buy',+ description: 'Supertrend direction is bullish (1)',+ conditions: [+ { indicator: 'SUPERTREND', params: { period: 10, multiplier: 3 }, field: 'direction', operator: '==', value: 1 },+ ],+ logic: 'AND',+ },+ {+ name: 'RSI + MACD Combo',+ description: 'RSI rising + MACD histogram > 0',+ conditions: [+ { indicator: 'RSI', params: { period: 14 }, field: 'value', operator: 'rising', value: 0, lookback: 3 },+ { indicator: 'MACD', params: { fast: 12, slow: 26, signal: 9 }, field: 'histogram', operator: '>', value: 0 },+ ],+ logic: 'AND',+ },+ {+ name: 'Price Above VWAP',+ description: 'Close crosses above VWAP (intraday)',+ conditions: [+ {+ indicator: 'CLOSE', params: {}, field: 'value', operator: 'crosses_above', value: 0,+ compareMode: 'indicator', compareIndicator: 'VWAP', compareParams: {}, compareField: 'value',+ },+ ],+ logic: 'AND',+ },+];++// ── Symbol Watchlists ────────────────────────────────────────────────────+const SYMBOL_WATCHLISTS: Record<string, string[]> = {+ 'NIFTY 50': [+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK', 'HINDUNILVR', 'ITC', 'SBIN',+ 'BHARTIARTL', 'KOTAKBANK', 'LT', 'AXISBANK', 'WIPRO', 'ASIANPAINT', 'MARUTI',+ 'BAJFINANCE', 'HCLTECH', 'SUNPHARMA', 'TITAN', 'TATASTEEL', 'ULTRACEMCO',+ 'ONGC', 'NTPC', 'POWERGRID', 'M&M', 'NESTLEIND', 'ADANIENT', 'JSWSTEEL',+ 'BAJAJFINSV', 'TECHM', 'INDUSINDBK', 'HINDALCO', 'TATAMOTORS', 'COALINDIA',+ 'GRASIM', 'SBILIFE', 'CIPLA', 'DIVISLAB', 'DRREDDY', 'BPCL',+ 'APOLLOHOSP', 'EICHERMOT', 'TATACONSUM', 'BRITANNIA', 'HDFCLIFE',+ 'HEROMOTOCO', 'BAJAJ-AUTO', 'LTIM', 'ADANIPORTS', 'UPL',+ ],+ 'BANK NIFTY': [+ 'HDFCBANK', 'ICICIBANK', 'KOTAKBANK', 'AXISBANK', 'SBIN', 'INDUSINDBK',+ 'BANKBARODA', 'AUBANK', 'FEDERALBNK', 'BANDHANBNK', 'PNB', 'IDFCFIRSTB',+ ],+ 'IT STOCKS': [+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM', 'MPHASIS', 'COFORGE',+ 'PERSISTENT', 'TATAELXSI', 'LTTS', 'MINDTREE',+ ],+ 'PHARMA': [+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'DIVISLAB', 'AUROPHARMA', 'LUPIN',+ 'BIOCON', 'TORNTPHARM', 'ALKEM', 'GLENMARK',+ ],+};+const STOCK_BROKERS = ['fyers', 'zerodha', 'upstox', 'dhan', 'angelone', 'kotak', 'groww', 'aliceblue', 'fivepaisa', 'iifl', 'motilal', 'shoonya'];+// ── Helper to format condition detail for display ────────────────────────+function formatConditionDetail(d: ConditionDetail): React.ReactNode {+ const opLabels: Record<string, string> = {+ '>': '>', '<': '<', '>=': '>=', '<=': '<=', '==': '==',+ 'crosses_above': 'X↑', 'crosses_below': 'X↓', 'between': 'BTW',+ 'crossed_above_within': 'X↑ N', 'crossed_below_within': 'X↓ N',+ 'rising': '↑N', 'falling': '↓N',+ };+ const op = opLabels[d.operator] || d.operator;+ const val = d.computed_value != null ? d.computed_value.toFixed(2) : '—';++ if (d.target_indicator) {+ const targetVal = d.target_computed_value != null ? d.target_computed_value.toFixed(2) : '—';+ return (+ <span>+ <span style={{ color: F.WHITE, fontWeight: 700 }}>{d.indicator}</span>+ {d.field !== 'value' && <span style={{ color: F.MUTED }}>.{d.field}</span>}+ <span style={{ color: F.CYAN }}>={val}</span>+ <span style={{ color: F.ORANGE, margin: '0 3px' }}>{op}</span>+ <span style={{ color: F.YELLOW, fontWeight: 700 }}>{d.target_indicator}</span>+ <span style={{ color: F.CYAN }}>={targetVal}</span>+ </span>+ );+ }++ return (+ <span>+ <span style={{ color: F.WHITE, fontWeight: 700 }}>{d.indicator}</span>+ {d.field !== 'value' && <span style={{ color: F.MUTED }}>.{d.field}</span>}+ <span style={{ color: F.CYAN }}>={val}</span>+ <span style={{ color: F.ORANGE, margin: '0 3px' }}>{op}</span>+ <span style={{ color: F.MUTED }}>{d.target}</span>+ </span>+ );+}+const ScannerPanel: React.FC = () => {const stockBroker = useStockBrokerContextOptional();const { activeBroker } = useBrokerContext();- // For scanner, always prefer stock broker. Fallback to 'fyers' if the active broker is crypto-only.const provider = stockBroker?.activeBroker|| (STOCK_BROKERS.includes(activeBroker) ? activeBroker : null)|| 'fyers';@@ -54,6 +231,8 @@ const ScannerPanel: React.FC = () => {const [showDebug, setShowDebug] = useState(false);const [prefetchWarning, setPrefetchWarning] = useState('');const [symbolErrors, setSymbolErrors] = useState<SymbolError[]>([]);+ const [showPresets, setShowPresets] = useState(false);+ const [expandedResult, setExpandedResult] = useState<number | null>(null);const buildConditionsJson = (): string => {if (conditions.length === 0) return '[]';@@ -73,12 +252,12 @@ const ScannerPanel: React.FC = () => {setDebugLog([]);setPrefetchWarning('');setSymbolErrors([]);+ setExpandedResult(null);try {const result = await runAlgoScan(buildConditionsJson(), JSON.stringify(symbols), timeframe, provider);setScanning(false);- // Capture debug info regardless of success/failureif (result.debug) setDebugLog(result.debug);if (result.prefetch_warning) setPrefetchWarning(result.prefetch_warning);@@ -99,10 +278,126 @@ const ScannerPanel: React.FC = () => {}};+ const applyPreset = (preset: ScanPreset) => {+ // Deep clone to avoid mutating preset constants (params/compareParams are nested objects)+ setConditions(JSON.parse(JSON.stringify(preset.conditions)));+ setLogic(preset.logic);+ setShowPresets(false);+ };++ const appendWatchlist = (name: string) => {+ const symbols = SYMBOL_WATCHLISTS[name];+ if (!symbols) return;+ const existing = symbolsInput.split(/[,\n]/).map(s => s.trim().toUpperCase()).filter(Boolean);+ const newSymbols = symbols.filter(s => !existing.includes(s));+ const merged = [...existing, ...newSymbols];+ setSymbolsInput(merged.join(', '));+ };++ // Build a summary of the current scan conditions+ const conditionSummary = conditions.map(c => {+ const def = getIndicatorDef(c.indicator);+ const label = def?.label || c.indicator;+ const paramValues = Object.values(c.params);+ const paramStr = paramValues.length > 0 ? `(${paramValues.join(',')})` : '';+ const fieldStr = c.field !== 'value' ? `.${c.field}` : '';+ const opStr = c.operator;+ if (c.compareMode === 'indicator' && c.compareIndicator) {+ const cDef = getIndicatorDef(c.compareIndicator);+ const cLabel = cDef?.label || c.compareIndicator;+ const cParamValues = Object.values(c.compareParams || {});+ const cParamStr = cParamValues.length > 0 ? `(${cParamValues.join(',')})` : '';+ return `${label}${paramStr}${fieldStr} ${opStr} ${cLabel}${cParamStr}`;+ }+ return `${label}${paramStr}${fieldStr} ${opStr} ${c.value}`;+ }).join(` ${logic} `);+return (<div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>SCANNER</span>+ {/* Scanner Header + Presets Toggle */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <span style={{ fontSize: '11px', fontWeight: 700, color: F.WHITE, letterSpacing: '0.5px' }}>SCANNER</span>+ <div style={{ display: 'flex', gap: '6px' }}>+ <button+ onClick={() => setShowPresets(!showPresets)}+ style={{+ ...chipStyle,+ color: showPresets ? F.ORANGE : F.GRAY,+ borderColor: showPresets ? F.ORANGE : F.BORDER,+ }}+ >+ <Zap size={8} style={{ marginRight: '3px', display: 'inline' }} />+ PRESETS+ </button>+ <button+ onClick={() => {+ setConditions([{ indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 }]);+ setLogic('AND');+ setResults(null);+ setError('');+ setDebugLog([]);+ setPrefetchWarning('');+ setSymbolErrors([]);+ }}+ style={chipStyle}+ >+ <RotateCcw size={8} style={{ marginRight: '3px', display: 'inline' }} />+ RESET+ </button>+ </div>+ </div>++ {/* Scan Presets Panel */}+ {showPresets && (+ <div style={{+ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px',+ padding: '8px',+ }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>+ SCAN TEMPLATES — CLICK TO APPLY+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '6px' }}>+ {SCAN_PRESETS.map((preset, i) => (+ <button+ key={i}+ onClick={() => applyPreset(preset)}+ style={{+ padding: '8px 10px', backgroundColor: F.DARK_BG, border: `1px solid ${F.BORDER}`,+ borderRadius: '2px', cursor: 'pointer', textAlign: 'left', transition: 'all 0.15s',+ }}+ onMouseEnter={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.ORANGE;+ (e.currentTarget as HTMLElement).style.backgroundColor = F.HEADER_BG;+ }}+ onMouseLeave={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;+ (e.currentTarget as HTMLElement).style.backgroundColor = F.DARK_BG;+ }}+ >+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.ORANGE, marginBottom: '2px' }}>+ {preset.name}+ </div>+ <div style={{ fontSize: '8px', color: F.MUTED, lineHeight: '1.4' }}>+ {preset.description}+ </div>+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Active Condition Summary */}+ {conditions.length > 0 && (+ <div style={{+ padding: '6px 10px', backgroundColor: `${F.ORANGE}08`, border: `1px solid ${F.ORANGE}20`,+ borderRadius: '2px', fontSize: '9px', color: F.ORANGE, fontFamily: '"IBM Plex Mono", monospace',+ }}>+ <span style={{ fontWeight: 700, marginRight: '6px' }}>SCAN:</span>+ {conditionSummary}+ </div>+ )}+ {/* Condition Builder */}<ConditionBuilder label="Scan Conditions" conditions={conditions} logic={logic}onConditionsChange={setConditions} onLogicChange={setLogic} />@@ -117,6 +412,31 @@ const ScannerPanel: React.FC = () => {rows={3}style={{ ...inputStyle, resize: 'none' } as React.CSSProperties}/>+ {/* Watchlist Quick-Add */}+ <div style={{ display: 'flex', gap: '4px', marginTop: '4px', flexWrap: 'wrap' }}>+ {Object.keys(SYMBOL_WATCHLISTS).map(name => (+ <button+ key={name}+ onClick={() => appendWatchlist(name)}+ style={{+ ...chipStyle,+ padding: '2px 6px',+ fontSize: '7px',+ }}+ onMouseEnter={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.CYAN;+ (e.currentTarget as HTMLElement).style.color = F.CYAN;+ }}+ onMouseLeave={e => {+ (e.currentTarget as HTMLElement).style.borderColor = F.BORDER;+ (e.currentTarget as HTMLElement).style.color = F.GRAY;+ }}+ title={`Add ${SYMBOL_WATCHLISTS[name].length} symbols`}+ >+ + {name} ({SYMBOL_WATCHLISTS[name].length})+ </button>+ ))}+ </div></div><div><label style={labelStyle}>TIMEFRAME</label>@@ -138,12 +458,8 @@ const ScannerPanel: React.FC = () => {{/* Error Display */}{error && (<div style={{ padding: '8px 10px', backgroundColor: `${F.RED}15`, border: `1px solid ${F.RED}40`, borderRadius: '2px' }}>- <div style={{ fontSize: '9px', fontWeight: 700, color: F.RED, marginBottom: '2px' }}>- SCAN ERROR- </div>- <div style={{ fontSize: '9px', color: F.RED, lineHeight: '1.4', whiteSpace: 'pre-wrap' }}>- {error}- </div>+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.RED, marginBottom: '2px' }}>SCAN ERROR</div>+ <div style={{ fontSize: '9px', color: F.RED, lineHeight: '1.4', whiteSpace: 'pre-wrap' }}>{error}</div></div>)}@@ -211,10 +527,19 @@ const ScannerPanel: React.FC = () => {{/* Results */}{results !== null && (<div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>- <div style={{ padding: '8px 12px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}` }}>+ <div style={{+ padding: '8px 12px', backgroundColor: F.HEADER_BG, borderBottom: `1px solid ${F.BORDER}`,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ }}><span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>RESULTS: <span style={{ color: F.CYAN }}>{results.length}</span> MATCH{results.length !== 1 ? 'ES' : ''} / {scanned} SCANNED</span>+ {results.length > 0 && (+ <span style={{ fontSize: '8px', color: F.MUTED }}>+ <List size={8} style={{ marginRight: '3px', display: 'inline' }} />+ CLICK ROW FOR DETAILS+ </span>+ )}</div>{results.length === 0 ? (<div style={{ padding: '24px', textAlign: 'center', fontSize: '10px', color: F.MUTED }}>@@ -225,24 +550,102 @@ const ScannerPanel: React.FC = () => {<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px', fontFamily: '"IBM Plex Mono", monospace' }}><thead><tr style={{ borderBottom: `1px solid ${F.BORDER}` }}>+ <th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>#</th><th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>SYMBOL</th><th style={{ padding: '6px 12px', textAlign: 'right', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>PRICE</th>- <th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>INDICATORS</th>+ <th style={{ padding: '6px 12px', textAlign: 'left', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>CONDITIONS</th>+ <th style={{ padding: '6px 12px', textAlign: 'center', fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>STATUS</th></tr></thead><tbody>{results.map((r, i) => (- <tr key={i} style={{ borderBottom: `1px solid ${F.BORDER}15` }}>- <td style={{ padding: '6px 12px', fontWeight: 700, color: F.WHITE }}>{r.symbol}</td>- <td style={{ padding: '6px 12px', textAlign: 'right', color: F.CYAN }}>{r.price.toFixed(2)}</td>- <td style={{ padding: '6px 12px' }}>- {r.details.map((d, j) => (- <span key={j} style={{ marginRight: '8px', color: d.met ? F.GREEN : F.RED, fontSize: '9px' }}>- {d.indicator}({d.field})={d.computed_value?.toFixed(2)}+ <React.Fragment key={i}>+ <tr+ onClick={() => setExpandedResult(expandedResult === i ? null : i)}+ style={{+ borderBottom: `1px solid ${F.BORDER}15`,+ cursor: 'pointer',+ backgroundColor: expandedResult === i ? `${F.ORANGE}08` : 'transparent',+ transition: 'background-color 0.15s',+ }}+ onMouseEnter={e => {+ if (expandedResult !== i) (e.currentTarget as HTMLElement).style.backgroundColor = F.HEADER_BG;+ }}+ onMouseLeave={e => {+ if (expandedResult !== i) (e.currentTarget as HTMLElement).style.backgroundColor = 'transparent';+ }}+ >+ <td style={{ padding: '6px 12px', color: F.MUTED }}>{i + 1}</td>+ <td style={{ padding: '6px 12px', fontWeight: 700, color: F.WHITE }}>{r.symbol}</td>+ <td style={{ padding: '6px 12px', textAlign: 'right', color: F.CYAN, fontWeight: 700 }}>{r.price.toFixed(2)}</td>+ <td style={{ padding: '6px 12px' }}>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>+ {r.details.map((d, j) => (+ <span key={j} style={{+ display: 'inline-flex', alignItems: 'center', gap: '3px',+ padding: '1px 5px', borderRadius: '2px', fontSize: '8px',+ backgroundColor: d.met ? `${F.GREEN}15` : `${F.RED}15`,+ border: `1px solid ${d.met ? F.GREEN : F.RED}30`,+ color: d.met ? F.GREEN : F.RED,+ }}>+ {d.met ? '✓' : '✗'} {d.indicator}{d.field !== 'value' ? `.${d.field}` : ''}+ </span>+ ))}+ </div>+ </td>+ <td style={{ padding: '6px 12px', textAlign: 'center' }}>+ <span style={{+ padding: '2px 6px', borderRadius: '2px', fontSize: '8px', fontWeight: 700,+ backgroundColor: `${F.GREEN}15`, color: F.GREEN, border: `1px solid ${F.GREEN}40`,+ }}>+ MATCH</span>- ))}- </td>- </tr>+ </td>+ </tr>+ {/* Expanded detail row */}+ {expandedResult === i && (+ <tr>+ <td colSpan={5} style={{ padding: '0' }}>+ <div style={{+ padding: '8px 12px', backgroundColor: `${F.DARK_BG}`,+ borderBottom: `1px solid ${F.BORDER}`,+ }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>+ CONDITION DETAILS FOR {r.symbol}+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>+ {r.details.map((d, j) => (+ <div key={j} style={{+ display: 'flex', alignItems: 'center', gap: '8px',+ padding: '4px 8px', backgroundColor: F.PANEL_BG,+ borderRadius: '2px', border: `1px solid ${F.BORDER}`,+ fontSize: '9px',+ }}>+ <span style={{+ width: '16px', height: '16px', borderRadius: '2px',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ fontSize: '8px', fontWeight: 700, flexShrink: 0,+ backgroundColor: d.met ? `${F.GREEN}20` : `${F.RED}20`,+ color: d.met ? F.GREEN : F.RED,+ }}>+ {d.met ? '✓' : '✗'}+ </span>+ <div style={{ flex: 1 }}>+ {formatConditionDetail(d)}+ </div>+ {d.error && (+ <span style={{ fontSize: '8px', color: F.RED, fontStyle: 'italic' }}>+ {d.error}+ </span>+ )}+ </div>+ ))}+ </div>+ </div>+ </td>+ </tr>+ )}+ </React.Fragment>))}</tbody></table>diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsxindex 207485cb7..f95330b85 100644--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/MAAnalyticsTab.tsx@@ -1,56 +1,145 @@/**- * M&A Analytics Tab - Streamlined & Unified+ * M&A Analytics Tab - Comprehensive Corporate Finance Toolkit*- * Clean, professional M&A toolkit with 3 focused sections:+ * Professional M&A analytics with 8 focused sections:* 1. Valuation Toolkit - DCF, LBO, Trading Comps* 2. Merger Analysis - Accretion/Dilution, Synergies, Deal Structure* 3. Deal Database - Track and save deals+ * 4. Startup Valuation - Berkus, Scorecard, VC Method, First Chicago, Risk Factor+ * 5. Fairness Opinion - Valuation framework, premium analysis, process quality+ * 6. Industry Metrics - Technology, Healthcare, Financial Services+ * 7. Advanced Analytics - Monte Carlo, Regression+ * 8. Deal Comparison - Compare, rank, benchmark deals*/-import React, { useState , useCallback } from 'react';+import React, { useState, useCallback } from 'react';import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';-import { Calculator, GitMerge, Database, TrendingUp, Building2, Zap } from 'lucide-react';+import {+ Calculator,+ GitMerge,+ Database,+ Building2,+ Rocket,+ Scale,+ BarChart3,+ Activity,+ GitCompare,+} from 'lucide-react';import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../portfolio-tab/finceptStyles';-// Import new unified panels+// Import unified panelsimport { ValuationToolkit } from './unified/ValuationToolkit';import { MergerAnalysis } from './unified/MergerAnalysis';import { DealDatabase } from './unified/DealDatabase';+import { StartupValuation } from './unified/StartupValuation';+import { FairnessOpinion } from './unified/FairnessOpinion';+import { IndustryMetrics } from './unified/IndustryMetrics';+import { AdvancedAnalytics } from './unified/AdvancedAnalytics';+import { DealComparison } from './unified/DealComparison';-type MainTab = 'valuation' | 'merger' | 'database';+type MainTab =+ | 'valuation'+ | 'merger'+ | 'database'+ | 'startup'+ | 'fairness'+ | 'industry'+ | 'advanced'+ | 'comparison';++interface TabConfig {+ id: MainTab;+ label: string;+ shortLabel: string;+ icon: React.ElementType;+ description: string;+ category: 'core' | 'specialized' | 'analytics';+}const MAAnalyticsTabNew: React.FC = () => {const [activeTab, setActiveTab] = useState<MainTab>('valuation');// Workspace tab state- const getWorkspaceState = useCallback(() => ({- activeTab,- }), [activeTab]);+ const getWorkspaceState = useCallback(+ () => ({+ activeTab,+ }),+ [activeTab]+ );const setWorkspaceState = useCallback((state: Record<string, unknown>) => {- if (typeof state.activeTab === "string") setActiveTab(state.activeTab as any);+ if (typeof state.activeTab === 'string') setActiveTab(state.activeTab as MainTab);}, []);- useWorkspaceTabState("ma-analytics", getWorkspaceState, setWorkspaceState);+ useWorkspaceTabState('ma-analytics', getWorkspaceState, setWorkspaceState);- const TABS = [+ const TABS: TabConfig[] = [+ // Core M&A Tools{- id: 'valuation' as const,- label: 'VALUATION TOOLKIT',+ id: 'valuation',+ label: 'Valuation Toolkit',+ shortLabel: 'Valuation',icon: Calculator,- description: 'DCF, LBO, Trading Comps'+ description: 'DCF, LBO, Trading Comps',+ category: 'core',},{- id: 'merger' as const,- label: 'MERGER ANALYSIS',+ id: 'merger',+ label: 'Merger Analysis',+ shortLabel: 'Mergers',icon: GitMerge,- description: 'Accretion/Dilution, Synergies'+ description: 'Accretion/Dilution, Synergies',+ category: 'core',},{- id: 'database' as const,- label: 'DEAL DATABASE',+ id: 'database',+ label: 'Deal Database',+ shortLabel: 'Deals',icon: Database,- description: 'Track & Save Deals'+ description: 'Track & Save Deals',+ category: 'core',+ },+ // Specialized Tools+ {+ id: 'startup',+ label: 'Startup Valuation',+ shortLabel: 'Startup',+ icon: Rocket,+ description: 'Berkus, Scorecard, VC Method',+ category: 'specialized',+ },+ {+ id: 'fairness',+ label: 'Fairness Opinion',+ shortLabel: 'Fairness',+ icon: Scale,+ description: 'Board-level analysis',+ category: 'specialized',+ },+ {+ id: 'industry',+ label: 'Industry Metrics',+ shortLabel: 'Industry',+ icon: BarChart3,+ description: 'Sector-specific metrics',+ category: 'specialized',+ },+ // Analytics+ {+ id: 'advanced',+ label: 'Advanced Analytics',+ shortLabel: 'Advanced',+ icon: Activity,+ description: 'Monte Carlo, Regression',+ category: 'analytics',+ },+ {+ id: 'comparison',+ label: 'Deal Comparison',+ shortLabel: 'Compare',+ icon: GitCompare,+ description: 'Compare & Benchmark',+ category: 'analytics',},];@@ -62,133 +151,219 @@ const MAAnalyticsTabNew: React.FC = () => {return <MergerAnalysis />;case 'database':return <DealDatabase />;+ case 'startup':+ return <StartupValuation />;+ case 'fairness':+ return <FairnessOpinion />;+ case 'industry':+ return <IndustryMetrics />;+ case 'advanced':+ return <AdvancedAnalytics />;+ case 'comparison':+ return <DealComparison />;default:return null;}};+ const renderCategoryTabs = (category: 'core' | 'specialized' | 'analytics') => {+ const categoryTabs = TABS.filter((t) => t.category === category);+ return categoryTabs.map((tab) => {+ const Icon = tab.icon;+ const isActive = activeTab === tab.id;+ return (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id)}+ title={`${tab.label}: ${tab.description}`}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 12px',+ backgroundColor: isActive ? FINCEPT.PANEL_BG : 'transparent',+ border: `1px solid ${isActive ? FINCEPT.ORANGE : 'transparent'}`,+ borderRadius: '4px',+ color: isActive ? FINCEPT.ORANGE : FINCEPT.GRAY,+ cursor: 'pointer',+ transition: 'all 0.15s',+ fontSize: '11px',+ fontWeight: isActive ? 600 : 400,+ letterSpacing: '0.5px',+ whiteSpace: 'nowrap',+ }}+ onMouseEnter={(e) => {+ if (!isActive) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.color = '#fff';+ }+ }}+ onMouseLeave={(e) => {+ if (!isActive) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = FINCEPT.GRAY;+ }+ }}+ >+ <Icon size={14} />+ <span>{tab.shortLabel}</span>+ </button>+ );+ });+ };+return (- <div style={{- display: 'flex',- flexDirection: 'column',- height: '100%',- backgroundColor: FINCEPT.DARK_BG,- fontFamily: TYPOGRAPHY.MONO,- }}>+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ backgroundColor: FINCEPT.DARK_BG,+ fontFamily: TYPOGRAPHY.MONO,+ }}+ >{/* Header */}- <div style={{- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `2px solid ${FINCEPT.ORANGE}`,- padding: SPACING.DEFAULT,- }}>- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- marginBottom: SPACING.DEFAULT,- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <div+ style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ padding: '12px 16px',+ }}+ >+ {/* Title Row */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '12px',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><Building2 size={20} color={FINCEPT.ORANGE} />- <span style={{- color: FINCEPT.ORANGE,- fontWeight: TYPOGRAPHY.BOLD,- fontSize: TYPOGRAPHY.HEADING,- letterSpacing: TYPOGRAPHY.WIDE,- }}>+ <span+ style={{+ color: FINCEPT.ORANGE,+ fontWeight: 700,+ fontSize: '14px',+ letterSpacing: '1px',+ }}+ >M&A ANALYTICS</span></div>- <div style={{- fontSize: TYPOGRAPHY.TINY,- color: FINCEPT.GRAY,- letterSpacing: TYPOGRAPHY.WIDE,- }}>- PROFESSIONAL TOOLKIT+ <div+ style={{+ fontSize: '10px',+ color: FINCEPT.GRAY,+ letterSpacing: '1px',+ }}+ >+ CORPORATE FINANCE TOOLKIT</div></div>- {/* Tab Navigation */}- <div style={{ display: 'flex', gap: SPACING.SMALL }}>- {TABS.map((tab) => {- const Icon = tab.icon;- const isActive = activeTab === tab.id;- return (- <button- key={tab.id}- onClick={() => setActiveTab(tab.id)}- style={{- flex: 1,- padding: SPACING.DEFAULT,- backgroundColor: isActive ? FINCEPT.PANEL_BG : 'transparent',- border: `1px solid ${isActive ? FINCEPT.ORANGE : FINCEPT.BORDER}`,- borderRadius: '4px',- color: isActive ? FINCEPT.ORANGE : FINCEPT.GRAY,- cursor: 'pointer',- transition: 'all 0.2s',- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- gap: SPACING.TINY,- }}- onMouseEnter={(e) => {- if (!isActive) {- e.currentTarget.style.borderColor = FINCEPT.GRAY;- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;- }- }}- onMouseLeave={(e) => {- if (!isActive) {- e.currentTarget.style.borderColor = FINCEPT.BORDER;- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>- <Icon size={14} />- <span style={{- fontSize: TYPOGRAPHY.SMALL,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- }}>- {tab.label}- </span>- </div>- <span style={{- fontSize: TYPOGRAPHY.TINY,- color: FINCEPT.MUTED,- }}>- {tab.description}- </span>- </button>- );- })}+ {/* Tab Navigation - Grouped by Category */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '16px',+ flexWrap: 'wrap',+ }}+ >+ {/* Core Tools */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ style={{+ fontSize: '9px',+ color: FINCEPT.MUTED,+ letterSpacing: '1px',+ marginRight: '4px',+ }}+ >+ CORE+ </span>+ {renderCategoryTabs('core')}+ </div>++ <div+ style={{+ width: '1px',+ height: '24px',+ backgroundColor: FINCEPT.BORDER,+ }}+ />++ {/* Specialized Tools */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ style={{+ fontSize: '9px',+ color: FINCEPT.MUTED,+ letterSpacing: '1px',+ marginRight: '4px',+ }}+ >+ SPECIALIZED+ </span>+ {renderCategoryTabs('specialized')}+ </div>++ <div+ style={{+ width: '1px',+ height: '24px',+ backgroundColor: FINCEPT.BORDER,+ }}+ />++ {/* Analytics */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ style={{+ fontSize: '9px',+ color: FINCEPT.MUTED,+ letterSpacing: '1px',+ marginRight: '4px',+ }}+ >+ ANALYTICS+ </span>+ {renderCategoryTabs('analytics')}+ </div></div></div>{/* Main Content */}- <div style={{- flex: 1,- overflow: 'hidden',- }}>+ <div+ style={{+ flex: 1,+ overflow: 'hidden',+ }}+ >{renderContent()}</div>{/* Status Bar */}- <div style={{- backgroundColor: FINCEPT.HEADER_BG,- borderTop: `1px solid ${FINCEPT.BORDER}`,- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,- fontSize: TYPOGRAPHY.TINY,- color: FINCEPT.GRAY,- display: 'flex',- justifyContent: 'space-between',- }}>+ <div+ style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ padding: '6px 16px',+ fontSize: '10px',+ color: FINCEPT.GRAY,+ display: 'flex',+ justifyContent: 'space-between',+ }}+ ><span>- ACTIVE: <span style={{ color: FINCEPT.ORANGE }}>- {TABS.find(t => t.id === activeTab)?.label}+ ACTIVE:{' '}+ <span style={{ color: FINCEPT.ORANGE }}>+ {TABS.find((t) => t.id === activeTab)?.label.toUpperCase()}</span></span>- <span style={{ color: FINCEPT.MUTED }}>FINCEPT TERMINAL v3.2.1</span>+ <span style={{ color: FINCEPT.MUTED }}>FINCEPT TERMINAL v3.3</span></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/AdvancedAnalytics.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/AdvancedAnalytics.tsxnew file mode 100644index 000000000..01ab943ab--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/AdvancedAnalytics.tsx@@ -0,0 +1,544 @@+/**+ * Advanced Analytics Panel - Monte Carlo Simulation & Regression Valuation+ *+ * Tools: Monte Carlo simulation for probability distributions, Regression-based valuation+ */++import React, { useState } from 'react';+import { Activity, PlayCircle, Loader2, TrendingUp, BarChart3, Target, Percent, Plus, Trash2 } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService } from '@/services/maAnalyticsService';+import { showSuccess, showError } from '@/utils/notifications';++type AnalysisType = 'montecarlo' | 'regression';++interface CompanyData {+ name: string;+ ev: number;+ revenue: number;+ ebitda: number;+ growth: number;+}++const DEFAULT_COMPS: CompanyData[] = [+ { name: 'Comp A', ev: 5000, revenue: 1200, ebitda: 350, growth: 15 },+ { name: 'Comp B', ev: 3200, revenue: 850, ebitda: 220, growth: 12 },+ { name: 'Comp C', ev: 7500, revenue: 1800, ebitda: 520, growth: 18 },+ { name: 'Comp D', ev: 4100, revenue: 950, ebitda: 280, growth: 10 },+];++export const AdvancedAnalytics: React.FC = () => {+ const [analysisType, setAnalysisType] = useState<AnalysisType>('montecarlo');+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<any>(null);++ // Monte Carlo inputs+ const [mcInputs, setMcInputs] = useState({+ baseValuation: 1000,+ revenueGrowthMean: 15,+ revenueGrowthStd: 5,+ marginMean: 25,+ marginStd: 3,+ discountRate: 10,+ simulations: 10000,+ });++ // Regression inputs+ const [regressionType, setRegressionType] = useState<'ols' | 'multiple'>('ols');+ const [compData, setCompData] = useState<CompanyData[]>(DEFAULT_COMPS);+ const [subjectMetrics, setSubjectMetrics] = useState({+ revenue: 1000,+ ebitda: 300,+ growth: 14,+ });++ const runAnalysis = async () => {+ setLoading(true);+ setResult(null);+ try {+ let data;+ if (analysisType === 'montecarlo') {+ data = await MAAnalyticsService.AdvancedAnalytics.runMonteCarloValuation(+ mcInputs.baseValuation,+ mcInputs.revenueGrowthMean,+ mcInputs.revenueGrowthStd,+ mcInputs.marginMean,+ mcInputs.marginStd,+ mcInputs.discountRate,+ mcInputs.simulations+ );+ } else {+ data = await MAAnalyticsService.AdvancedAnalytics.runRegressionValuation(+ compData,+ subjectMetrics,+ regressionType+ );+ }+ setResult(data);+ showSuccess(`${analysisType === 'montecarlo' ? 'Monte Carlo' : 'Regression'} analysis completed`);+ } catch (error) {+ showError(`Analysis failed: ${error}`);+ } finally {+ setLoading(false);+ }+ };++ const addComp = () => {+ setCompData([...compData, { name: `Comp ${String.fromCharCode(65 + compData.length)}`, ev: 0, revenue: 0, ebitda: 0, growth: 0 }]);+ };++ const removeComp = (idx: number) => {+ setCompData(compData.filter((_, i) => i !== idx));+ };++ const updateComp = (idx: number, field: keyof CompanyData, value: string | number) => {+ const updated = [...compData];+ updated[idx] = { ...updated[idx], [field]: field === 'name' ? value : parseFloat(String(value)) || 0 };+ setCompData(updated);+ };++ const renderMonteCarloInputs = () => (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Base Valuation ($M)</label>+ <input+ type="number"+ value={mcInputs.baseValuation}+ onChange={e => setMcInputs({ ...mcInputs, baseValuation: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.CHARCOAL }}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Discount Rate (%)</label>+ <input+ type="number"+ value={mcInputs.discountRate}+ onChange={e => setMcInputs({ ...mcInputs, discountRate: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.CHARCOAL }}+ />+ </div>+ </div>++ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Revenue Growth Distribution</h4>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Mean (%)</label>+ <input+ type="number"+ value={mcInputs.revenueGrowthMean}+ onChange={e => setMcInputs({ ...mcInputs, revenueGrowthMean: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Std Dev (%)</label>+ <input+ type="number"+ value={mcInputs.revenueGrowthStd}+ onChange={e => setMcInputs({ ...mcInputs, revenueGrowthStd: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ </div>+ </div>++ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Margin Distribution</h4>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Mean (%)</label>+ <input+ type="number"+ value={mcInputs.marginMean}+ onChange={e => setMcInputs({ ...mcInputs, marginMean: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Std Dev (%)</label>+ <input+ type="number"+ value={mcInputs.marginStd}+ onChange={e => setMcInputs({ ...mcInputs, marginStd: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ </div>+ </div>++ <div>+ <label className="text-xs text-gray-400 mb-1 block">Number of Simulations</label>+ <select+ value={mcInputs.simulations}+ onChange={e => setMcInputs({ ...mcInputs, simulations: parseInt(e.target.value) })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.CHARCOAL }}+ >+ <option value={1000}>1,000</option>+ <option value={5000}>5,000</option>+ <option value={10000}>10,000</option>+ <option value={50000}>50,000</option>+ <option value={100000}>100,000</option>+ </select>+ </div>+ </div>+ );++ const renderRegressionInputs = () => (+ <div className="space-y-4">+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Regression Type</label>+ <div className="flex gap-2">+ <button+ onClick={() => setRegressionType('ols')}+ className={`flex-1 px-3 py-2 rounded text-xs font-medium transition-all ${+ regressionType === 'ols' ? 'text-white' : 'text-gray-400'+ }`}+ style={{ backgroundColor: regressionType === 'ols' ? FINCEPT.ORANGE + '30' : FINCEPT.CHARCOAL }}+ >+ OLS (Simple)+ </button>+ <button+ onClick={() => setRegressionType('multiple')}+ className={`flex-1 px-3 py-2 rounded text-xs font-medium transition-all ${+ regressionType === 'multiple' ? 'text-white' : 'text-gray-400'+ }`}+ style={{ backgroundColor: regressionType === 'multiple' ? FINCEPT.ORANGE + '30' : FINCEPT.CHARCOAL }}+ >+ Multiple Regression+ </button>+ </div>+ </div>++ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="flex items-center justify-between mb-3">+ <h4 className="text-xs font-medium text-white">Comparable Companies</h4>+ <button+ onClick={addComp}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs"+ style={{ backgroundColor: FINCEPT.ORANGE + '20', color: FINCEPT.ORANGE }}+ >+ <Plus size={12} /> Add+ </button>+ </div>+ <div className="space-y-2 max-h-48 overflow-y-auto">+ {compData.map((comp, idx) => (+ <div key={idx} className="grid grid-cols-6 gap-2 items-center">+ <input+ type="text"+ value={comp.name}+ onChange={e => updateComp(idx, 'name', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ placeholder="Name"+ />+ <input+ type="number"+ value={comp.ev}+ onChange={e => updateComp(idx, 'ev', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ placeholder="EV"+ />+ <input+ type="number"+ value={comp.revenue}+ onChange={e => updateComp(idx, 'revenue', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ placeholder="Revenue"+ />+ <input+ type="number"+ value={comp.ebitda}+ onChange={e => updateComp(idx, 'ebitda', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ placeholder="EBITDA"+ />+ <input+ type="number"+ value={comp.growth}+ onChange={e => updateComp(idx, 'growth', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ placeholder="Growth %"+ />+ <button+ onClick={() => removeComp(idx)}+ className="p-1 rounded hover:bg-red-500/20"+ disabled={compData.length <= 2}+ >+ <Trash2 size={12} className={compData.length <= 2 ? 'text-gray-600' : 'text-red-400'} />+ </button>+ </div>+ ))}+ </div>+ <div className="mt-2 grid grid-cols-6 gap-2 text-xs text-gray-500">+ <span>Name</span>+ <span>EV ($M)</span>+ <span>Rev ($M)</span>+ <span>EBITDA</span>+ <span>Growth %</span>+ <span></span>+ </div>+ </div>++ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Subject Company Metrics</h4>+ <div className="grid grid-cols-3 gap-3">+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Revenue ($M)</label>+ <input+ type="number"+ value={subjectMetrics.revenue}+ onChange={e => setSubjectMetrics({ ...subjectMetrics, revenue: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">EBITDA ($M)</label>+ <input+ type="number"+ value={subjectMetrics.ebitda}+ onChange={e => setSubjectMetrics({ ...subjectMetrics, ebitda: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ <div>+ <label className="text-xs text-gray-400 mb-1 block">Growth (%)</label>+ <input+ type="number"+ value={subjectMetrics.growth}+ onChange={e => setSubjectMetrics({ ...subjectMetrics, growth: parseFloat(e.target.value) || 0 })}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ </div>+ </div>+ </div>+ </div>+ );++ const renderMonteCarloResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Key Statistics */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">Mean Valuation</div>+ <div className="text-lg font-bold text-white">${(result.mean || 0).toFixed(0)}M</div>+ </div>+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">Median Valuation</div>+ <div className="text-lg font-bold text-white">${(result.median || 0).toFixed(0)}M</div>+ </div>+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">Std Deviation</div>+ <div className="text-lg font-bold text-white">${(result.std || 0).toFixed(0)}M</div>+ </div>+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">CV</div>+ <div className="text-lg font-bold text-white">{((result.std / result.mean) * 100 || 0).toFixed(1)}%</div>+ </div>+ </div>++ {/* Percentiles */}+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Valuation Distribution</h4>+ <div className="space-y-2">+ {[+ { label: '5th Percentile', key: 'p5', color: '#ef4444' },+ { label: '25th Percentile', key: 'p25', color: '#f97316' },+ { label: '50th Percentile (Median)', key: 'median', color: FINCEPT.ORANGE },+ { label: '75th Percentile', key: 'p75', color: '#22c55e' },+ { label: '95th Percentile', key: 'p95', color: '#10b981' },+ ].map(item => (+ <div key={item.key} className="flex items-center justify-between">+ <span className="text-xs text-gray-400">{item.label}</span>+ <div className="flex items-center gap-2">+ <div className="w-24 h-2 rounded-full overflow-hidden" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div+ className="h-full rounded-full"+ style={{+ backgroundColor: item.color,+ width: `${Math.min(100, ((result[item.key] || 0) / (result.p95 || 1)) * 100)}%`,+ }}+ />+ </div>+ <span className="text-sm font-medium text-white w-20 text-right">+ ${(result[item.key] || 0).toFixed(0)}M+ </span>+ </div>+ </div>+ ))}+ </div>+ </div>++ {/* Range */}+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-2">90% Confidence Interval</h4>+ <div className="flex items-center justify-center gap-4">+ <span className="text-lg font-medium" style={{ color: FINCEPT.ORANGE }}>+ ${(result.p5 || 0).toFixed(0)}M+ </span>+ <span className="text-gray-500">—</span>+ <span className="text-lg font-medium" style={{ color: FINCEPT.ORANGE }}>+ ${(result.p95 || 0).toFixed(0)}M+ </span>+ </div>+ </div>+ </div>+ );+ };++ const renderRegressionResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Implied Valuation */}+ <div className="p-4 rounded text-center" style={{ backgroundColor: FINCEPT.ORANGE + '20' }}>+ <div className="text-xs text-gray-400 mb-1">Implied Enterprise Value</div>+ <div className="text-3xl font-bold" style={{ color: FINCEPT.ORANGE }}>+ ${(result.implied_ev || 0).toFixed(0)}M+ </div>+ </div>++ {/* Regression Stats */}+ <div className="grid grid-cols-2 gap-3">+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">R-Squared</div>+ <div className="text-lg font-bold text-white">{((result.r_squared || 0) * 100).toFixed(1)}%</div>+ </div>+ <div className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">Adj. R-Squared</div>+ <div className="text-lg font-bold text-white">{((result.adj_r_squared || 0) * 100).toFixed(1)}%</div>+ </div>+ </div>++ {/* Coefficients */}+ {result.coefficients && (+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Regression Coefficients</h4>+ <div className="space-y-2">+ {Object.entries(result.coefficients).map(([key, value]) => (+ <div key={key} className="flex items-center justify-between">+ <span className="text-xs text-gray-400">{key.replace(/_/g, ' ')}</span>+ <span className="text-sm font-medium text-white">{(value as number).toFixed(4)}</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Implied Multiples */}+ {result.implied_multiples && (+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Implied Multiples</h4>+ <div className="grid grid-cols-2 gap-3">+ {Object.entries(result.implied_multiples).map(([key, value]) => (+ <div key={key} className="flex items-center justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <span className="text-xs text-gray-400">{key.toUpperCase()}</span>+ <span className="text-sm font-bold" style={{ color: FINCEPT.ORANGE }}>{(value as number).toFixed(1)}x</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+ };++ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ {/* Header */}+ <div className="flex items-center justify-between p-4 border-b" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <div className="flex items-center gap-3">+ <div className="p-2 rounded-lg" style={{ backgroundColor: FINCEPT.ORANGE + '20' }}>+ <Activity size={20} style={{ color: FINCEPT.ORANGE }} />+ </div>+ <div>+ <h2 className={TYPOGRAPHY.HEADING}>Advanced Analytics</h2>+ <p className="text-xs text-gray-400">Monte Carlo simulation and regression-based valuation</p>+ </div>+ </div>+ <button+ onClick={runAnalysis}+ disabled={loading}+ className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-90 disabled:opacity-50"+ style={{ backgroundColor: FINCEPT.ORANGE, color: '#000' }}+ >+ {loading ? <Loader2 size={16} className="animate-spin" /> : <PlayCircle size={16} />}+ Run Analysis+ </button>+ </div>++ {/* Analysis Type Tabs */}+ <div className="flex items-center gap-2 px-4 py-2 border-b" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <button+ onClick={() => { setAnalysisType('montecarlo'); setResult(null); }}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${+ analysisType === 'montecarlo' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'montecarlo' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <Target size={16} /> Monte Carlo+ </button>+ <button+ onClick={() => { setAnalysisType('regression'); setResult(null); }}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${+ analysisType === 'regression' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'regression' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <TrendingUp size={16} /> Regression+ </button>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-auto p-4">+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ {/* Input Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">+ {analysisType === 'montecarlo' ? 'Monte Carlo Parameters' : 'Regression Inputs'}+ </h3>+ {analysisType === 'montecarlo' ? renderMonteCarloInputs() : renderRegressionInputs()}+ </div>++ {/* Results Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">Analysis Results</h3>+ {loading ? (+ <div className="flex items-center justify-center h-48">+ <Loader2 size={24} className="animate-spin" style={{ color: FINCEPT.ORANGE }} />+ </div>+ ) : result ? (+ analysisType === 'montecarlo' ? renderMonteCarloResults() : renderRegressionResults()+ ) : (+ <div className="flex flex-col items-center justify-center h-48 text-gray-500 text-sm">+ <Activity size={32} className="mb-2 opacity-50" />+ <p>Click "Run Analysis" to start</p>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++export default AdvancedAnalytics;diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealComparison.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealComparison.tsxnew file mode 100644index 000000000..a49e979be--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealComparison.tsx@@ -0,0 +1,771 @@+/**+ * Deal Comparison Panel - Compare, Rank, and Benchmark M&A Deals+ *+ * Tools: Side-by-side comparison, deal ranking, premium benchmarking, payment structure analysis, industry analysis+ */++import React, { useState, useEffect } from 'react';+import { GitCompare, PlayCircle, Loader2, TrendingUp, BarChart3, Award, CreditCard, Building2, Plus, Trash2, RefreshCw } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService, MADeal } from '@/services/maAnalyticsService';+import { showSuccess, showError } from '@/utils/notifications';++type AnalysisType = 'compare' | 'rank' | 'benchmark' | 'payment' | 'industry';++type RankCriteria = 'premium' | 'deal_value' | 'ev_revenue' | 'ev_ebitda' | 'synergies';++// Extended deal type for local comparison (superset of MADeal)+interface ComparisonDeal {+ deal_id: string;+ acquirer_name: string;+ target_name: string;+ deal_value: number;+ announced_date: string;+ status: string;+ premium_1day: number;+ ev_revenue?: number;+ ev_ebitda?: number;+ synergies?: number;+ payment_cash_pct: number;+ payment_stock_pct: number;+ industry: string;+}++const DEFAULT_DEALS: ComparisonDeal[] = [+ {+ deal_id: '1',+ acquirer_name: 'TechCorp Inc',+ target_name: 'StartupA',+ deal_value: 2500,+ announced_date: '2024-01-15',+ status: 'completed',+ premium_1day: 35,+ ev_revenue: 8.5,+ ev_ebitda: 18.2,+ synergies: 150,+ payment_cash_pct: 100,+ payment_stock_pct: 0,+ industry: 'Technology',+ },+ {+ deal_id: '2',+ acquirer_name: 'MegaCorp',+ target_name: 'GrowthCo',+ deal_value: 4200,+ announced_date: '2024-02-20',+ status: 'completed',+ premium_1day: 28,+ ev_revenue: 6.2,+ ev_ebitda: 14.5,+ synergies: 280,+ payment_cash_pct: 50,+ payment_stock_pct: 50,+ industry: 'Technology',+ },+ {+ deal_id: '3',+ acquirer_name: 'GlobalTech',+ target_name: 'InnovateCo',+ deal_value: 1800,+ announced_date: '2024-03-10',+ status: 'pending',+ premium_1day: 42,+ ev_revenue: 10.1,+ ev_ebitda: 22.0,+ synergies: 95,+ payment_cash_pct: 0,+ payment_stock_pct: 100,+ industry: 'Healthcare',+ },+];++const RANK_CRITERIA_OPTIONS: { value: RankCriteria; label: string; desc: string }[] = [+ { value: 'premium', label: 'Premium Paid', desc: 'Rank by 1-day premium to target shareholders' },+ { value: 'deal_value', label: 'Deal Value', desc: 'Rank by total transaction value' },+ { value: 'ev_revenue', label: 'EV/Revenue', desc: 'Rank by enterprise value to revenue multiple' },+ { value: 'ev_ebitda', label: 'EV/EBITDA', desc: 'Rank by enterprise value to EBITDA multiple' },+ { value: 'synergies', label: 'Synergies', desc: 'Rank by estimated synergy value' },+];++export const DealComparison: React.FC = () => {+ const [analysisType, setAnalysisType] = useState<AnalysisType>('compare');+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<any>(null);+ const [deals, setDeals] = useState<ComparisonDeal[]>(DEFAULT_DEALS);+ const [rankCriteria, setRankCriteria] = useState<RankCriteria>('premium');+ const [targetDealIdx, setTargetDealIdx] = useState(0);+ const [dbDeals, setDbDeals] = useState<MADeal[]>([]);+ const [loadingDb, setLoadingDb] = useState(false);++ // Load deals from database+ const loadFromDatabase = async () => {+ setLoadingDb(true);+ try {+ const data = await MAAnalyticsService.DealDatabase.getAllDeals();+ if (data && data.length > 0) {+ setDbDeals(data);+ showSuccess(`Loaded ${data.length} deals from database`);+ } else {+ showError('No deals found in database. Add deals manually or scan SEC filings.');+ }+ } catch (error) {+ showError(`Failed to load deals: ${error}`);+ } finally {+ setLoadingDb(false);+ }+ };++ const runAnalysis = async () => {+ if (deals.length < 2) {+ showError('Add at least 2 deals to compare');+ return;+ }++ setLoading(true);+ setResult(null);+ try {+ let data;+ const dealData = deals as MADeal[];++ switch (analysisType) {+ case 'compare':+ data = await MAAnalyticsService.DealComparison.compareDeals(dealData);+ break;+ case 'rank':+ data = await MAAnalyticsService.DealComparison.rankDeals(dealData, rankCriteria);+ break;+ case 'benchmark':+ const targetDeal = dealData[targetDealIdx];+ const comparables = dealData.filter((_, i) => i !== targetDealIdx);+ data = await MAAnalyticsService.DealComparison.benchmarkDealPremium(targetDeal, comparables);+ break;+ case 'payment':+ data = await MAAnalyticsService.DealComparison.analyzePaymentStructures(dealData);+ break;+ case 'industry':+ data = await MAAnalyticsService.DealComparison.analyzeIndustryDeals(dealData);+ break;+ }++ setResult(data);+ showSuccess('Analysis completed');+ } catch (error) {+ showError(`Analysis failed: ${error}`);+ } finally {+ setLoading(false);+ }+ };++ const addDeal = () => {+ setDeals([+ ...deals,+ {+ deal_id: String(Date.now()),+ acquirer_name: '',+ target_name: '',+ deal_value: 0,+ announced_date: new Date().toISOString().split('T')[0],+ status: 'pending',+ premium_1day: 0,+ ev_revenue: 0,+ ev_ebitda: 0,+ synergies: 0,+ payment_cash_pct: 100,+ payment_stock_pct: 0,+ industry: 'Technology',+ },+ ]);+ };++ const removeDeal = (idx: number) => {+ if (deals.length <= 2) return;+ setDeals(deals.filter((_, i) => i !== idx));+ if (targetDealIdx >= deals.length - 1) {+ setTargetDealIdx(Math.max(0, deals.length - 2));+ }+ };++ const updateDeal = (idx: number, field: keyof ComparisonDeal, value: any) => {+ const updated = [...deals];+ updated[idx] = { ...updated[idx], [field]: value };+ setDeals(updated);+ };++ const importFromDb = (dbDeal: MADeal) => {+ // Convert MADeal to ComparisonDeal+ const converted: ComparisonDeal = {+ deal_id: dbDeal.deal_id,+ acquirer_name: dbDeal.acquirer_name,+ target_name: dbDeal.target_name,+ deal_value: dbDeal.deal_value,+ announced_date: dbDeal.announced_date,+ status: dbDeal.status,+ premium_1day: dbDeal.premium_1day,+ ev_revenue: dbDeal.ev_revenue,+ ev_ebitda: dbDeal.ev_ebitda,+ synergies: dbDeal.synergies,+ payment_cash_pct: dbDeal.payment_cash_pct,+ payment_stock_pct: dbDeal.payment_stock_pct,+ industry: dbDeal.industry,+ };+ setDeals([...deals, converted]);+ };++ const renderDealInputs = () => (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <h4 className="text-sm font-medium text-white">Deals ({deals.length})</h4>+ <div className="flex gap-2">+ <button+ onClick={loadFromDatabase}+ disabled={loadingDb}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs"+ style={{ backgroundColor: FINCEPT.CHARCOAL, color: FINCEPT.ORANGE }}+ >+ {loadingDb ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ Load from DB+ </button>+ <button+ onClick={addDeal}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs"+ style={{ backgroundColor: FINCEPT.ORANGE + '20', color: FINCEPT.ORANGE }}+ >+ <Plus size={12} /> Add Deal+ </button>+ </div>+ </div>++ {/* Database deals quick import */}+ {dbDeals.length > 0 && (+ <div className="p-2 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400 mb-2">Quick Import from Database:</div>+ <div className="flex flex-wrap gap-1">+ {dbDeals.slice(0, 5).map(d => (+ <button+ key={d.deal_id}+ onClick={() => importFromDb(d)}+ className="px-2 py-1 rounded text-xs hover:opacity-80"+ style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}+ >+ {d.target_name}+ </button>+ ))}+ {dbDeals.length > 5 && (+ <span className="text-xs text-gray-500 px-2 py-1">+{dbDeals.length - 5} more</span>+ )}+ </div>+ </div>+ )}++ {/* Deal list */}+ <div className="space-y-3 max-h-96 overflow-y-auto">+ {deals.map((deal, idx) => (+ <div key={deal.deal_id} className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-white">Deal #{idx + 1}</span>+ <button+ onClick={() => removeDeal(idx)}+ disabled={deals.length <= 2}+ className="p-1 rounded hover:bg-red-500/20"+ >+ <Trash2 size={12} className={deals.length <= 2 ? 'text-gray-600' : 'text-red-400'} />+ </button>+ </div>+ <div className="grid grid-cols-2 gap-2">+ <input+ type="text"+ value={deal.acquirer_name || ''}+ onChange={e => updateDeal(idx, 'acquirer_name', e.target.value)}+ placeholder="Acquirer"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="text"+ value={deal.target_name || ''}+ onChange={e => updateDeal(idx, 'target_name', e.target.value)}+ placeholder="Target"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="number"+ value={deal.deal_value || 0}+ onChange={e => updateDeal(idx, 'deal_value', parseFloat(e.target.value) || 0)}+ placeholder="Value ($M)"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="number"+ value={deal.premium_1day || 0}+ onChange={e => updateDeal(idx, 'premium_1day', parseFloat(e.target.value) || 0)}+ placeholder="Premium %"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="number"+ value={deal.ev_revenue || 0}+ onChange={e => updateDeal(idx, 'ev_revenue', parseFloat(e.target.value) || 0)}+ placeholder="EV/Rev"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="number"+ value={deal.ev_ebitda || 0}+ onChange={e => updateDeal(idx, 'ev_ebitda', parseFloat(e.target.value) || 0)}+ placeholder="EV/EBITDA"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <input+ type="number"+ value={deal.payment_cash_pct || 0}+ onChange={e => {+ const cashPct = parseFloat(e.target.value) || 0;+ updateDeal(idx, 'payment_cash_pct', cashPct);+ updateDeal(idx, 'payment_stock_pct', 100 - cashPct);+ }}+ placeholder="Cash %"+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ />+ <select+ value={deal.industry || 'Technology'}+ onChange={e => updateDeal(idx, 'industry', e.target.value)}+ className="px-2 py-1 rounded text-xs text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ >+ <option value="Technology">Technology</option>+ <option value="Healthcare">Healthcare</option>+ <option value="Financial Services">Financial Services</option>+ <option value="Consumer">Consumer</option>+ <option value="Industrial">Industrial</option>+ <option value="Energy">Energy</option>+ </select>+ </div>+ </div>+ ))}+ </div>++ {/* Analysis-specific options */}+ {analysisType === 'rank' && (+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <label className="text-xs text-gray-400 mb-2 block">Ranking Criteria</label>+ <div className="space-y-1">+ {RANK_CRITERIA_OPTIONS.map(opt => (+ <button+ key={opt.value}+ onClick={() => setRankCriteria(opt.value)}+ className={`w-full text-left px-3 py-2 rounded text-xs transition-all ${+ rankCriteria === opt.value ? 'text-white' : 'text-gray-400'+ }`}+ style={{ backgroundColor: rankCriteria === opt.value ? FINCEPT.ORANGE + '30' : FINCEPT.PANEL_BG }}+ >+ <div className="font-medium">{opt.label}</div>+ <div className="text-xs opacity-70">{opt.desc}</div>+ </button>+ ))}+ </div>+ </div>+ )}++ {analysisType === 'benchmark' && (+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <label className="text-xs text-gray-400 mb-2 block">Target Deal to Benchmark</label>+ <select+ value={targetDealIdx}+ onChange={e => setTargetDealIdx(parseInt(e.target.value))}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.PANEL_BG }}+ >+ {deals.map((d, i) => (+ <option key={i} value={i}>+ {d.target_name || `Deal #${i + 1}`}+ </option>+ ))}+ </select>+ </div>+ )}+ </div>+ );++ const renderCompareResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Comparison Table */}+ {result.comparison && (+ <div className="overflow-x-auto">+ <table className="w-full text-xs">+ <thead>+ <tr style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <th className="text-left p-2 text-gray-400">Metric</th>+ {deals.map((d, i) => (+ <th key={i} className="text-right p-2 text-gray-400">{d.target_name || `Deal ${i + 1}`}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {Object.entries(result.comparison).map(([metric, values]: [string, any]) => (+ <tr key={metric} className="border-t" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <td className="p-2 text-gray-300">{metric.replace(/_/g, ' ')}</td>+ {(values as any[]).map((v, i) => (+ <td key={i} className="p-2 text-right text-white font-medium">+ {typeof v === 'number' ? v.toFixed(2) : v}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ {/* Summary Stats */}+ {result.summary && (+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {Object.entries(result.summary).map(([key, value]) => (+ <div key={key} className="p-3 rounded text-center" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">{key.replace(/_/g, ' ')}</div>+ <div className="text-lg font-bold text-white">+ {typeof value === 'number' ? value.toFixed(1) : String(value)}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+ };++ const renderRankResults = () => {+ if (!result || !result.rankings) return null;++ return (+ <div className="space-y-4">+ <div className="text-xs text-gray-400 mb-2">+ Ranked by: <span style={{ color: FINCEPT.ORANGE }}>{RANK_CRITERIA_OPTIONS.find(o => o.value === rankCriteria)?.label}</span>+ </div>+ {result.rankings.map((deal: any, idx: number) => (+ <div+ key={idx}+ className="flex items-center gap-3 p-3 rounded"+ style={{ backgroundColor: FINCEPT.CHARCOAL }}+ >+ <div+ className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold"+ style={{+ backgroundColor: idx === 0 ? '#FFD700' : idx === 1 ? '#C0C0C0' : idx === 2 ? '#CD7F32' : FINCEPT.PANEL_BG,+ color: idx < 3 ? '#000' : '#fff',+ }}+ >+ {idx + 1}+ </div>+ <div className="flex-1">+ <div className="text-sm font-medium text-white">{deal.target_name}</div>+ <div className="text-xs text-gray-400">Acquired by {deal.acquirer_name}</div>+ </div>+ <div className="text-right">+ <div className="text-lg font-bold" style={{ color: FINCEPT.ORANGE }}>+ {rankCriteria === 'premium' && `${deal.premium_1day?.toFixed(1)}%`}+ {rankCriteria === 'deal_value' && `$${deal.deal_value?.toFixed(0)}M`}+ {rankCriteria === 'ev_revenue' && `${deal.ev_revenue?.toFixed(1)}x`}+ {rankCriteria === 'ev_ebitda' && `${deal.ev_ebitda?.toFixed(1)}x`}+ {rankCriteria === 'synergies' && `$${deal.synergy_value?.toFixed(0)}M`}+ </div>+ </div>+ </div>+ ))}+ </div>+ );+ };++ const renderBenchmarkResults = () => {+ if (!result) return null;++ const targetDeal = deals[targetDealIdx];++ return (+ <div className="space-y-4">+ {/* Target Deal Summary */}+ <div className="p-4 rounded text-center" style={{ backgroundColor: FINCEPT.ORANGE + '20' }}>+ <div className="text-xs text-gray-400 mb-1">Benchmarking</div>+ <div className="text-xl font-bold" style={{ color: FINCEPT.ORANGE }}>+ {targetDeal?.target_name}+ </div>+ </div>++ {/* Premium Comparison */}+ {result.premium_comparison && (+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Premium vs Comparables</h4>+ <div className="grid grid-cols-3 gap-3">+ <div className="text-center p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Target Premium</div>+ <div className="text-lg font-bold text-white">{result.premium_comparison.target?.toFixed(1)}%</div>+ </div>+ <div className="text-center p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Median Premium</div>+ <div className="text-lg font-bold text-white">{result.premium_comparison.median?.toFixed(1)}%</div>+ </div>+ <div className="text-center p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Percentile</div>+ <div className="text-lg font-bold" style={{ color: FINCEPT.ORANGE }}>+ {result.premium_comparison.percentile?.toFixed(0)}%+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Insight */}+ {result.insight && (+ <div className="p-3 rounded text-sm text-gray-300" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ {result.insight}+ </div>+ )}+ </div>+ );+ };++ const renderPaymentResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Payment Type Distribution */}+ {result.distribution && (+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Payment Structure Distribution</h4>+ <div className="space-y-2">+ {Object.entries(result.distribution).map(([type, count]: [string, any]) => (+ <div key={type} className="flex items-center justify-between">+ <span className="text-xs text-gray-400">{type.replace(/_/g, ' ')}</span>+ <div className="flex items-center gap-2">+ <div className="w-24 h-2 rounded-full overflow-hidden" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div+ className="h-full rounded-full"+ style={{+ backgroundColor: FINCEPT.ORANGE,+ width: `${(count / deals.length) * 100}%`,+ }}+ />+ </div>+ <span className="text-sm font-medium text-white">{count}</span>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* By Payment Type Stats */}+ {result.stats_by_type && (+ <div className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <h4 className="text-xs font-medium text-white mb-3">Metrics by Payment Type</h4>+ <div className="space-y-3">+ {Object.entries(result.stats_by_type).map(([type, stats]: [string, any]) => (+ <div key={type} className="p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs font-medium text-white mb-2">{type.replace(/_/g, ' ')}</div>+ <div className="grid grid-cols-3 gap-2 text-xs">+ <div>+ <span className="text-gray-400">Avg Premium: </span>+ <span className="text-white">{stats.avg_premium?.toFixed(1)}%</span>+ </div>+ <div>+ <span className="text-gray-400">Avg Value: </span>+ <span className="text-white">${stats.avg_value?.toFixed(0)}M</span>+ </div>+ <div>+ <span className="text-gray-400">Count: </span>+ <span className="text-white">{stats.count}</span>+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+ };++ const renderIndustryResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Industry Distribution */}+ {result.by_industry && (+ <div className="space-y-3">+ {Object.entries(result.by_industry).map(([industry, data]: [string, any]) => (+ <div key={industry} className="p-4 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="flex items-center gap-2 mb-3">+ <Building2 size={14} style={{ color: FINCEPT.ORANGE }} />+ <h4 className="text-sm font-medium text-white">{industry}</h4>+ <span className="text-xs text-gray-400">({data.count} deals)</span>+ </div>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ <div className="p-2 rounded text-center" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Avg Premium</div>+ <div className="text-sm font-bold text-white">{data.avg_premium?.toFixed(1)}%</div>+ </div>+ <div className="p-2 rounded text-center" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Avg EV/Rev</div>+ <div className="text-sm font-bold text-white">{data.avg_ev_revenue?.toFixed(1)}x</div>+ </div>+ <div className="p-2 rounded text-center" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Avg EV/EBITDA</div>+ <div className="text-sm font-bold text-white">{data.avg_ev_ebitda?.toFixed(1)}x</div>+ </div>+ <div className="p-2 rounded text-center" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <div className="text-xs text-gray-400">Total Value</div>+ <div className="text-sm font-bold text-white">${data.total_value?.toFixed(0)}M</div>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+ };++ const renderResults = () => {+ if (loading) {+ return (+ <div className="flex items-center justify-center h-48">+ <Loader2 size={24} className="animate-spin" style={{ color: FINCEPT.ORANGE }} />+ </div>+ );+ }++ if (!result) {+ return (+ <div className="flex flex-col items-center justify-center h-48 text-gray-500 text-sm">+ <GitCompare size={32} className="mb-2 opacity-50" />+ <p>Add deals and run analysis</p>+ </div>+ );+ }++ switch (analysisType) {+ case 'compare':+ return renderCompareResults();+ case 'rank':+ return renderRankResults();+ case 'benchmark':+ return renderBenchmarkResults();+ case 'payment':+ return renderPaymentResults();+ case 'industry':+ return renderIndustryResults();+ default:+ return null;+ }+ };++ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ {/* Header */}+ <div className="flex items-center justify-between p-4 border-b" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <div className="flex items-center gap-3">+ <div className="p-2 rounded-lg" style={{ backgroundColor: FINCEPT.ORANGE + '20' }}>+ <GitCompare size={20} style={{ color: FINCEPT.ORANGE }} />+ </div>+ <div>+ <h2 className={TYPOGRAPHY.HEADING}>Deal Comparison</h2>+ <p className="text-xs text-gray-400">Compare, rank, and benchmark M&A transactions</p>+ </div>+ </div>+ <button+ onClick={runAnalysis}+ disabled={loading || deals.length < 2}+ className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-90 disabled:opacity-50"+ style={{ backgroundColor: FINCEPT.ORANGE, color: '#000' }}+ >+ {loading ? <Loader2 size={16} className="animate-spin" /> : <PlayCircle size={16} />}+ Analyze+ </button>+ </div>++ {/* Analysis Type Tabs */}+ <div className="flex items-center gap-1 px-4 py-2 border-b overflow-x-auto" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <button+ onClick={() => { setAnalysisType('compare'); setResult(null); }}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all whitespace-nowrap ${+ analysisType === 'compare' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'compare' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <GitCompare size={14} /> Compare+ </button>+ <button+ onClick={() => { setAnalysisType('rank'); setResult(null); }}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all whitespace-nowrap ${+ analysisType === 'rank' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'rank' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <Award size={14} /> Rank+ </button>+ <button+ onClick={() => { setAnalysisType('benchmark'); setResult(null); }}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all whitespace-nowrap ${+ analysisType === 'benchmark' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'benchmark' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <BarChart3 size={14} /> Benchmark+ </button>+ <button+ onClick={() => { setAnalysisType('payment'); setResult(null); }}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all whitespace-nowrap ${+ analysisType === 'payment' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'payment' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <CreditCard size={14} /> Payment+ </button>+ <button+ onClick={() => { setAnalysisType('industry'); setResult(null); }}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all whitespace-nowrap ${+ analysisType === 'industry' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: analysisType === 'industry' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <Building2 size={14} /> Industry+ </button>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-auto p-4">+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ {/* Input Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">Deal Data</h3>+ {renderDealInputs()}+ </div>++ {/* Results Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">+ {analysisType === 'compare' && 'Comparison Results'}+ {analysisType === 'rank' && 'Rankings'}+ {analysisType === 'benchmark' && 'Benchmark Results'}+ {analysisType === 'payment' && 'Payment Analysis'}+ {analysisType === 'industry' && 'Industry Analysis'}+ </h3>+ {renderResults()}+ </div>+ </div>+ </div>+ </div>+ );+};++export default DealComparison;diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/FairnessOpinion.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/FairnessOpinion.tsxnew file mode 100644index 000000000..954cdca11--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/FairnessOpinion.tsx@@ -0,0 +1,589 @@+/**+ * Fairness Opinion Panel - Board-Level M&A Analysis+ *+ * Tools: Valuation Framework, Premium Analysis, Process Quality Assessment+ */++import React, { useState } from 'react';+import { Scale, PlayCircle, Loader2, TrendingUp, CheckCircle, AlertTriangle, FileText } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService } from '@/services/maAnalyticsService';+import { showSuccess, showError } from '@/utils/notifications';++type AnalysisType = 'fairness' | 'premium' | 'process';++const QUALITATIVE_FACTORS = [+ 'Strategic rationale clearly articulated',+ 'Arm\'s length negotiation process',+ 'Board formed special committee',+ 'Independent financial advisor engaged',+ 'Adequate time for due diligence',+ 'No conflicts of interest identified',+ 'Market check or go-shop provision',+ 'Fiduciary out provisions included',+ 'Shareholder vote required',+ 'Material adverse change clause present',+];++const PROCESS_FACTORS = [+ { key: 'board_independence', label: 'Board Independence', desc: 'Independent directors led process' },+ { key: 'special_committee', label: 'Special Committee', desc: 'Formed to evaluate transaction' },+ { key: 'independent_advisor', label: 'Independent Advisor', desc: 'Engaged qualified financial advisor' },+ { key: 'market_check', label: 'Market Check', desc: 'Conducted auction or market check' },+ { key: 'negotiation_process', label: 'Negotiation Process', desc: 'Arm\'s length negotiations' },+ { key: 'due_diligence', label: 'Due Diligence', desc: 'Comprehensive review completed' },+ { key: 'disclosure', label: 'Disclosure Quality', desc: 'Full disclosure to shareholders' },+ { key: 'timing', label: 'Timing Adequacy', desc: 'Sufficient time for evaluation' },+];++export const FairnessOpinion: React.FC = () => {+ const [analysisType, setAnalysisType] = useState<AnalysisType>('fairness');+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<any>(null);++ // Fairness Opinion inputs+ const [fairnessInputs, setFairnessInputs] = useState({+ offerPrice: 50,+ valuationMethods: [+ { method: 'DCF', valuation: 45, range: { min: 40, max: 55 } },+ { method: 'Trading Comps', valuation: 48, range: { min: 42, max: 54 } },+ { method: 'Precedent Transactions', valuation: 52, range: { min: 46, max: 58 } },+ ],+ selectedFactors: new Set<string>(['Strategic rationale clearly articulated', 'Board formed special committee']),+ });++ // Premium Analysis inputs+ const [premiumInputs, setPremiumInputs] = useState({+ offerPrice: 50,+ dailyPrices: '42,43,44,43,45,44,46,45,47,46,48,47,49,48,50,49,51,50,52,51', // Last 20 days+ announcementDate: 15, // Day index+ });++ // Process Quality inputs+ const [processInputs, setProcessInputs] = useState<Record<string, number>>(+ Object.fromEntries(PROCESS_FACTORS.map(f => [f.key, 3])) // 1-5 scale+ );++ const formatCurrency = (value: number) => `$${value.toFixed(2)}`;++ const handleRunFairness = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.FairnessOpinion.generateFairnessOpinion({+ valuation_methods: fairnessInputs.valuationMethods.map(v => ({+ method: v.method,+ valuation: v.valuation,+ range: v.range,+ assumptions: {},+ })),+ offer_price: fairnessInputs.offerPrice,+ qualitative_factors: Array.from(fairnessInputs.selectedFactors),+ });+ setResult(res);+ showSuccess('Fairness Opinion Generated', [+ { label: 'CONCLUSION', value: res.is_fair ? 'FAIR' : 'NOT FAIR' }+ ]);+ } catch (error) {+ showError('Fairness opinion failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunPremium = async () => {+ setLoading(true);+ try {+ const prices = premiumInputs.dailyPrices.split(',').map(p => parseFloat(p.trim()));+ const res = await MAAnalyticsService.FairnessOpinion.analyzePremiumFairness(+ prices,+ premiumInputs.offerPrice,+ premiumInputs.announcementDate+ );+ setResult(res);+ showSuccess('Premium Analysis Complete', [+ { label: '1-DAY PREMIUM', value: `${res.premium_1day?.toFixed(1)}%` }+ ]);+ } catch (error) {+ showError('Premium analysis failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunProcess = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.FairnessOpinion.assessProcessQuality(processInputs);+ setResult(res);+ showSuccess('Process Assessment Complete', [+ { label: 'QUALITY SCORE', value: `${res.overall_score?.toFixed(1)}/5` }+ ]);+ } catch (error) {+ showError('Process assessment failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRun = () => {+ switch (analysisType) {+ case 'fairness': return handleRunFairness();+ case 'premium': return handleRunPremium();+ case 'process': return handleRunProcess();+ }+ };++ const toggleFactor = (factor: string) => {+ const newSet = new Set(fairnessInputs.selectedFactors);+ if (newSet.has(factor)) {+ newSet.delete(factor);+ } else {+ newSet.add(factor);+ }+ setFairnessInputs({ ...fairnessInputs, selectedFactors: newSet });+ };++ const renderInputs = () => {+ switch (analysisType) {+ case 'fairness':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Offer Price ($/share)</label>+ <input+ type="number"+ step="0.01"+ value={fairnessInputs.offerPrice}+ onChange={(e) => setFairnessInputs({ ...fairnessInputs, offerPrice: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginTop: SPACING.SMALL }}>+ VALUATION METHODS+ </div>+ {fairnessInputs.valuationMethods.map((method, idx) => (+ <div key={idx} style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.ORANGE, marginBottom: '4px' }}>+ {method.method}+ </div>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Value</label>+ <input+ type="number"+ step="0.01"+ value={method.valuation}+ onChange={(e) => {+ const updated = [...fairnessInputs.valuationMethods];+ updated[idx].valuation = Number(e.target.value);+ setFairnessInputs({ ...fairnessInputs, valuationMethods: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Min</label>+ <input+ type="number"+ step="0.01"+ value={method.range.min}+ onChange={(e) => {+ const updated = [...fairnessInputs.valuationMethods];+ updated[idx].range.min = Number(e.target.value);+ setFairnessInputs({ ...fairnessInputs, valuationMethods: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Max</label>+ <input+ type="number"+ step="0.01"+ value={method.range.max}+ onChange={(e) => {+ const updated = [...fairnessInputs.valuationMethods];+ updated[idx].range.max = Number(e.target.value);+ setFairnessInputs({ ...fairnessInputs, valuationMethods: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ </div>+ </div>+ ))}++ <div style={{ ...COMMON_STYLES.dataLabel, marginTop: SPACING.SMALL }}>+ QUALITATIVE FACTORS+ </div>+ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>+ {QUALITATIVE_FACTORS.map(factor => (+ <div+ key={factor}+ onClick={() => toggleFactor(factor)}+ style={{+ padding: '6px',+ marginBottom: '2px',+ backgroundColor: fairnessInputs.selectedFactors.has(factor) ? `${FINCEPT.GREEN}20` : FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${fairnessInputs.selectedFactors.has(factor) ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}+ >+ <CheckCircle+ size={12}+ color={fairnessInputs.selectedFactors.has(factor) ? FINCEPT.GREEN : FINCEPT.MUTED}+ />+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{factor}</span>+ </div>+ ))}+ </div>+ </div>+ );++ case 'premium':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Offer Price ($/share)</label>+ <input+ type="number"+ step="0.01"+ value={premiumInputs.offerPrice}+ onChange={(e) => setPremiumInputs({ ...premiumInputs, offerPrice: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>+ Daily Prices (comma-separated, most recent last)+ </label>+ <textarea+ value={premiumInputs.dailyPrices}+ onChange={(e) => setPremiumInputs({ ...premiumInputs, dailyPrices: e.target.value })}+ rows={4}+ style={{ ...COMMON_STYLES.inputField, width: '100%', resize: 'vertical' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>+ Announcement Date (day index, 0-based)+ </label>+ <input+ type="number"+ value={premiumInputs.announcementDate}+ onChange={(e) => setPremiumInputs({ ...premiumInputs, announcementDate: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div style={{+ padding: SPACING.SMALL,+ backgroundColor: `${FINCEPT.CYAN}15`,+ borderRadius: '4px',+ fontSize: TYPOGRAPHY.TINY,+ color: FINCEPT.CYAN,+ }}>+ Calculates premiums vs 1-day, 1-week, 1-month, and 52-week prices+ </div>+ </div>+ );++ case 'process':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div style={{ ...COMMON_STYLES.dataLabel }}>+ PROCESS QUALITY ASSESSMENT (1-5)+ </div>+ {PROCESS_FACTORS.map(factor => (+ <div key={factor.key} style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.WHITE }}>{factor.label}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{factor.desc}</div>+ </div>+ <select+ value={processInputs[factor.key]}+ onChange={(e) => setProcessInputs({ ...processInputs, [factor.key]: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '60px', fontSize: TYPOGRAPHY.TINY }}+ >+ <option value={1}>1 - Poor</option>+ <option value={2}>2</option>+ <option value={3}>3 - Average</option>+ <option value={4}>4</option>+ <option value={5}>5 - Excellent</option>+ </select>+ </div>+ </div>+ ))}+ </div>+ );+ }+ };++ const renderResults = () => {+ if (!result) {+ return (+ <div style={{ ...COMMON_STYLES.emptyState }}>+ <Scale size={32} style={{ opacity: 0.3, marginBottom: SPACING.SMALL }} />+ <span style={{ color: FINCEPT.GRAY }}>Run analysis to see results</span>+ </div>+ );+ }++ return (+ <div style={{ padding: SPACING.DEFAULT }}>+ {/* Fairness Opinion Result */}+ {result.is_fair !== undefined && (+ <>+ <div style={{+ padding: SPACING.DEFAULT,+ backgroundColor: result.is_fair ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,+ borderRadius: '4px',+ border: `2px solid ${result.is_fair ? FINCEPT.GREEN : FINCEPT.RED}`,+ textAlign: 'center',+ marginBottom: SPACING.DEFAULT,+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>FAIRNESS OPINION</div>+ <div style={{+ fontSize: '24px',+ color: result.is_fair ? FINCEPT.GREEN : FINCEPT.RED,+ fontWeight: TYPOGRAPHY.BOLD,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: SPACING.SMALL,+ }}>+ {result.is_fair ? <CheckCircle size={24} /> : <AlertTriangle size={24} />}+ {result.is_fair ? 'FAIR' : 'NOT FAIR'}+ </div>+ </div>++ {result.valuation_summary && (+ <div style={{ marginBottom: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>VALUATION SUMMARY</div>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>OFFER</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.ORANGE }}>+ {formatCurrency(result.offer_price || fairnessInputs.offerPrice)}+ </div>+ </div>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>AVG VALUATION</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.GREEN }}>+ {formatCurrency(result.valuation_summary.average || 0)}+ </div>+ </div>+ </div>+ </div>+ )}+ </>+ )}++ {/* Premium Analysis Result */}+ {result.premium_1day !== undefined && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>PREMIUM ANALYSIS</div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {[+ { label: '1-DAY', value: result.premium_1day },+ { label: '1-WEEK', value: result.premium_1week },+ { label: '1-MONTH', value: result.premium_1month },+ { label: '52-WEEK HIGH', value: result.premium_52week_high },+ ].map(item => (+ <div key={item.label} style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ textAlign: 'center',+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{item.label}</div>+ <div style={{+ fontSize: TYPOGRAPHY.HEADING,+ color: (item.value || 0) >= 0 ? FINCEPT.GREEN : FINCEPT.RED,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>+ {item.value !== undefined ? `${item.value.toFixed(1)}%` : 'N/A'}+ </div>+ </div>+ ))}+ </div>+ </>+ )}++ {/* Process Quality Result */}+ {result.overall_score !== undefined && (+ <>+ <div style={{+ padding: SPACING.DEFAULT,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.ORANGE}`,+ textAlign: 'center',+ marginBottom: SPACING.DEFAULT,+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>PROCESS QUALITY SCORE</div>+ <div style={{ fontSize: '32px', color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>+ {result.overall_score.toFixed(1)} / 5+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED }}>+ {result.overall_score >= 4 ? 'Strong Process' :+ result.overall_score >= 3 ? 'Adequate Process' : 'Process Concerns'}+ </div>+ </div>++ {result.factor_scores && (+ <div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>FACTOR BREAKDOWN</div>+ {Object.entries(result.factor_scores).map(([key, score]: [string, any]) => (+ <div key={key} style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ padding: '4px 0',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>+ {key.replace(/_/g, ' ').toUpperCase()}+ </span>+ <span style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: score >= 4 ? FINCEPT.GREEN : score >= 3 ? FINCEPT.ORANGE : FINCEPT.RED,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>+ {score}/5+ </span>+ </div>+ ))}+ </div>+ )}+ </>+ )}++ {/* Raw JSON */}+ <details style={{ marginTop: SPACING.DEFAULT }}>+ <summary style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, cursor: 'pointer' }}>+ Raw Output+ </summary>+ <pre style={{+ fontSize: '9px',+ color: FINCEPT.GRAY,+ backgroundColor: FINCEPT.PANEL_BG,+ padding: SPACING.SMALL,+ borderRadius: '4px',+ overflow: 'auto',+ maxHeight: '200px',+ }}>+ {JSON.stringify(result, null, 2)}+ </pre>+ </details>+ </div>+ );+ };++ return (+ <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>+ {/* LEFT - Analysis Type & Inputs */}+ <div style={{+ width: '380px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ {/* Analysis Type Tabs */}+ <div style={{+ display: 'flex',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ {[+ { id: 'fairness' as const, label: 'FAIRNESS OPINION', icon: Scale },+ { id: 'premium' as const, label: 'PREMIUM', icon: TrendingUp },+ { id: 'process' as const, label: 'PROCESS', icon: FileText },+ ].map(tab => (+ <button+ key={tab.id}+ onClick={() => { setAnalysisType(tab.id); setResult(null); }}+ style={{+ flex: 1,+ padding: SPACING.SMALL,+ backgroundColor: 'transparent',+ border: 'none',+ borderBottom: analysisType === tab.id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ color: analysisType === tab.id ? FINCEPT.ORANGE : FINCEPT.GRAY,+ cursor: 'pointer',+ fontSize: '9px',+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ }}+ >+ <tab.icon size={12} />+ {tab.label}+ </button>+ ))}+ </div>++ {/* Inputs */}+ <div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>+ {renderInputs()}+ </div>++ {/* Run Button */}+ <div style={{ padding: SPACING.DEFAULT, borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <button+ onClick={handleRun}+ disabled={loading}+ style={{+ width: '100%',+ padding: SPACING.SMALL,+ backgroundColor: loading ? FINCEPT.PANEL_BG : FINCEPT.ORANGE,+ border: 'none',+ borderRadius: '4px',+ color: loading ? FINCEPT.GRAY : FINCEPT.DARK_BG,+ cursor: loading ? 'not-allowed' : 'pointer',+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: SPACING.SMALL,+ }}+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : <PlayCircle size={14} />}+ {loading ? 'ANALYZING...' : 'RUN ANALYSIS'}+ </button>+ </div>+ </div>++ {/* RIGHT - Results */}+ <div style={{ flex: 1, overflow: 'auto', backgroundColor: FINCEPT.DARK_BG }}>+ {renderResults()}+ </div>+ </div>+ );+};diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/IndustryMetrics.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/IndustryMetrics.tsxnew file mode 100644index 000000000..b3ef72a94--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/IndustryMetrics.tsx@@ -0,0 +1,444 @@+/**+ * Industry Metrics Panel - Sector-Specific Valuation Metrics+ *+ * Sectors: Technology (SaaS, Marketplace, Semiconductor), Healthcare (Pharma, Biotech, Devices, Services),+ * Financial Services (Banking, Insurance, Asset Management)+ */++import React, { useState } from 'react';+import { Cpu, HeartPulse, Building2, PlayCircle, Loader2, TrendingUp, BarChart3 } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService } from '@/services/maAnalyticsService';+import { showSuccess, showError } from '@/utils/notifications';++type IndustryType = 'tech' | 'healthcare' | 'financial';++const TECH_SECTORS = [+ { value: 'saas', label: 'SaaS / Cloud', icon: '☁️' },+ { value: 'marketplace', label: 'Marketplace / Platform', icon: '🏪' },+ { value: 'semiconductor', label: 'Semiconductor', icon: '🔌' },+] as const;++const HEALTHCARE_SECTORS = [+ { value: 'pharma', label: 'Pharmaceuticals', icon: '💊' },+ { value: 'biotech', label: 'Biotechnology', icon: '🧬' },+ { value: 'devices', label: 'Medical Devices', icon: '🩺' },+ { value: 'services', label: 'Healthcare Services', icon: '🏥' },+] as const;++const FINANCIAL_SECTORS = [+ { value: 'banking', label: 'Banking', icon: '🏦' },+ { value: 'insurance', label: 'Insurance', icon: '🛡️' },+ { value: 'asset_management', label: 'Asset Management', icon: '📈' },+] as const;++const TECH_FIELDS = {+ saas: [+ { key: 'arr', label: 'Annual Recurring Revenue ($M)', type: 'number' },+ { key: 'arr_growth', label: 'ARR Growth Rate (%)', type: 'number' },+ { key: 'net_retention', label: 'Net Revenue Retention (%)', type: 'number' },+ { key: 'gross_margin', label: 'Gross Margin (%)', type: 'number' },+ { key: 'cac_payback', label: 'CAC Payback (months)', type: 'number' },+ { key: 'ltv_cac', label: 'LTV/CAC Ratio', type: 'number' },+ { key: 'rule_of_40', label: 'Rule of 40 Score', type: 'number' },+ ],+ marketplace: [+ { key: 'gmv', label: 'Gross Merchandise Value ($M)', type: 'number' },+ { key: 'take_rate', label: 'Take Rate (%)', type: 'number' },+ { key: 'gmv_growth', label: 'GMV Growth Rate (%)', type: 'number' },+ { key: 'active_buyers', label: 'Active Buyers (000s)', type: 'number' },+ { key: 'active_sellers', label: 'Active Sellers (000s)', type: 'number' },+ { key: 'repeat_rate', label: 'Repeat Purchase Rate (%)', type: 'number' },+ ],+ semiconductor: [+ { key: 'revenue', label: 'Revenue ($M)', type: 'number' },+ { key: 'revenue_growth', label: 'Revenue Growth (%)', type: 'number' },+ { key: 'gross_margin', label: 'Gross Margin (%)', type: 'number' },+ { key: 'r_and_d_intensity', label: 'R&D Intensity (%)', type: 'number' },+ { key: 'design_wins', label: 'Design Wins', type: 'number' },+ { key: 'book_to_bill', label: 'Book-to-Bill Ratio', type: 'number' },+ ],+};++const HEALTHCARE_FIELDS = {+ pharma: [+ { key: 'revenue', label: 'Revenue ($M)', type: 'number' },+ { key: 'pipeline_value', label: 'Pipeline NPV ($M)', type: 'number' },+ { key: 'phase3_count', label: 'Phase 3 Drug Candidates', type: 'number' },+ { key: 'patent_expiry_revenue', label: 'Revenue Facing Patent Expiry (%)', type: 'number' },+ { key: 'r_and_d_spend', label: 'R&D Spend ($M)', type: 'number' },+ { key: 'ebitda_margin', label: 'EBITDA Margin (%)', type: 'number' },+ ],+ biotech: [+ { key: 'cash_position', label: 'Cash Position ($M)', type: 'number' },+ { key: 'burn_rate', label: 'Monthly Burn Rate ($M)', type: 'number' },+ { key: 'pipeline_value', label: 'Pipeline NPV ($M)', type: 'number' },+ { key: 'lead_program_phase', label: 'Lead Program Phase (1-3)', type: 'number' },+ { key: 'platform_value', label: 'Platform Value ($M)', type: 'number' },+ { key: 'partnership_revenue', label: 'Partnership Revenue ($M)', type: 'number' },+ ],+ devices: [+ { key: 'revenue', label: 'Revenue ($M)', type: 'number' },+ { key: 'revenue_growth', label: 'Revenue Growth (%)', type: 'number' },+ { key: 'gross_margin', label: 'Gross Margin (%)', type: 'number' },+ { key: 'fda_clearances', label: 'FDA Clearances (past 2 yrs)', type: 'number' },+ { key: 'recurring_revenue_pct', label: 'Recurring Revenue (%)', type: 'number' },+ { key: 'international_revenue_pct', label: 'International Revenue (%)', type: 'number' },+ ],+ services: [+ { key: 'revenue', label: 'Revenue ($M)', type: 'number' },+ { key: 'organic_growth', label: 'Organic Growth (%)', type: 'number' },+ { key: 'ebitda_margin', label: 'EBITDA Margin (%)', type: 'number' },+ { key: 'patient_volume_growth', label: 'Patient Volume Growth (%)', type: 'number' },+ { key: 'payor_mix_commercial', label: 'Commercial Payor Mix (%)', type: 'number' },+ { key: 'same_store_growth', label: 'Same-Store Growth (%)', type: 'number' },+ ],+};++const FINANCIAL_FIELDS = {+ banking: [+ { key: 'total_assets', label: 'Total Assets ($M)', type: 'number' },+ { key: 'total_deposits', label: 'Total Deposits ($M)', type: 'number' },+ { key: 'net_interest_margin', label: 'Net Interest Margin (%)', type: 'number' },+ { key: 'efficiency_ratio', label: 'Efficiency Ratio (%)', type: 'number' },+ { key: 'roa', label: 'Return on Assets (%)', type: 'number' },+ { key: 'roe', label: 'Return on Equity (%)', type: 'number' },+ { key: 'cet1_ratio', label: 'CET1 Capital Ratio (%)', type: 'number' },+ { key: 'npl_ratio', label: 'NPL Ratio (%)', type: 'number' },+ ],+ insurance: [+ { key: 'gross_premiums', label: 'Gross Written Premiums ($M)', type: 'number' },+ { key: 'combined_ratio', label: 'Combined Ratio (%)', type: 'number' },+ { key: 'loss_ratio', label: 'Loss Ratio (%)', type: 'number' },+ { key: 'expense_ratio', label: 'Expense Ratio (%)', type: 'number' },+ { key: 'investment_yield', label: 'Investment Yield (%)', type: 'number' },+ { key: 'book_value', label: 'Book Value ($M)', type: 'number' },+ { key: 'roe', label: 'Return on Equity (%)', type: 'number' },+ ],+ asset_management: [+ { key: 'aum', label: 'Assets Under Management ($B)', type: 'number' },+ { key: 'net_flows', label: 'Net Flows ($B)', type: 'number' },+ { key: 'fee_rate', label: 'Average Fee Rate (bps)', type: 'number' },+ { key: 'operating_margin', label: 'Operating Margin (%)', type: 'number' },+ { key: 'active_vs_passive', label: 'Active AUM (%)', type: 'number' },+ { key: 'alpha_generation', label: 'Avg Alpha vs Benchmark (bps)', type: 'number' },+ ],+};++export const IndustryMetrics: React.FC = () => {+ const [industryType, setIndustryType] = useState<IndustryType>('tech');+ const [techSector, setTechSector] = useState<'saas' | 'marketplace' | 'semiconductor'>('saas');+ const [healthcareSector, setHealthcareSector] = useState<'pharma' | 'biotech' | 'devices' | 'services'>('pharma');+ const [financialSector, setFinancialSector] = useState<'banking' | 'insurance' | 'asset_management'>('banking');+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<any>(null);++ const [techInputs, setTechInputs] = useState<Record<string, Record<string, number>>>({+ saas: { arr: 100, arr_growth: 40, net_retention: 115, gross_margin: 75, cac_payback: 18, ltv_cac: 3.5, rule_of_40: 55 },+ marketplace: { gmv: 500, take_rate: 15, gmv_growth: 35, active_buyers: 150, active_sellers: 25, repeat_rate: 55 },+ semiconductor: { revenue: 200, revenue_growth: 20, gross_margin: 55, r_and_d_intensity: 18, design_wins: 12, book_to_bill: 1.15 },+ });++ const [healthcareInputs, setHealthcareInputs] = useState<Record<string, Record<string, number>>>({+ pharma: { revenue: 5000, pipeline_value: 3000, phase3_count: 5, patent_expiry_revenue: 25, r_and_d_spend: 800, ebitda_margin: 35 },+ biotech: { cash_position: 200, burn_rate: 15, pipeline_value: 800, lead_program_phase: 2, platform_value: 300, partnership_revenue: 25 },+ devices: { revenue: 300, revenue_growth: 12, gross_margin: 65, fda_clearances: 8, recurring_revenue_pct: 35, international_revenue_pct: 40 },+ services: { revenue: 800, organic_growth: 8, ebitda_margin: 18, patient_volume_growth: 5, payor_mix_commercial: 55, same_store_growth: 4 },+ });++ const [financialInputs, setFinancialInputs] = useState<Record<string, Record<string, number>>>({+ banking: { total_assets: 50000, total_deposits: 40000, net_interest_margin: 3.2, efficiency_ratio: 58, roa: 1.1, roe: 12, cet1_ratio: 12.5, npl_ratio: 0.8 },+ insurance: { gross_premiums: 2000, combined_ratio: 95, loss_ratio: 65, expense_ratio: 30, investment_yield: 4.5, book_value: 800, roe: 14 },+ asset_management: { aum: 150, net_flows: 8, fee_rate: 45, operating_margin: 35, active_vs_passive: 60, alpha_generation: 75 },+ });++ const runAnalysis = async () => {+ setLoading(true);+ setResult(null);+ try {+ let data;+ if (industryType === 'tech') {+ data = await MAAnalyticsService.IndustryMetrics.calculateTechMetrics(techSector, techInputs[techSector]);+ } else if (industryType === 'healthcare') {+ data = await MAAnalyticsService.IndustryMetrics.calculateHealthcareMetrics(healthcareSector, healthcareInputs[healthcareSector]);+ } else {+ data = await MAAnalyticsService.IndustryMetrics.calculateFinancialServicesMetrics(financialSector, financialInputs[financialSector]);+ }+ setResult(data);+ showSuccess('Industry metrics calculated successfully');+ } catch (error) {+ showError(`Failed to calculate metrics: ${error}`);+ } finally {+ setLoading(false);+ }+ };++ const getCurrentSector = () => {+ if (industryType === 'tech') return techSector;+ if (industryType === 'healthcare') return healthcareSector;+ return financialSector;+ };++ const getCurrentFields = () => {+ if (industryType === 'tech') return TECH_FIELDS[techSector];+ if (industryType === 'healthcare') return HEALTHCARE_FIELDS[healthcareSector];+ return FINANCIAL_FIELDS[financialSector];+ };++ const getCurrentInputs = () => {+ if (industryType === 'tech') return techInputs[techSector];+ if (industryType === 'healthcare') return healthcareInputs[healthcareSector];+ return financialInputs[financialSector];+ };++ const updateInput = (key: string, value: number) => {+ if (industryType === 'tech') {+ setTechInputs(prev => ({+ ...prev,+ [techSector]: { ...prev[techSector], [key]: value },+ }));+ } else if (industryType === 'healthcare') {+ setHealthcareInputs(prev => ({+ ...prev,+ [healthcareSector]: { ...prev[healthcareSector], [key]: value },+ }));+ } else {+ setFinancialInputs(prev => ({+ ...prev,+ [financialSector]: { ...prev[financialSector], [key]: value },+ }));+ }+ };++ const renderSectorTabs = () => {+ if (industryType === 'tech') {+ return TECH_SECTORS.map(s => (+ <button+ key={s.value}+ onClick={() => setTechSector(s.value as any)}+ className={`px-3 py-2 text-xs font-medium transition-all ${+ techSector === s.value+ ? 'text-white border-b-2'+ : 'text-gray-400 hover:text-white'+ }`}+ style={{ borderColor: techSector === s.value ? FINCEPT.ORANGE : 'transparent' }}+ >+ {s.icon} {s.label}+ </button>+ ));+ }+ if (industryType === 'healthcare') {+ return HEALTHCARE_SECTORS.map(s => (+ <button+ key={s.value}+ onClick={() => setHealthcareSector(s.value as any)}+ className={`px-3 py-2 text-xs font-medium transition-all ${+ healthcareSector === s.value+ ? 'text-white border-b-2'+ : 'text-gray-400 hover:text-white'+ }`}+ style={{ borderColor: healthcareSector === s.value ? FINCEPT.ORANGE : 'transparent' }}+ >+ {s.icon} {s.label}+ </button>+ ));+ }+ return FINANCIAL_SECTORS.map(s => (+ <button+ key={s.value}+ onClick={() => setFinancialSector(s.value as any)}+ className={`px-3 py-2 text-xs font-medium transition-all ${+ financialSector === s.value+ ? 'text-white border-b-2'+ : 'text-gray-400 hover:text-white'+ }`}+ style={{ borderColor: financialSector === s.value ? FINCEPT.ORANGE : 'transparent' }}+ >+ {s.icon} {s.label}+ </button>+ ));+ };++ const renderResults = () => {+ if (!result) return null;++ return (+ <div className="space-y-4">+ {/* Valuation Metrics */}+ {result.valuation_metrics && (+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h4 className="text-sm font-medium text-white mb-3 flex items-center gap-2">+ <TrendingUp size={14} style={{ color: FINCEPT.ORANGE }} />+ Valuation Metrics+ </h4>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {Object.entries(result.valuation_metrics).map(([key, value]) => (+ <div key={key} className="p-3 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <div className="text-xs text-gray-400">{key.replace(/_/g, ' ').toUpperCase()}</div>+ <div className="text-lg font-bold text-white">+ {typeof value === 'number' ? value.toFixed(2) : String(value)}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Benchmarks */}+ {result.benchmarks && (+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h4 className="text-sm font-medium text-white mb-3 flex items-center gap-2">+ <BarChart3 size={14} style={{ color: FINCEPT.ORANGE }} />+ Industry Benchmarks+ </h4>+ <div className="space-y-2">+ {Object.entries(result.benchmarks).map(([key, benchmark]: [string, any]) => (+ <div key={key} className="flex items-center justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ <span className="text-xs text-gray-400">{key.replace(/_/g, ' ')}</span>+ <div className="flex items-center gap-4">+ <span className="text-xs text-gray-500">25th: {benchmark.p25?.toFixed(1) ?? '-'}</span>+ <span className="text-xs text-gray-400">Median: {benchmark.median?.toFixed(1) ?? '-'}</span>+ <span className="text-xs text-gray-500">75th: {benchmark.p75?.toFixed(1) ?? '-'}</span>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Key Insights */}+ {result.insights && result.insights.length > 0 && (+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h4 className="text-sm font-medium text-white mb-3">Key Insights</h4>+ <ul className="space-y-2">+ {result.insights.map((insight: string, idx: number) => (+ <li key={idx} className="text-xs text-gray-300 flex items-start gap-2">+ <span style={{ color: FINCEPT.ORANGE }}>•</span>+ {insight}+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* Raw Data */}+ <details className="text-xs">+ <summary className="text-gray-500 cursor-pointer hover:text-gray-400">View raw data</summary>+ <pre className="mt-2 p-3 rounded overflow-auto text-gray-400" style={{ backgroundColor: FINCEPT.CHARCOAL, maxHeight: 200 }}>+ {JSON.stringify(result, null, 2)}+ </pre>+ </details>+ </div>+ );+ };++ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT.CHARCOAL }}>+ {/* Header */}+ <div className="flex items-center justify-between p-4 border-b" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <div className="flex items-center gap-3">+ <div className="p-2 rounded-lg" style={{ backgroundColor: FINCEPT.ORANGE + '20' }}>+ <BarChart3 size={20} style={{ color: FINCEPT.ORANGE }} />+ </div>+ <div>+ <h2 className={TYPOGRAPHY.HEADING}>Industry Metrics</h2>+ <p className="text-xs text-gray-400">Sector-specific valuation metrics and benchmarks</p>+ </div>+ </div>+ <button+ onClick={runAnalysis}+ disabled={loading}+ className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-90 disabled:opacity-50"+ style={{ backgroundColor: FINCEPT.ORANGE, color: '#000' }}+ >+ {loading ? <Loader2 size={16} className="animate-spin" /> : <PlayCircle size={16} />}+ Calculate Metrics+ </button>+ </div>++ {/* Industry Type Tabs */}+ <div className="flex items-center gap-2 px-4 py-2 border-b" style={{ borderColor: FINCEPT.PANEL_BG }}>+ <button+ onClick={() => setIndustryType('tech')}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${+ industryType === 'tech' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: industryType === 'tech' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <Cpu size={16} /> Technology+ </button>+ <button+ onClick={() => setIndustryType('healthcare')}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${+ industryType === 'healthcare' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: industryType === 'healthcare' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <HeartPulse size={16} /> Healthcare+ </button>+ <button+ onClick={() => setIndustryType('financial')}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${+ industryType === 'financial' ? 'text-white' : 'text-gray-400 hover:text-white'+ }`}+ style={{ backgroundColor: industryType === 'financial' ? FINCEPT.PANEL_BG : 'transparent' }}+ >+ <Building2 size={16} /> Financial Services+ </button>+ </div>++ {/* Sector Sub-tabs */}+ <div className="flex items-center gap-1 px-4 py-1 border-b overflow-x-auto" style={{ borderColor: FINCEPT.PANEL_BG }}>+ {renderSectorTabs()}+ </div>++ {/* Content */}+ <div className="flex-1 overflow-auto p-4">+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ {/* Input Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">+ {industryType === 'tech' && TECH_SECTORS.find(s => s.value === techSector)?.label}+ {industryType === 'healthcare' && HEALTHCARE_SECTORS.find(s => s.value === healthcareSector)?.label}+ {industryType === 'financial' && FINANCIAL_SECTORS.find(s => s.value === financialSector)?.label}+ {' '}Inputs+ </h3>+ <div className="space-y-3">+ {getCurrentFields().map(field => (+ <div key={field.key}>+ <label className="text-xs text-gray-400 mb-1 block">{field.label}</label>+ <input+ type="number"+ value={getCurrentInputs()[field.key] || 0}+ onChange={e => updateInput(field.key, parseFloat(e.target.value) || 0)}+ className="w-full px-3 py-2 rounded text-sm text-white"+ style={{ backgroundColor: FINCEPT.CHARCOAL, border: `1px solid ${FINCEPT.CHARCOAL}` }}+ />+ </div>+ ))}+ </div>+ </div>++ {/* Results Panel */}+ <div className="p-4 rounded-lg" style={{ backgroundColor: FINCEPT.PANEL_BG }}>+ <h3 className="text-sm font-medium text-white mb-4">Analysis Results</h3>+ {loading ? (+ <div className="flex items-center justify-center h-48">+ <Loader2 size={24} className="animate-spin" style={{ color: FINCEPT.ORANGE }} />+ </div>+ ) : result ? (+ renderResults()+ ) : (+ <div className="flex flex-col items-center justify-center h-48 text-gray-500 text-sm">+ <BarChart3 size={32} className="mb-2 opacity-50" />+ <p>Click "Calculate Metrics" to analyze</p>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++export default IndustryMetrics;diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsxindex 899084982..13ab77071 100644--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/MergerAnalysis.tsx@@ -1,19 +1,23 @@/**- * Merger Analysis - Unified Accretion/Dilution, Synergies, Deal Structure+ * Merger Analysis - Unified Accretion/Dilution, Synergies, Deal Structure, Pro Forma*- * All merger analysis tools in one interface+ * Complete merger analysis toolkit with advanced deal structures*/import React, { useState } from 'react';-import { GitMerge, Zap, DollarSign, PlayCircle, TrendingUp, TrendingDown } from 'lucide-react';+import { GitMerge, Zap, DollarSign, PlayCircle, TrendingUp, TrendingDown, Target, Percent, Shield, FileText, PieChart, Layers } from 'lucide-react';import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';import { MAAnalyticsService } from '@/services/maAnalyticsService';import { showSuccess, showError } from '@/utils/notifications';-type AnalysisType = 'accretion' | 'synergies' | 'structure';+type AnalysisType = 'accretion' | 'synergies' | 'structure' | 'proforma';+type StructureSubTab = 'payment' | 'earnout' | 'exchange' | 'collar' | 'cvr';+type ProFormaSubTab = 'proforma' | 'sources_uses' | 'contribution';export const MergerAnalysis: React.FC = () => {const [analysisType, setAnalysisType] = useState<AnalysisType>('accretion');+ const [structureSubTab, setStructureSubTab] = useState<StructureSubTab>('payment');+ const [proformaSubTab, setProformaSubTab] = useState<ProFormaSubTab>('proforma');const [loading, setLoading] = useState(false);const [result, setResult] = useState<any>(null);@@ -40,7 +44,7 @@ export const MergerAnalysis: React.FC = () => {years: 5,});- // Deal Structure Inputs+ // Payment Structure Inputsconst [structureInputs, setStructureInputs] = useState({purchasePrice: 1000,cashPct: 60,@@ -48,6 +52,79 @@ export const MergerAnalysis: React.FC = () => {debtCapacity: 400,});+ // Earnout Inputs+ const [earnoutInputs, setEarnoutInputs] = useState({+ maxEarnout: 200,+ revenueTarget: 500,+ ebitdaTarget: 100,+ earnoutPeriod: 3,+ baseRevenue: 400,+ revenueGrowth: 0.10,+ baseEbitda: 80,+ ebitdaGrowth: 0.08,+ });++ // Exchange Ratio Inputs+ const [exchangeInputs, setExchangeInputs] = useState({+ acquirerPrice: 50,+ targetPrice: 30,+ offerPremium: 0.25,+ });++ // Collar Inputs+ const [collarInputs, setCollarInputs] = useState({+ baseRatio: 0.8,+ floorPrice: 45,+ capPrice: 55,+ targetShares: 50,+ priceScenarios: '40,45,50,55,60,65',+ });++ // CVR Inputs+ const [cvrInputs, setCvrInputs] = useState({+ cvrType: 'milestone' as 'milestone' | 'earnout' | 'litigation',+ milestone: 'FDA_APPROVAL',+ probability: 0.60,+ payoutAmount: 5.00,+ expectedDate: '2025-12-31',+ discountRate: 0.12,+ });++ // Pro Forma Inputs+ const [proformaInputs, setProformaInputs] = useState({+ acquirerRevenue: 10000,+ acquirerEbitda: 2000,+ acquirerNetIncome: 1000,+ targetRevenue: 3000,+ targetEbitda: 600,+ targetNetIncome: 300,+ projectionYear: 1,+ });++ // Sources & Uses Inputs+ const [sourcesUsesInputs, setSourcesUsesInputs] = useState({+ purchasePrice: 5000,+ targetDebt: 500,+ transactionFees: 100,+ financingFees: 50,+ cashOnHand: 1000,+ newDebt: 2000,+ stockIssuance: 2650,+ });++ // Contribution Analysis Inputs+ const [contributionInputs, setContributionInputs] = useState({+ acquirerRevenue: 10000,+ acquirerEbitda: 2000,+ acquirerNetIncome: 1000,+ acquirerAssets: 15000,+ targetRevenue: 3000,+ targetEbitda: 600,+ targetNetIncome: 300,+ targetAssets: 4000,+ ownershipSplit: 0.77,+ });+const handleRunAccretion = async () => {setLoading(true);try {@@ -114,7 +191,7 @@ export const MergerAnalysis: React.FC = () => {}};- const handleRunStructure = async () => {+ const handleRunPaymentStructure = async () => {setLoading(true);try {const res = await MAAnalyticsService.DealStructure.analyzePaymentStructure(@@ -134,11 +211,223 @@ export const MergerAnalysis: React.FC = () => {}};+ const handleRunEarnout = async () => {+ setLoading(true);+ try {+ const earnoutParams = {+ max_earnout: earnoutInputs.maxEarnout * 1000000,+ revenue_target: earnoutInputs.revenueTarget * 1000000,+ ebitda_target: earnoutInputs.ebitdaTarget * 1000000,+ earnout_period: earnoutInputs.earnoutPeriod,+ payment_schedule: 'annual',+ };++ const financialProjections = {+ revenue: Array.from({ length: earnoutInputs.earnoutPeriod }, (_, i) =>+ earnoutInputs.baseRevenue * Math.pow(1 + earnoutInputs.revenueGrowth, i + 1) * 1000000+ ),+ ebitda: Array.from({ length: earnoutInputs.earnoutPeriod }, (_, i) =>+ earnoutInputs.baseEbitda * Math.pow(1 + earnoutInputs.ebitdaGrowth, i + 1) * 1000000+ ),+ };++ const res = await MAAnalyticsService.DealStructure.valueEarnout(earnoutParams, financialProjections);+ setResult(res);+ showSuccess('Earnout Valued', [+ { label: 'EXPECTED VALUE', value: formatCurrency(res.data?.expected_value || 0) }+ ]);+ } catch (error) {+ showError('Earnout valuation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunExchangeRatio = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.DealStructure.calculateExchangeRatio(+ exchangeInputs.acquirerPrice,+ exchangeInputs.targetPrice,+ exchangeInputs.offerPremium+ );+ setResult(res);+ showSuccess('Exchange Ratio Calculated', [+ { label: 'RATIO', value: `${res.data?.exchange_ratio?.toFixed(4)}x` }+ ]);+ } catch (error) {+ showError('Exchange ratio calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunCollar = async () => {+ setLoading(true);+ try {+ const collarParams = {+ base_exchange_ratio: collarInputs.baseRatio,+ floor_price: collarInputs.floorPrice,+ cap_price: collarInputs.capPrice,+ target_shares: collarInputs.targetShares * 1000000,+ collar_type: 'fixed_value',+ };++ const priceScenarios = {+ acquirer_prices: collarInputs.priceScenarios.split(',').map(v => parseFloat(v.trim())),+ };++ const res = await MAAnalyticsService.DealStructure.analyzeCollarMechanism(collarParams, priceScenarios);+ setResult(res);+ showSuccess('Collar Analysis Complete');+ } catch (error) {+ showError('Collar analysis failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunCVR = async () => {+ setLoading(true);+ try {+ const cvrParams = {+ milestone: cvrInputs.milestone,+ probability: cvrInputs.probability,+ payout_amount: cvrInputs.payoutAmount,+ expected_date: cvrInputs.expectedDate,+ discount_rate: cvrInputs.discountRate,+ };++ const res = await MAAnalyticsService.DealStructure.valueCVR(cvrInputs.cvrType, cvrParams);+ setResult(res);+ showSuccess('CVR Valued', [+ { label: 'EXPECTED VALUE', value: `$${res.data?.expected_value?.toFixed(2)}` }+ ]);+ } catch (error) {+ showError('CVR valuation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunProForma = async () => {+ setLoading(true);+ try {+ const acquirerData = {+ revenue: proformaInputs.acquirerRevenue * 1000000,+ ebitda: proformaInputs.acquirerEbitda * 1000000,+ net_income: proformaInputs.acquirerNetIncome * 1000000,+ };++ const targetData = {+ revenue: proformaInputs.targetRevenue * 1000000,+ ebitda: proformaInputs.targetEbitda * 1000000,+ net_income: proformaInputs.targetNetIncome * 1000000,+ };++ const res = await MAAnalyticsService.MergerModel.buildProForma(acquirerData, targetData, proformaInputs.projectionYear);+ setResult(res);+ showSuccess('Pro Forma Built', [+ { label: 'COMBINED REVENUE', value: formatCurrency(res.data?.combined_revenue || 0) }+ ]);+ } catch (error) {+ showError('Pro Forma failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunSourcesUses = async () => {+ setLoading(true);+ try {+ const dealStructure = {+ purchase_price: sourcesUsesInputs.purchasePrice * 1000000,+ target_debt: sourcesUsesInputs.targetDebt * 1000000,+ transaction_fees: sourcesUsesInputs.transactionFees * 1000000,+ financing_fees: sourcesUsesInputs.financingFees * 1000000,+ };++ const financingStructure = {+ cash_on_hand: sourcesUsesInputs.cashOnHand * 1000000,+ new_debt: sourcesUsesInputs.newDebt * 1000000,+ stock_issuance: sourcesUsesInputs.stockIssuance * 1000000,+ };++ const res = await MAAnalyticsService.MergerModel.calculateSourcesUses(dealStructure, financingStructure);+ setResult(res);+ showSuccess('Sources & Uses Calculated');+ } catch (error) {+ showError('Sources & Uses failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunContribution = async () => {+ setLoading(true);+ try {+ const acquirerData = {+ revenue: contributionInputs.acquirerRevenue * 1000000,+ ebitda: contributionInputs.acquirerEbitda * 1000000,+ net_income: contributionInputs.acquirerNetIncome * 1000000,+ total_assets: contributionInputs.acquirerAssets * 1000000,+ };++ const targetData = {+ revenue: contributionInputs.targetRevenue * 1000000,+ ebitda: contributionInputs.targetEbitda * 1000000,+ net_income: contributionInputs.targetNetIncome * 1000000,+ total_assets: contributionInputs.targetAssets * 1000000,+ };++ const res = await MAAnalyticsService.MergerModel.analyzeContribution(+ acquirerData,+ targetData,+ contributionInputs.ownershipSplit+ );+ setResult(res);+ showSuccess('Contribution Analysis Complete');+ } catch (error) {+ showError('Contribution analysis failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };+const handleRun = () => {+ if (analysisType === 'structure') {+ switch (structureSubTab) {+ case 'payment': return handleRunPaymentStructure();+ case 'earnout': return handleRunEarnout();+ case 'exchange': return handleRunExchangeRatio();+ case 'collar': return handleRunCollar();+ case 'cvr': return handleRunCVR();+ }+ }+ if (analysisType === 'proforma') {+ switch (proformaSubTab) {+ case 'proforma': return handleRunProForma();+ case 'sources_uses': return handleRunSourcesUses();+ case 'contribution': return handleRunContribution();+ }+ }switch (analysisType) {case 'accretion': return handleRunAccretion();case 'synergies': return handleRunSynergies();- case 'structure': return handleRunStructure();}};@@ -148,11 +437,30 @@ export const MergerAnalysis: React.FC = () => {return `$${value.toLocaleString()}`;};+ const renderInputField = (+ label: string,+ value: number | string,+ onChange: (val: string) => void,+ placeholder?: string+ ) => (+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{label}</label>+ <input+ type="text"+ inputMode="decimal"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ style={COMMON_STYLES.inputField}+ />+ </div>+ );+return (<div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>{/* LEFT - Analysis Type & Inputs */}<div style={{- width: '400px',+ width: '420px',backgroundColor: FINCEPT.PANEL_BG,borderRight: `1px solid ${FINCEPT.BORDER}`,display: 'flex',@@ -168,11 +476,12 @@ export const MergerAnalysis: React.FC = () => {<div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>ANALYSIS TYPE</div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.TINY }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.TINY }}>{[- { id: 'accretion', label: 'ACCRETION / DILUTION', icon: GitMerge },+ { id: 'accretion', label: 'ACCRETION/DILUTION', icon: GitMerge },{ id: 'synergies', label: 'SYNERGIES', icon: Zap },{ id: 'structure', label: 'DEAL STRUCTURE', icon: DollarSign },+ { id: 'proforma', label: 'PRO FORMA', icon: FileText },].map((type) => {const Icon = type.icon;return (@@ -181,243 +490,275 @@ export const MergerAnalysis: React.FC = () => {onClick={() => { setAnalysisType(type.id as AnalysisType); setResult(null); }}style={{...COMMON_STYLES.tabButton(analysisType === type.id),- width: '100%',justifyContent: 'flex-start',+ padding: '8px',}}>- <Icon size={12} style={{ marginRight: SPACING.SMALL }} />+ <Icon size={12} style={{ marginRight: SPACING.TINY }} />{type.label}</button>);})}</div>++ {/* Structure Sub-tabs */}+ {analysisType === 'structure' && (+ <div style={{ marginTop: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>STRUCTURE TYPE</div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: SPACING.TINY }}>+ {[+ { id: 'payment', label: 'Payment', icon: DollarSign },+ { id: 'earnout', label: 'Earnout', icon: Target },+ { id: 'exchange', label: 'Exchange', icon: Percent },+ { id: 'collar', label: 'Collar', icon: Shield },+ { id: 'cvr', label: 'CVR', icon: FileText },+ ].map((t) => {+ const Icon = t.icon;+ return (+ <button+ key={t.id}+ onClick={() => { setStructureSubTab(t.id as StructureSubTab); setResult(null); }}+ style={{+ ...COMMON_STYLES.tabButton(structureSubTab === t.id),+ padding: '4px 8px',+ fontSize: TYPOGRAPHY.TINY,+ }}+ >+ <Icon size={10} style={{ marginRight: '4px' }} />+ {t.label}+ </button>+ );+ })}+ </div>+ </div>+ )}++ {/* Pro Forma Sub-tabs */}+ {analysisType === 'proforma' && (+ <div style={{ marginTop: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>PRO FORMA TYPE</div>+ <div style={{ display: 'flex', gap: SPACING.TINY }}>+ {[+ { id: 'proforma', label: 'Pro Forma', icon: FileText },+ { id: 'sources_uses', label: 'Sources/Uses', icon: Layers },+ { id: 'contribution', label: 'Contribution', icon: PieChart },+ ].map((t) => {+ const Icon = t.icon;+ return (+ <button+ key={t.id}+ onClick={() => { setProformaSubTab(t.id as ProFormaSubTab); setResult(null); }}+ style={{+ ...COMMON_STYLES.tabButton(proformaSubTab === t.id),+ padding: '6px 10px',+ fontSize: TYPOGRAPHY.TINY,+ }}+ >+ <Icon size={10} style={{ marginRight: '4px' }} />+ {t.label}+ </button>+ );+ })}+ </div>+ </div>+ )}</div>{/* Input Forms */}<div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>+ {/* Accretion/Dilution */}{analysisType === 'accretion' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- ACQUIRER ($M)- </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>ACQUIRER ($M)</div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Revenue</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.acquirerRevenue}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, acquirerRevenue: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Net Income</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.acquirerNetIncome}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, acquirerNetIncome: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Shares (M)</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.acquirerShares}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, acquirerShares: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>EPS</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.acquirerEPS}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, acquirerEPS: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- </div>-- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- TARGET ($M)+ {renderInputField('Revenue', accretionInputs.acquirerRevenue, (v) => setAccretionInputs({ ...accretionInputs, acquirerRevenue: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', accretionInputs.acquirerNetIncome, (v) => setAccretionInputs({ ...accretionInputs, acquirerNetIncome: parseFloat(v) || 0 }))}+ {renderInputField('Shares (M)', accretionInputs.acquirerShares, (v) => setAccretionInputs({ ...accretionInputs, acquirerShares: parseFloat(v) || 0 }))}+ {renderInputField('EPS', accretionInputs.acquirerEPS, (v) => setAccretionInputs({ ...accretionInputs, acquirerEPS: parseFloat(v) || 0 }))}</div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Revenue</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.targetRevenue}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, targetRevenue: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Net Income</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.targetNetIncome}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, targetNetIncome: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Purchase Price</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.purchasePrice}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setAccretionInputs({ ...accretionInputs, purchasePrice: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Cash %</label>- <input- type="text"- inputMode="decimal"- value={accretionInputs.cashPct}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { const cash = parseFloat(v) || 0; setAccretionInputs({ ...accretionInputs, cashPct: cash, stockPct: 100 - cash }); } }}- style={COMMON_STYLES.inputField}- />- </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TARGET ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Revenue', accretionInputs.targetRevenue, (v) => setAccretionInputs({ ...accretionInputs, targetRevenue: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', accretionInputs.targetNetIncome, (v) => setAccretionInputs({ ...accretionInputs, targetNetIncome: parseFloat(v) || 0 }))}+ {renderInputField('Purchase Price', accretionInputs.purchasePrice, (v) => setAccretionInputs({ ...accretionInputs, purchasePrice: parseFloat(v) || 0 }))}+ {renderInputField('Cash %', accretionInputs.cashPct, (v) => { const cash = parseFloat(v) || 0; setAccretionInputs({ ...accretionInputs, cashPct: cash, stockPct: 100 - cash }); })}</div></>)}+ {/* Synergies */}{analysisType === 'synergies' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- SYNERGY TYPE- </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>SYNERGY TYPE</div><div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}><buttononClick={() => setSynergiesInputs({ ...synergiesInputs, synergyType: 'revenue' })}- style={{- ...COMMON_STYLES.tabButton(synergiesInputs.synergyType === 'revenue'),- flex: 1,- }}+ style={{ ...COMMON_STYLES.tabButton(synergiesInputs.synergyType === 'revenue'), flex: 1 }}>REVENUE</button><buttononClick={() => setSynergiesInputs({ ...synergiesInputs, synergyType: 'cost' })}- style={{- ...COMMON_STYLES.tabButton(synergiesInputs.synergyType === 'cost'),- flex: 1,- }}+ style={{ ...COMMON_STYLES.tabButton(synergiesInputs.synergyType === 'cost'), flex: 1 }}>COST</button></div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Base Revenue ($M)', synergiesInputs.baseRevenue, (v) => setSynergiesInputs({ ...synergiesInputs, baseRevenue: parseFloat(v) || 0 }))}+ {renderInputField('Cross-Sell Rate', synergiesInputs.crossSellRate, (v) => setSynergiesInputs({ ...synergiesInputs, crossSellRate: parseFloat(v) || 0 }))}+ {renderInputField('Projection Years', synergiesInputs.years, (v) => setSynergiesInputs({ ...synergiesInputs, years: parseInt(v) || 0 }))}+ </div>+ </>+ )}- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- SYNERGY INPUTS+ {/* Deal Structure - Payment */}+ {analysisType === 'structure' && structureSubTab === 'payment' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>PAYMENT STRUCTURE ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Purchase Price', structureInputs.purchasePrice, (v) => setStructureInputs({ ...structureInputs, purchasePrice: parseFloat(v) || 0 }))}+ {renderInputField('Cash %', structureInputs.cashPct, (v) => setStructureInputs({ ...structureInputs, cashPct: parseFloat(v) || 0 }))}+ {renderInputField('Acquirer Cash Available', structureInputs.acquirerCash, (v) => setStructureInputs({ ...structureInputs, acquirerCash: parseFloat(v) || 0 }))}+ {renderInputField('Debt Capacity', structureInputs.debtCapacity, (v) => setStructureInputs({ ...structureInputs, debtCapacity: parseFloat(v) || 0 }))}</div>+ </>+ )}++ {/* Deal Structure - Earnout */}+ {analysisType === 'structure' && structureSubTab === 'earnout' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>EARNOUT TERMS ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Max Earnout', earnoutInputs.maxEarnout, (v) => setEarnoutInputs({ ...earnoutInputs, maxEarnout: parseFloat(v) || 0 }))}+ {renderInputField('Revenue Target', earnoutInputs.revenueTarget, (v) => setEarnoutInputs({ ...earnoutInputs, revenueTarget: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA Target', earnoutInputs.ebitdaTarget, (v) => setEarnoutInputs({ ...earnoutInputs, ebitdaTarget: parseFloat(v) || 0 }))}+ {renderInputField('Earnout Period (Years)', earnoutInputs.earnoutPeriod, (v) => setEarnoutInputs({ ...earnoutInputs, earnoutPeriod: parseInt(v) || 0 }))}+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>PROJECTIONS</div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Base Revenue ($M)- </label>- <input- type="text"- inputMode="decimal"- value={synergiesInputs.baseRevenue}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setSynergiesInputs({ ...synergiesInputs, baseRevenue: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Cross-Sell Rate- </label>- <input- type="text"- inputMode="decimal"- value={synergiesInputs.crossSellRate}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setSynergiesInputs({ ...synergiesInputs, crossSellRate: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Projection Years- </label>- <input- type="text"- inputMode="numeric"- value={synergiesInputs.years}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*$/.test(v)) setSynergiesInputs({ ...synergiesInputs, years: parseInt(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>+ {renderInputField('Base Revenue ($M)', earnoutInputs.baseRevenue, (v) => setEarnoutInputs({ ...earnoutInputs, baseRevenue: parseFloat(v) || 0 }))}+ {renderInputField('Revenue Growth Rate', earnoutInputs.revenueGrowth, (v) => setEarnoutInputs({ ...earnoutInputs, revenueGrowth: parseFloat(v) || 0 }))}+ {renderInputField('Base EBITDA ($M)', earnoutInputs.baseEbitda, (v) => setEarnoutInputs({ ...earnoutInputs, baseEbitda: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA Growth Rate', earnoutInputs.ebitdaGrowth, (v) => setEarnoutInputs({ ...earnoutInputs, ebitdaGrowth: parseFloat(v) || 0 }))}</div></>)}- {analysisType === 'structure' && (+ {/* Deal Structure - Exchange Ratio */}+ {analysisType === 'structure' && structureSubTab === 'exchange' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- PAYMENT STRUCTURE ($M)+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>EXCHANGE RATIO INPUTS</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Acquirer Stock Price', exchangeInputs.acquirerPrice, (v) => setExchangeInputs({ ...exchangeInputs, acquirerPrice: parseFloat(v) || 0 }))}+ {renderInputField('Target Stock Price', exchangeInputs.targetPrice, (v) => setExchangeInputs({ ...exchangeInputs, targetPrice: parseFloat(v) || 0 }))}+ {renderInputField('Offer Premium', exchangeInputs.offerPremium, (v) => setExchangeInputs({ ...exchangeInputs, offerPremium: parseFloat(v) || 0 }))}</div>+ </>+ )}++ {/* Deal Structure - Collar */}+ {analysisType === 'structure' && structureSubTab === 'collar' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>COLLAR MECHANISM</div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Purchase Price- </label>- <input- type="text"- inputMode="decimal"- value={structureInputs.purchasePrice}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setStructureInputs({ ...structureInputs, purchasePrice: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Cash %- </label>- <input- type="text"- inputMode="decimal"- value={structureInputs.cashPct}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setStructureInputs({ ...structureInputs, cashPct: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Acquirer Cash Available- </label>- <input- type="text"- inputMode="decimal"- value={structureInputs.acquirerCash}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setStructureInputs({ ...structureInputs, acquirerCash: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Debt Capacity- </label>- <input- type="text"- inputMode="decimal"- value={structureInputs.debtCapacity}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setStructureInputs({ ...structureInputs, debtCapacity: parseFloat(v) || 0 }); }}- style={COMMON_STYLES.inputField}- />- </div>+ {renderInputField('Base Exchange Ratio', collarInputs.baseRatio, (v) => setCollarInputs({ ...collarInputs, baseRatio: parseFloat(v) || 0 }))}+ {renderInputField('Floor Price', collarInputs.floorPrice, (v) => setCollarInputs({ ...collarInputs, floorPrice: parseFloat(v) || 0 }))}+ {renderInputField('Cap Price', collarInputs.capPrice, (v) => setCollarInputs({ ...collarInputs, capPrice: parseFloat(v) || 0 }))}+ {renderInputField('Target Shares (M)', collarInputs.targetShares, (v) => setCollarInputs({ ...collarInputs, targetShares: parseFloat(v) || 0 }))}+ {renderInputField('Price Scenarios (comma-sep)', collarInputs.priceScenarios, (v) => setCollarInputs({ ...collarInputs, priceScenarios: v }), '40,45,50,55,60')}+ </div>+ </>+ )}++ {/* Deal Structure - CVR */}+ {analysisType === 'structure' && structureSubTab === 'cvr' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>CVR TYPE</div>+ <div style={{ display: 'flex', gap: SPACING.TINY, marginBottom: SPACING.DEFAULT }}>+ {['milestone', 'earnout', 'litigation'].map((type) => (+ <button+ key={type}+ onClick={() => setCvrInputs({ ...cvrInputs, cvrType: type as any })}+ style={{+ ...COMMON_STYLES.tabButton(cvrInputs.cvrType === type),+ flex: 1,+ textTransform: 'uppercase',+ }}+ >+ {type}+ </button>+ ))}+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>CVR PARAMETERS</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Milestone', cvrInputs.milestone, (v) => setCvrInputs({ ...cvrInputs, milestone: v }), 'FDA_APPROVAL')}+ {renderInputField('Probability', cvrInputs.probability, (v) => setCvrInputs({ ...cvrInputs, probability: parseFloat(v) || 0 }))}+ {renderInputField('Payout Amount ($)', cvrInputs.payoutAmount, (v) => setCvrInputs({ ...cvrInputs, payoutAmount: parseFloat(v) || 0 }))}+ {renderInputField('Expected Date', cvrInputs.expectedDate, (v) => setCvrInputs({ ...cvrInputs, expectedDate: v }), 'YYYY-MM-DD')}+ {renderInputField('Discount Rate', cvrInputs.discountRate, (v) => setCvrInputs({ ...cvrInputs, discountRate: parseFloat(v) || 0 }))}</div></>)}++ {/* Pro Forma */}+ {analysisType === 'proforma' && proformaSubTab === 'proforma' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>ACQUIRER ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Revenue', proformaInputs.acquirerRevenue, (v) => setProformaInputs({ ...proformaInputs, acquirerRevenue: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA', proformaInputs.acquirerEbitda, (v) => setProformaInputs({ ...proformaInputs, acquirerEbitda: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', proformaInputs.acquirerNetIncome, (v) => setProformaInputs({ ...proformaInputs, acquirerNetIncome: parseFloat(v) || 0 }))}+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TARGET ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Revenue', proformaInputs.targetRevenue, (v) => setProformaInputs({ ...proformaInputs, targetRevenue: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA', proformaInputs.targetEbitda, (v) => setProformaInputs({ ...proformaInputs, targetEbitda: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', proformaInputs.targetNetIncome, (v) => setProformaInputs({ ...proformaInputs, targetNetIncome: parseFloat(v) || 0 }))}+ </div>+ {renderInputField('Projection Year', proformaInputs.projectionYear, (v) => setProformaInputs({ ...proformaInputs, projectionYear: parseInt(v) || 1 }))}+ </>+ )}++ {/* Sources & Uses */}+ {analysisType === 'proforma' && proformaSubTab === 'sources_uses' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>USES OF FUNDS ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Purchase Price', sourcesUsesInputs.purchasePrice, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, purchasePrice: parseFloat(v) || 0 }))}+ {renderInputField('Target Debt Refinance', sourcesUsesInputs.targetDebt, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, targetDebt: parseFloat(v) || 0 }))}+ {renderInputField('Transaction Fees', sourcesUsesInputs.transactionFees, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, transactionFees: parseFloat(v) || 0 }))}+ {renderInputField('Financing Fees', sourcesUsesInputs.financingFees, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, financingFees: parseFloat(v) || 0 }))}+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>SOURCES OF FUNDS ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Cash on Hand', sourcesUsesInputs.cashOnHand, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, cashOnHand: parseFloat(v) || 0 }))}+ {renderInputField('New Debt', sourcesUsesInputs.newDebt, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, newDebt: parseFloat(v) || 0 }))}+ {renderInputField('Stock Issuance', sourcesUsesInputs.stockIssuance, (v) => setSourcesUsesInputs({ ...sourcesUsesInputs, stockIssuance: parseFloat(v) || 0 }))}+ </div>+ </>+ )}++ {/* Contribution Analysis */}+ {analysisType === 'proforma' && proformaSubTab === 'contribution' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>ACQUIRER ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Revenue', contributionInputs.acquirerRevenue, (v) => setContributionInputs({ ...contributionInputs, acquirerRevenue: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA', contributionInputs.acquirerEbitda, (v) => setContributionInputs({ ...contributionInputs, acquirerEbitda: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', contributionInputs.acquirerNetIncome, (v) => setContributionInputs({ ...contributionInputs, acquirerNetIncome: parseFloat(v) || 0 }))}+ {renderInputField('Total Assets', contributionInputs.acquirerAssets, (v) => setContributionInputs({ ...contributionInputs, acquirerAssets: parseFloat(v) || 0 }))}+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TARGET ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Revenue', contributionInputs.targetRevenue, (v) => setContributionInputs({ ...contributionInputs, targetRevenue: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA', contributionInputs.targetEbitda, (v) => setContributionInputs({ ...contributionInputs, targetEbitda: parseFloat(v) || 0 }))}+ {renderInputField('Net Income', contributionInputs.targetNetIncome, (v) => setContributionInputs({ ...contributionInputs, targetNetIncome: parseFloat(v) || 0 }))}+ {renderInputField('Total Assets', contributionInputs.targetAssets, (v) => setContributionInputs({ ...contributionInputs, targetAssets: parseFloat(v) || 0 }))}+ </div>+ {renderInputField('Acquirer Ownership %', contributionInputs.ownershipSplit, (v) => setContributionInputs({ ...contributionInputs, ownershipSplit: parseFloat(v) || 0 }))}+ </>+ )}</div>{/* Run Button */}@@ -445,7 +786,14 @@ export const MergerAnalysis: React.FC = () => {<div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>{analysisType === 'accretion' && 'ACCRETION / DILUTION ANALYSIS'}{analysisType === 'synergies' && `${synergiesInputs.synergyType.toUpperCase()} SYNERGIES`}- {analysisType === 'structure' && 'PAYMENT STRUCTURE ANALYSIS'}+ {analysisType === 'structure' && structureSubTab === 'payment' && 'PAYMENT STRUCTURE'}+ {analysisType === 'structure' && structureSubTab === 'earnout' && 'EARNOUT VALUATION'}+ {analysisType === 'structure' && structureSubTab === 'exchange' && 'EXCHANGE RATIO'}+ {analysisType === 'structure' && structureSubTab === 'collar' && 'COLLAR MECHANISM'}+ {analysisType === 'structure' && structureSubTab === 'cvr' && 'CVR VALUATION'}+ {analysisType === 'proforma' && proformaSubTab === 'proforma' && 'PRO FORMA FINANCIALS'}+ {analysisType === 'proforma' && proformaSubTab === 'sources_uses' && 'SOURCES & USES'}+ {analysisType === 'proforma' && proformaSubTab === 'contribution' && 'CONTRIBUTION ANALYSIS'}</div>{/* Accretion/Dilution Results */}@@ -460,48 +808,246 @@ export const MergerAnalysis: React.FC = () => {<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div><div style={COMMON_STYLES.dataLabel}>PRO FORMA EPS</div>- <div style={{- fontSize: '32px',- fontWeight: TYPOGRAPHY.BOLD,- color: FINCEPT.WHITE,- marginTop: SPACING.TINY,- }}>+ <div style={{ fontSize: '32px', fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>${result.pro_forma_eps.toFixed(2)}</div></div><div style={{ textAlign: 'right' }}>- <div style={{- fontSize: TYPOGRAPHY.SMALL,- color: result.eps_accretion_pct > 0 ? FINCEPT.GREEN : FINCEPT.RED,- display: 'flex',- alignItems: 'center',- gap: SPACING.TINY,- }}>+ <div style={{ fontSize: TYPOGRAPHY.SMALL, color: result.eps_accretion_pct > 0 ? FINCEPT.GREEN : FINCEPT.RED, display: 'flex', alignItems: 'center', gap: SPACING.TINY }}>{result.eps_accretion_pct > 0 ? <TrendingUp size={16} /> : <TrendingDown size={16} />}{result.eps_accretion_pct > 0 ? 'ACCRETIVE' : 'DILUTIVE'}</div>- <div style={{- fontSize: '24px',- fontWeight: TYPOGRAPHY.BOLD,- color: result.eps_accretion_pct > 0 ? FINCEPT.GREEN : FINCEPT.RED,- }}>+ <div style={{ fontSize: '24px', fontWeight: TYPOGRAPHY.BOLD, color: result.eps_accretion_pct > 0 ? FINCEPT.GREEN : FINCEPT.RED }}>{result.eps_accretion_pct > 0 ? '+' : ''}{result.eps_accretion_pct.toFixed(1)}%</div></div></div></div>-<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}><div style={COMMON_STYLES.metricCard}><div style={COMMON_STYLES.dataLabel}>PRO FORMA REVENUE</div>- <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>- {formatCurrency(result.pro_forma_revenue || 0)}- </div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>{formatCurrency(result.pro_forma_revenue || 0)}</div></div><div style={COMMON_STYLES.metricCard}><div style={COMMON_STYLES.dataLabel}>PRO FORMA SHARES</div>- <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>- {((result.pro_forma_shares || 0) / 1000000).toFixed(1)}M+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>{((result.pro_forma_shares || 0) / 1000000).toFixed(1)}M</div>+ </div>+ </div>+ </div>+ )}++ {/* Exchange Ratio Results */}+ {analysisType === 'structure' && structureSubTab === 'exchange' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.CYAN}15` }}>+ <div style={COMMON_STYLES.dataLabel}>EXCHANGE RATIO</div>+ <div style={{ fontSize: '28px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {result.data.exchange_ratio?.toFixed(4)}x+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>OFFER PRICE</div>+ <div style={{ fontSize: '24px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ ${result.data.offer_price?.toFixed(2)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>PREMIUM</div>+ <div style={{ fontSize: '24px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {(result.data.premium * 100)?.toFixed(1)}%+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Earnout Results */}+ {analysisType === 'structure' && structureSubTab === 'earnout' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.GREEN}15` }}>+ <div style={COMMON_STYLES.dataLabel}>EXPECTED VALUE</div>+ <div style={{ fontSize: '24px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.expected_value || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>ACHIEVEMENT PROB</div>+ <div style={{ fontSize: '24px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {((result.data.achievement_probability || 0) * 100).toFixed(0)}%+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>MAX EARNOUT</div>+ <div style={{ fontSize: '24px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.max_earnout || 0)}+ </div>+ </div>+ </div>+ </div>+ )}++ {/* CVR Results */}+ {analysisType === 'structure' && structureSubTab === 'cvr' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.PURPLE}15` }}>+ <div style={COMMON_STYLES.dataLabel}>CVR VALUE</div>+ <div style={{ fontSize: '28px', color: FINCEPT.PURPLE, marginTop: SPACING.TINY }}>+ ${result.data.expected_value?.toFixed(2)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>PRESENT VALUE</div>+ <div style={{ fontSize: '24px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ ${result.data.present_value?.toFixed(2)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>PROBABILITY</div>+ <div style={{ fontSize: '24px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {((result.data.probability || 0) * 100).toFixed(0)}%+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Collar Results */}+ {analysisType === 'structure' && structureSubTab === 'collar' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ {result.data.scenarios && Array.isArray(result.data.scenarios) && (+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ overflow: 'auto',+ }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: TYPOGRAPHY.TINY }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Acquirer Price</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Effective Ratio</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Shares Issued</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Deal Value</th>+ </tr>+ </thead>+ <tbody>+ {result.data.scenarios.map((row: any, idx: number) => (+ <tr key={idx}>+ <td style={{ padding: '8px', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>${row.acquirer_price}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.CYAN, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{row.effective_ratio?.toFixed(4)}x</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{((row.shares_issued || 0) / 1000000).toFixed(1)}M</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GREEN, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{formatCurrency(row.deal_value || 0)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </div>+ )}++ {/* Sources & Uses Results */}+ {analysisType === 'proforma' && proformaSubTab === 'sources_uses' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL, color: FINCEPT.GREEN }}>SOURCES</div>+ {result.data.sources && Object.entries(result.data.sources).map(([key, val]) => (+ <div key={key} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: SPACING.TINY }}>+ <span style={{ color: FINCEPT.GRAY, textTransform: 'uppercase', fontSize: TYPOGRAPHY.TINY }}>{key.replace(/_/g, ' ')}</span>+ <span style={{ color: FINCEPT.WHITE }}>{formatCurrency(val as number)}</span>+ </div>+ ))}+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, paddingTop: SPACING.SMALL, marginTop: SPACING.SMALL, display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GREEN, fontWeight: TYPOGRAPHY.BOLD }}>TOTAL</span>+ <span style={{ color: FINCEPT.GREEN, fontWeight: TYPOGRAPHY.BOLD }}>{formatCurrency(result.data.total_sources || 0)}</span>+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL, color: FINCEPT.RED }}>USES</div>+ {result.data.uses && Object.entries(result.data.uses).map(([key, val]) => (+ <div key={key} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: SPACING.TINY }}>+ <span style={{ color: FINCEPT.GRAY, textTransform: 'uppercase', fontSize: TYPOGRAPHY.TINY }}>{key.replace(/_/g, ' ')}</span>+ <span style={{ color: FINCEPT.WHITE }}>{formatCurrency(val as number)}</span>+ </div>+ ))}+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, paddingTop: SPACING.SMALL, marginTop: SPACING.SMALL, display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.RED, fontWeight: TYPOGRAPHY.BOLD }}>TOTAL</span>+ <span style={{ color: FINCEPT.RED, fontWeight: TYPOGRAPHY.BOLD }}>{formatCurrency(result.data.total_uses || 0)}</span>+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Contribution Analysis Results */}+ {analysisType === 'proforma' && proformaSubTab === 'contribution' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ {result.data.contributions && (+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ overflow: 'auto',+ marginBottom: SPACING.DEFAULT,+ }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: TYPOGRAPHY.TINY }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Metric</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Acquirer %</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Target %</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Ownership</th>+ </tr>+ </thead>+ <tbody>+ {Object.entries(result.data.contributions).map(([metric, data]: [string, any]) => (+ <tr key={metric}>+ <td style={{ padding: '8px', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}`, textTransform: 'uppercase' }}>{metric.replace(/_/g, ' ')}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.CYAN, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{(data.acquirer_pct * 100).toFixed(1)}%</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{(data.target_pct * 100).toFixed(1)}%</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{(contributionInputs.ownershipSplit * 100).toFixed(0)}%</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ {result.data.fairness_assessment && (+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: result.data.fairness_assessment.is_fair ? `${FINCEPT.GREEN}15` : `${FINCEPT.RED}15` }}>+ <div style={COMMON_STYLES.dataLabel}>FAIRNESS ASSESSMENT</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: result.data.fairness_assessment.is_fair ? FINCEPT.GREEN : FINCEPT.RED, marginTop: SPACING.TINY }}>+ {result.data.fairness_assessment.is_fair ? 'FAIR' : 'POTENTIALLY UNFAIR'}+ </div>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginTop: SPACING.TINY }}>+ {result.data.fairness_assessment.commentary}+ </div>+ </div>+ )}+ </div>+ )}++ {/* Pro Forma Results */}+ {analysisType === 'proforma' && proformaSubTab === 'proforma' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>COMBINED REVENUE</div>+ <div style={{ fontSize: '24px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.combined_revenue || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>COMBINED EBITDA</div>+ <div style={{ fontSize: '24px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.combined_ebitda || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>COMBINED NET INCOME</div>+ <div style={{ fontSize: '24px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.combined_net_income || 0)}</div></div></div>@@ -517,7 +1063,7 @@ export const MergerAnalysis: React.FC = () => {padding: SPACING.DEFAULT,borderRadius: '4px',overflow: 'auto',- maxHeight: '500px',+ maxHeight: '300px',}}>{JSON.stringify(result, null, 2)}</pre>@@ -529,7 +1075,7 @@ export const MergerAnalysis: React.FC = () => {Select an analysis type and configure inputs</div><div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, marginTop: SPACING.SMALL }}>- Accretion/Dilution, Synergies, Deal Structure+ Accretion/Dilution • Synergies • Deal Structure • Pro Forma</div></div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/StartupValuation.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/StartupValuation.tsxnew file mode 100644index 000000000..0ea47fd50--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/StartupValuation.tsx@@ -0,0 +1,750 @@+/**+ * Startup Valuation Panel - 5 Pre-Revenue Valuation Methods+ *+ * Methods: Berkus, Scorecard, VC Method, First Chicago, Risk Factor Summation+ */++import React, { useState } from 'react';+import { Rocket, PlayCircle, Loader2, TrendingUp, AlertTriangle, Target, Users, Lightbulb, Shield } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { MAAnalyticsService } from '@/services/maAnalyticsService';+import { showSuccess, showError } from '@/utils/notifications';++type ValuationMethod = 'berkus' | 'scorecard' | 'vc' | 'first_chicago' | 'risk_factor' | 'comprehensive';++const METHODS = [+ { id: 'berkus' as const, label: 'BERKUS', desc: 'Pre-revenue milestone-based' },+ { id: 'scorecard' as const, label: 'SCORECARD', desc: 'Comparative assessment' },+ { id: 'vc' as const, label: 'VC METHOD', desc: 'Expected return approach' },+ { id: 'first_chicago' as const, label: 'FIRST CHICAGO', desc: 'Scenario-weighted' },+ { id: 'risk_factor' as const, label: 'RISK FACTOR', desc: 'Risk adjustment method' },+ { id: 'comprehensive' as const, label: 'ALL METHODS', desc: 'Run all 5 methods' },+];++// Berkus factor descriptions+const BERKUS_FACTORS = [+ { key: 'sound_idea', label: 'Sound Idea', desc: 'Basic value of the concept', max: 500000 },+ { key: 'prototype', label: 'Prototype', desc: 'Reduces technology risk', max: 500000 },+ { key: 'quality_team', label: 'Quality Team', desc: 'Reduces execution risk', max: 500000 },+ { key: 'strategic_relationships', label: 'Strategic Relationships', desc: 'Reduces market risk', max: 500000 },+ { key: 'product_rollout', label: 'Product Rollout/Sales', desc: 'Reduces production risk', max: 500000 },+];++// Scorecard factors+const SCORECARD_FACTORS = [+ { key: 'team', label: 'Management Team', weight: 0.30 },+ { key: 'market_size', label: 'Market Size', weight: 0.25 },+ { key: 'product', label: 'Product/Technology', weight: 0.15 },+ { key: 'competitive', label: 'Competitive Environment', weight: 0.10 },+ { key: 'marketing', label: 'Marketing/Sales', weight: 0.10 },+ { key: 'need_for_funding', label: 'Need for Additional Funding', weight: 0.05 },+ { key: 'other', label: 'Other Factors', weight: 0.05 },+];++// Risk factors for Risk Factor Summation+const RISK_FACTORS = [+ { key: 'management', label: 'Management Risk' },+ { key: 'stage', label: 'Stage of Business' },+ { key: 'legislation', label: 'Legislation/Political Risk' },+ { key: 'manufacturing', label: 'Manufacturing Risk' },+ { key: 'sales_marketing', label: 'Sales & Marketing Risk' },+ { key: 'funding', label: 'Funding/Capital Raising Risk' },+ { key: 'competition', label: 'Competition Risk' },+ { key: 'technology', label: 'Technology Risk' },+ { key: 'litigation', label: 'Litigation Risk' },+ { key: 'international', label: 'International Risk' },+ { key: 'reputation', label: 'Reputation Risk' },+ { key: 'exit', label: 'Potential Lucrative Exit' },+];++export const StartupValuation: React.FC = () => {+ const [method, setMethod] = useState<ValuationMethod>('berkus');+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<any>(null);++ // Berkus inputs (0-100% of max $500K per factor)+ const [berkusScores, setBerkusScores] = useState<Record<string, number>>({+ sound_idea: 70,+ prototype: 50,+ quality_team: 80,+ strategic_relationships: 40,+ product_rollout: 30,+ });++ // Scorecard inputs+ const [scorecardInputs, setScorecardInputs] = useState({+ stage: 'seed',+ region: 'us',+ assessments: {+ team: 1.2,+ market_size: 1.1,+ product: 1.0,+ competitive: 0.9,+ marketing: 1.0,+ need_for_funding: 0.8,+ other: 1.0,+ } as Record<string, number>,+ });++ // VC Method inputs+ const [vcInputs, setVcInputs] = useState({+ exitYearMetric: 50, // $50M revenue at exit+ exitMultiple: 8, // 8x revenue multiple+ yearsToExit: 5,+ investmentAmount: 5, // $5M investment+ stage: 'seed',+ });++ // First Chicago inputs (3 scenarios)+ const [chicagoScenarios, setChicagoScenarios] = useState([+ { name: 'Bull Case', probability: 25, exit_year: 5, exit_value: 100, description: 'Exceeds targets' },+ { name: 'Base Case', probability: 50, exit_year: 5, exit_value: 40, description: 'Meets targets' },+ { name: 'Bear Case', probability: 25, exit_year: 5, exit_value: 10, description: 'Below targets' },+ ]);++ // Risk Factor inputs (-2 to +2 scale)+ const [riskInputs, setRiskInputs] = useState({+ baseValuation: 3, // $3M base+ assessments: Object.fromEntries(RISK_FACTORS.map(f => [f.key, 0])) as Record<string, number>,+ });++ // Startup name for comprehensive+ const [startupName, setStartupName] = useState('My Startup');++ const formatCurrency = (value: number) => {+ if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;+ if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;+ if (value >= 1e3) return `$${(value / 1e3).toFixed(0)}K`;+ return `$${value.toLocaleString()}`;+ };++ const handleRunBerkus = async () => {+ setLoading(true);+ try {+ const scores = Object.fromEntries(+ Object.entries(berkusScores).map(([k, v]) => [k, v / 100])+ );+ const res = await MAAnalyticsService.StartupValuation.calculateBerkusValuation(scores);+ setResult(res);+ showSuccess('Berkus Valuation Complete', [+ { label: 'VALUATION', value: formatCurrency(res.valuation || 0) }+ ]);+ } catch (error) {+ showError('Berkus calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunScorecard = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.StartupValuation.calculateScorecardValuation(+ scorecardInputs.stage,+ scorecardInputs.region,+ scorecardInputs.assessments+ );+ setResult(res);+ showSuccess('Scorecard Valuation Complete', [+ { label: 'VALUATION', value: formatCurrency(res.valuation || 0) }+ ]);+ } catch (error) {+ showError('Scorecard calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunVC = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.StartupValuation.calculateVCMethodValuation(+ vcInputs.exitYearMetric * 1e6,+ vcInputs.exitMultiple,+ vcInputs.yearsToExit,+ vcInputs.investmentAmount * 1e6,+ vcInputs.stage+ );+ setResult(res);+ showSuccess('VC Method Complete', [+ { label: 'PRE-MONEY', value: formatCurrency(res.pre_money_valuation || 0) },+ { label: 'POST-MONEY', value: formatCurrency(res.post_money_valuation || 0) }+ ]);+ } catch (error) {+ showError('VC Method calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunFirstChicago = async () => {+ setLoading(true);+ try {+ const scenarios = chicagoScenarios.map(s => ({+ ...s,+ probability: s.probability / 100,+ exit_value: s.exit_value * 1e6,+ }));+ const res = await MAAnalyticsService.StartupValuation.calculateFirstChicagoValuation(scenarios);+ setResult(res);+ showSuccess('First Chicago Complete', [+ { label: 'WEIGHTED VALUE', value: formatCurrency(res.weighted_valuation || 0) }+ ]);+ } catch (error) {+ showError('First Chicago calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunRiskFactor = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.StartupValuation.calculateRiskFactorValuation(+ riskInputs.baseValuation * 1e6,+ riskInputs.assessments+ );+ setResult(res);+ showSuccess('Risk Factor Complete', [+ { label: 'ADJUSTED VALUE', value: formatCurrency(res.adjusted_valuation || 0) }+ ]);+ } catch (error) {+ showError('Risk Factor calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunComprehensive = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.StartupValuation.comprehensiveStartupValuation({+ startup_name: startupName,+ berkus_scores: Object.fromEntries(+ Object.entries(berkusScores).map(([k, v]) => [k, v / 100])+ ),+ scorecard_inputs: scorecardInputs,+ vc_inputs: {+ exit_year_metric: vcInputs.exitYearMetric * 1e6,+ exit_multiple: vcInputs.exitMultiple,+ years_to_exit: vcInputs.yearsToExit,+ investment_amount: vcInputs.investmentAmount * 1e6,+ stage: vcInputs.stage,+ },+ first_chicago_scenarios: chicagoScenarios.map(s => ({+ ...s,+ probability: s.probability / 100,+ exit_value: s.exit_value * 1e6,+ })),+ risk_factor_assessments: riskInputs.assessments,+ });+ setResult(res);+ showSuccess('Comprehensive Valuation Complete');+ } catch (error) {+ showError('Comprehensive valuation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRun = () => {+ switch (method) {+ case 'berkus': return handleRunBerkus();+ case 'scorecard': return handleRunScorecard();+ case 'vc': return handleRunVC();+ case 'first_chicago': return handleRunFirstChicago();+ case 'risk_factor': return handleRunRiskFactor();+ case 'comprehensive': return handleRunComprehensive();+ }+ };++ const renderInputs = () => {+ switch (method) {+ case 'berkus':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.TINY }}>+ BERKUS FACTORS (0-100%)+ </div>+ {BERKUS_FACTORS.map(factor => (+ <div key={factor.key}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{factor.label}</span>+ <span style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.ORANGE }}>+ {berkusScores[factor.key]}% (${((berkusScores[factor.key] / 100) * factor.max / 1000).toFixed(0)}K)+ </span>+ </div>+ <input+ type="range"+ min="0"+ max="100"+ value={berkusScores[factor.key]}+ onChange={(e) => setBerkusScores({ ...berkusScores, [factor.key]: Number(e.target.value) })}+ style={{ width: '100%', accentColor: FINCEPT.ORANGE }}+ />+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{factor.desc}</div>+ </div>+ ))}+ </div>+ );++ case 'scorecard':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Stage</label>+ <select+ value={scorecardInputs.stage}+ onChange={(e) => setScorecardInputs({ ...scorecardInputs, stage: e.target.value })}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ >+ <option value="pre_seed">Pre-Seed</option>+ <option value="seed">Seed</option>+ <option value="series_a">Series A</option>+ </select>+ </div>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Region</label>+ <select+ value={scorecardInputs.region}+ onChange={(e) => setScorecardInputs({ ...scorecardInputs, region: e.target.value })}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ >+ <option value="us">United States</option>+ <option value="europe">Europe</option>+ <option value="asia">Asia</option>+ <option value="other">Other</option>+ </select>+ </div>+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginTop: SPACING.SMALL }}>+ FACTOR SCORES (0.5 = Below Avg, 1.0 = Avg, 1.5 = Above)+ </div>+ {SCORECARD_FACTORS.map(factor => (+ <div key={factor.key} style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <span style={{ flex: 1, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>+ {factor.label} ({(factor.weight * 100).toFixed(0)}%)+ </span>+ <input+ type="number"+ step="0.1"+ min="0.5"+ max="1.5"+ value={scorecardInputs.assessments[factor.key]}+ onChange={(e) => setScorecardInputs({+ ...scorecardInputs,+ assessments: { ...scorecardInputs.assessments, [factor.key]: Number(e.target.value) }+ })}+ style={{ ...COMMON_STYLES.inputField, width: '60px', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ ))}+ </div>+ );++ case 'vc':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Exit Year Revenue ($M)</label>+ <input+ type="number"+ value={vcInputs.exitYearMetric}+ onChange={(e) => setVcInputs({ ...vcInputs, exitYearMetric: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Exit Multiple (x Revenue)</label>+ <input+ type="number"+ step="0.5"+ value={vcInputs.exitMultiple}+ onChange={(e) => setVcInputs({ ...vcInputs, exitMultiple: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Years to Exit</label>+ <input+ type="number"+ value={vcInputs.yearsToExit}+ onChange={(e) => setVcInputs({ ...vcInputs, yearsToExit: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Investment Amount ($M)</label>+ <input+ type="number"+ value={vcInputs.investmentAmount}+ onChange={(e) => setVcInputs({ ...vcInputs, investmentAmount: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Stage</label>+ <select+ value={vcInputs.stage}+ onChange={(e) => setVcInputs({ ...vcInputs, stage: e.target.value })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ >+ <option value="seed">Seed (50-70% IRR)</option>+ <option value="series_a">Series A (40-60% IRR)</option>+ <option value="series_b">Series B (30-50% IRR)</option>+ <option value="growth">Growth (20-35% IRR)</option>+ </select>+ </div>+ </div>+ );++ case 'first_chicago':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div style={{ ...COMMON_STYLES.dataLabel }}>SCENARIO ANALYSIS</div>+ {chicagoScenarios.map((scenario, idx) => (+ <div key={idx} style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ fontWeight: TYPOGRAPHY.BOLD, color: FINCEPT.WHITE, marginBottom: SPACING.TINY }}>+ {scenario.name}+ </div>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Probability %</label>+ <input+ type="number"+ value={scenario.probability}+ onChange={(e) => {+ const updated = [...chicagoScenarios];+ updated[idx].probability = Number(e.target.value);+ setChicagoScenarios(updated);+ }}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ <div style={{ flex: 1 }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Exit Value ($M)</label>+ <input+ type="number"+ value={scenario.exit_value}+ onChange={(e) => {+ const updated = [...chicagoScenarios];+ updated[idx].exit_value = Number(e.target.value);+ setChicagoScenarios(updated);+ }}+ style={{ ...COMMON_STYLES.inputField, width: '100%', fontSize: TYPOGRAPHY.TINY }}+ />+ </div>+ </div>+ </div>+ ))}+ </div>+ );++ case 'risk_factor':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Base Valuation ($M)</label>+ <input+ type="number"+ value={riskInputs.baseValuation}+ onChange={(e) => setRiskInputs({ ...riskInputs, baseValuation: Number(e.target.value) })}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginTop: SPACING.SMALL }}>+ RISK ADJUSTMENTS (-2 to +2)+ </div>+ <div style={{ maxHeight: '300px', overflowY: 'auto' }}>+ {RISK_FACTORS.map(factor => (+ <div key={factor.key} style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL, marginBottom: '4px' }}>+ <span style={{ flex: 1, fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{factor.label}</span>+ <select+ value={riskInputs.assessments[factor.key]}+ onChange={(e) => setRiskInputs({+ ...riskInputs,+ assessments: { ...riskInputs.assessments, [factor.key]: Number(e.target.value) }+ })}+ style={{ ...COMMON_STYLES.inputField, width: '80px', fontSize: TYPOGRAPHY.TINY }}+ >+ <option value={-2}>-2 (High Risk)</option>+ <option value={-1}>-1</option>+ <option value={0}>0 (Neutral)</option>+ <option value={1}>+1</option>+ <option value={2}>+2 (Low Risk)</option>+ </select>+ </div>+ ))}+ </div>+ </div>+ );++ case 'comprehensive':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>Startup Name</label>+ <input+ type="text"+ value={startupName}+ onChange={(e) => setStartupName(e.target.value)}+ style={{ ...COMMON_STYLES.inputField, width: '100%' }}+ />+ </div>+ <div style={{+ padding: SPACING.SMALL,+ backgroundColor: `${FINCEPT.ORANGE}15`,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.ORANGE}40`,+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>+ COMPREHENSIVE ANALYSIS+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginTop: '4px' }}>+ Runs all 5 valuation methods using inputs from each tab. Configure each method first, then run comprehensive for a complete valuation range.+ </div>+ </div>+ </div>+ );+ }+ };++ const renderResults = () => {+ if (!result) {+ return (+ <div style={{ ...COMMON_STYLES.emptyState }}>+ <Rocket size={32} style={{ opacity: 0.3, marginBottom: SPACING.SMALL }} />+ <span style={{ color: FINCEPT.GRAY }}>Run a valuation to see results</span>+ </div>+ );+ }++ return (+ <div style={{ padding: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>+ VALUATION RESULTS+ </div>++ {/* Main valuation */}+ {result.valuation && (+ <div style={{+ padding: SPACING.DEFAULT,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.ORANGE}`,+ marginBottom: SPACING.DEFAULT,+ textAlign: 'center',+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>ESTIMATED VALUATION</div>+ <div style={{ fontSize: '24px', color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatCurrency(result.valuation)}+ </div>+ </div>+ )}++ {/* VC Method specific */}+ {result.pre_money_valuation && (+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>PRE-MONEY</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.GREEN }}>+ {formatCurrency(result.pre_money_valuation)}+ </div>+ </div>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>POST-MONEY</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.CYAN }}>+ {formatCurrency(result.post_money_valuation)}+ </div>+ </div>+ </div>+ )}++ {/* First Chicago specific */}+ {result.weighted_valuation && (+ <div style={{ marginBottom: SPACING.DEFAULT }}>+ <div style={{+ padding: SPACING.DEFAULT,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.ORANGE}`,+ textAlign: 'center',+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>PROBABILITY-WEIGHTED VALUE</div>+ <div style={{ fontSize: '24px', color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatCurrency(result.weighted_valuation)}+ </div>+ </div>+ </div>+ )}++ {/* Risk Factor specific */}+ {result.adjusted_valuation && (+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>BASE VALUE</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.GRAY }}>+ {formatCurrency(result.base_valuation || riskInputs.baseValuation * 1e6)}+ </div>+ </div>+ <div style={{ flex: 1, padding: SPACING.SMALL, backgroundColor: FINCEPT.PANEL_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>ADJUSTED VALUE</div>+ <div style={{ fontSize: TYPOGRAPHY.HEADING, color: FINCEPT.GREEN }}>+ {formatCurrency(result.adjusted_valuation)}+ </div>+ </div>+ </div>+ )}++ {/* Comprehensive results */}+ {result.methods && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {Object.entries(result.methods).map(([methodName, methodResult]: [string, any]) => (+ <div key={methodName} style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <span style={{ color: FINCEPT.GRAY, fontSize: TYPOGRAPHY.SMALL }}>+ {methodName.replace(/_/g, ' ').toUpperCase()}+ </span>+ <span style={{ color: FINCEPT.GREEN, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatCurrency(methodResult.valuation || methodResult.weighted_valuation || methodResult.adjusted_valuation || 0)}+ </span>+ </div>+ ))}+ </div>+ )}++ {/* Raw JSON for debugging */}+ <details style={{ marginTop: SPACING.DEFAULT }}>+ <summary style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, cursor: 'pointer' }}>+ Raw Output+ </summary>+ <pre style={{+ fontSize: '9px',+ color: FINCEPT.GRAY,+ backgroundColor: FINCEPT.PANEL_BG,+ padding: SPACING.SMALL,+ borderRadius: '4px',+ overflow: 'auto',+ maxHeight: '200px',+ }}>+ {JSON.stringify(result, null, 2)}+ </pre>+ </details>+ </div>+ );+ };++ return (+ <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>+ {/* LEFT - Method Selector & Inputs */}+ <div style={{+ width: '380px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ {/* Method Tabs */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: '1px',+ backgroundColor: FINCEPT.BORDER,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ {METHODS.map(m => (+ <button+ key={m.id}+ onClick={() => { setMethod(m.id); setResult(null); }}+ style={{+ padding: SPACING.SMALL,+ backgroundColor: method === m.id ? FINCEPT.PANEL_BG : FINCEPT.DARK_BG,+ border: 'none',+ borderBottom: method === m.id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ color: method === m.id ? FINCEPT.ORANGE : FINCEPT.GRAY,+ cursor: 'pointer',+ fontSize: '9px',+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}+ >+ {m.label}+ </button>+ ))}+ </div>++ {/* Method Description */}+ <div style={{+ padding: SPACING.SMALL,+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED }}>+ {METHODS.find(m => m.id === method)?.desc}+ </div>+ </div>++ {/* Inputs */}+ <div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>+ {renderInputs()}+ </div>++ {/* Run Button */}+ <div style={{ padding: SPACING.DEFAULT, borderTop: `1px solid ${FINCEPT.BORDER}` }}>+ <button+ onClick={handleRun}+ disabled={loading}+ style={{+ width: '100%',+ padding: SPACING.SMALL,+ backgroundColor: loading ? FINCEPT.PANEL_BG : FINCEPT.ORANGE,+ border: 'none',+ borderRadius: '4px',+ color: loading ? FINCEPT.GRAY : FINCEPT.DARK_BG,+ cursor: loading ? 'not-allowed' : 'pointer',+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: SPACING.SMALL,+ }}+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : <PlayCircle size={14} />}+ {loading ? 'CALCULATING...' : `RUN ${METHODS.find(m => m.id === method)?.label}`}+ </button>+ </div>+ </div>++ {/* RIGHT - Results */}+ <div style={{ flex: 1, overflow: 'auto', backgroundColor: FINCEPT.DARK_BG }}>+ {renderResults()}+ </div>+ </div>+ );+};diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsxindex fa6db61ea..6bdacdd7c 100644--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/ValuationToolkit.tsx@@ -1,19 +1,21 @@/**- * Valuation Toolkit - Unified DCF, LBO, Trading Comps Calculator+ * Valuation Toolkit - Unified DCF, LBO, Trading Comps, Precedent Transactions*- * All valuation tools in one clean interface+ * Complete valuation toolkit with full LBO modeling, debt schedules, and sensitivity analysis*/import React, { useState } from 'react';-import { Calculator, TrendingUp, Building2, BarChart3, PlayCircle } from 'lucide-react';+import { Calculator, TrendingUp, Building2, BarChart3, PlayCircle, Layers, Grid3X3, DollarSign, Calendar, Plus, Minus } from 'lucide-react';import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';-import { MAAnalyticsService } from '@/services/maAnalyticsService';+import { MAAnalyticsService, LBOInputs } from '@/services/maAnalyticsService';import { showSuccess, showError, showWarning } from '@/utils/notifications';-type ValuationMethod = 'dcf' | 'lbo' | 'comps';+type ValuationMethod = 'dcf' | 'lbo' | 'lbo_model' | 'debt_schedule' | 'lbo_sensitivity' | 'comps' | 'precedent';+type LBOSubTab = 'returns' | 'full_model' | 'debt_schedule' | 'sensitivity';export const ValuationToolkit: React.FC = () => {const [method, setMethod] = useState<ValuationMethod>('dcf');+ const [lboSubTab, setLboSubTab] = useState<LBOSubTab>('returns');const [loading, setLoading] = useState(false);const [result, setResult] = useState<any>(null);@@ -27,7 +29,7 @@ export const ValuationToolkit: React.FC = () => {shares: 100,});- // LBO Inputs+ // LBO Returns Inputs (simple)const [lboInputs, setLboInputs] = useState({entryValuation: 1000,exitValuation: 1500,@@ -35,12 +37,68 @@ export const ValuationToolkit: React.FC = () => {holdingPeriod: 5,});+ // Full LBO Model Inputs+ const [lboModelInputs, setLboModelInputs] = useState<LBOInputs>({+ company_data: {+ revenue: 500,+ ebitda: 100,+ ebit: 80,+ capex: 25,+ nwc: 50,+ },+ transaction_assumptions: {+ purchase_price: 800,+ entry_multiple: 8.0,+ exit_multiple: 9.0,+ debt_percent: 0.60,+ equity_percent: 0.40,+ },+ projection_years: 5,+ });++ // Debt Schedule Inputs+ const [debtScheduleInputs, setDebtScheduleInputs] = useState({+ seniorDebt: 300,+ seniorRate: 0.06,+ seniorTerm: 7,+ subDebt: 100,+ subRate: 0.10,+ subTerm: 8,+ revolver: 50,+ revolverRate: 0.055,+ ebitdaYears: '100,110,121,133,146',+ capexYears: '25,27,30,33,36',+ sweepPct: 0.75,+ });++ // Sensitivity Inputs+ const [sensitivityInputs, setSensitivityInputs] = useState({+ baseRevenue: 500,+ baseEbitdaMargin: 0.20,+ baseExitMultiple: 9.0,+ baseDebtPct: 0.60,+ holdingPeriod: 5,+ revenueGrowthScenarios: '0.02,0.05,0.08,0.10,0.12',+ exitMultipleScenarios: '7.0,8.0,9.0,10.0,11.0',+ });+// Comps Inputsconst [compsInputs, setCompsInputs] = useState({targetTicker: '',compTickers: 'AAPL,MSFT,GOOGL',});+ // Precedent Transaction Inputs+ const [precedentInputs, setPrecedentInputs] = useState({+ targetRevenue: 500,+ targetEbitda: 100,+ transactions: [+ { name: 'Deal A', ev: 900, revenue: 400, ebitda: 80 },+ { name: 'Deal B', ev: 1200, revenue: 500, ebitda: 120 },+ { name: 'Deal C', ev: 750, revenue: 350, ebitda: 70 },+ ] as Array<{ name: string; ev: number; revenue: number; ebitda: number }>,+ });+const handleRunDCF = async () => {setLoading(true);try {@@ -84,7 +142,7 @@ export const ValuationToolkit: React.FC = () => {}};- const handleRunLBO = async () => {+ const handleRunLBOReturns = async () => {setLoading(true);try {const res = await MAAnalyticsService.LBO.calculateLBOReturns(@@ -94,12 +152,109 @@ export const ValuationToolkit: React.FC = () => {lboInputs.holdingPeriod);setResult(res);- showSuccess('LBO Complete', [+ showSuccess('LBO Returns Complete', [{ label: 'IRR', value: `${res.irr?.toFixed(1)}%` },{ label: 'MOIC', value: `${res.moic?.toFixed(2)}x` }]);} catch (error) {- showError('LBO calculation failed', [+ showError('LBO Returns calculation failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunLBOModel = async () => {+ setLoading(true);+ try {+ const res = await MAAnalyticsService.LBO.buildLBOModel(lboModelInputs);+ setResult(res);+ showSuccess('LBO Model Complete', [+ { label: 'IRR', value: res.data?.returns?.irr ? `${(res.data.returns.irr * 100).toFixed(1)}%` : 'N/A' },+ { label: 'MOIC', value: res.data?.returns?.moic ? `${res.data.returns.moic.toFixed(2)}x` : 'N/A' }+ ]);+ } catch (error) {+ showError('LBO Model failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunDebtSchedule = async () => {+ setLoading(true);+ try {+ const ebitdaArr = debtScheduleInputs.ebitdaYears.split(',').map(v => parseFloat(v.trim()) * 1000000);+ const capexArr = debtScheduleInputs.capexYears.split(',').map(v => parseFloat(v.trim()) * 1000000);++ const debtStructure = {+ senior: {+ amount: debtScheduleInputs.seniorDebt * 1000000,+ rate: debtScheduleInputs.seniorRate,+ term: debtScheduleInputs.seniorTerm,+ amortization: 'straight_line',+ },+ subordinated: {+ amount: debtScheduleInputs.subDebt * 1000000,+ rate: debtScheduleInputs.subRate,+ term: debtScheduleInputs.subTerm,+ amortization: 'bullet',+ },+ revolver: {+ amount: debtScheduleInputs.revolver * 1000000,+ rate: debtScheduleInputs.revolverRate,+ commitment: debtScheduleInputs.revolver * 1000000 * 1.5,+ },+ };++ const cashFlows = {+ ebitda: ebitdaArr,+ capex: capexArr,+ interest_paid: ebitdaArr.map((_, i) => (debtScheduleInputs.seniorDebt * debtScheduleInputs.seniorRate + debtScheduleInputs.subDebt * debtScheduleInputs.subRate) * 1000000 / (i + 1)),+ taxes: ebitdaArr.map(e => e * 0.21),+ };++ const res = await MAAnalyticsService.LBO.analyzeDebtSchedule(+ debtStructure,+ cashFlows,+ debtScheduleInputs.sweepPct+ );+ setResult(res);+ showSuccess('Debt Schedule Complete');+ } catch (error) {+ showError('Debt Schedule analysis failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };++ const handleRunSensitivity = async () => {+ setLoading(true);+ try {+ const revenueGrowths = sensitivityInputs.revenueGrowthScenarios.split(',').map(v => parseFloat(v.trim()));+ const exitMultiples = sensitivityInputs.exitMultipleScenarios.split(',').map(v => parseFloat(v.trim()));++ const baseCase = {+ revenue: sensitivityInputs.baseRevenue * 1000000,+ ebitda_margin: sensitivityInputs.baseEbitdaMargin,+ exit_multiple: sensitivityInputs.baseExitMultiple,+ debt_percent: sensitivityInputs.baseDebtPct,+ holding_period: sensitivityInputs.holdingPeriod,+ };++ const res = await MAAnalyticsService.LBO.calculateLBOSensitivity(+ baseCase,+ revenueGrowths,+ exitMultiples+ );+ setResult({ ...res, revenueGrowths, exitMultiples });+ showSuccess('Sensitivity Analysis Complete');+ } catch (error) {+ showError('Sensitivity analysis failed', [{ label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }]);} finally {@@ -129,11 +284,57 @@ export const ValuationToolkit: React.FC = () => {}};+ const handleRunPrecedent = async () => {+ setLoading(true);+ try {+ const targetData = {+ revenue: precedentInputs.targetRevenue * 1000000,+ ebitda: precedentInputs.targetEbitda * 1000000,+ };++ // Create MADeal-compatible structures from precedent transactions+ const compDeals = precedentInputs.transactions.map((t, idx) => ({+ deal_id: `precedent_${idx}`,+ target_name: t.name,+ acquirer_name: 'Acquirer',+ deal_value: t.ev * 1000000,+ premium_1day: 0.25,+ payment_cash_pct: 50,+ payment_stock_pct: 50,+ ev_revenue: t.revenue > 0 ? (t.ev / t.revenue) : undefined,+ ev_ebitda: t.ebitda > 0 ? (t.ev / t.ebitda) : undefined,+ status: 'completed',+ industry: 'General',+ announced_date: new Date().toISOString().split('T')[0],+ }));++ const res = await MAAnalyticsService.Valuation.calculatePrecedentTransactions(targetData, compDeals);+ setResult(res);+ showSuccess('Precedent Transactions Complete', [+ { label: 'IMPLIED EV', value: formatCurrency(res.valuation || 0) }+ ]);+ } catch (error) {+ showError('Precedent Transactions failed', [+ { label: 'ERROR', value: error instanceof Error ? error.message : 'Unknown error' }+ ]);+ } finally {+ setLoading(false);+ }+ };+const handleRun = () => {+ if (method === 'lbo') {+ switch (lboSubTab) {+ case 'returns': return handleRunLBOReturns();+ case 'full_model': return handleRunLBOModel();+ case 'debt_schedule': return handleRunDebtSchedule();+ case 'sensitivity': return handleRunSensitivity();+ }+ }switch (method) {case 'dcf': return handleRunDCF();- case 'lbo': return handleRunLBO();case 'comps': return handleRunComps();+ case 'precedent': return handleRunPrecedent();}};@@ -143,11 +344,44 @@ export const ValuationToolkit: React.FC = () => {return `$${value.toLocaleString()}`;};+ const renderInputField = (+ label: string,+ value: number | string,+ onChange: (val: string) => void,+ placeholder?: string+ ) => (+ <div>+ <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>{label}</label>+ <input+ type="text"+ inputMode="decimal"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ style={COMMON_STYLES.inputField}+ />+ </div>+ );++ const addPrecedentTransaction = () => {+ setPrecedentInputs({+ ...precedentInputs,+ transactions: [...precedentInputs.transactions, { name: `Deal ${String.fromCharCode(65 + precedentInputs.transactions.length)}`, ev: 0, revenue: 0, ebitda: 0 }],+ });+ };++ const removePrecedentTransaction = (index: number) => {+ setPrecedentInputs({+ ...precedentInputs,+ transactions: precedentInputs.transactions.filter((_, i) => i !== index),+ });+ };+return (<div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>{/* LEFT - Method Selector & Inputs */}<div style={{- width: '380px',+ width: '400px',backgroundColor: FINCEPT.PANEL_BG,borderRight: `1px solid ${FINCEPT.BORDER}`,display: 'flex',@@ -166,8 +400,9 @@ export const ValuationToolkit: React.FC = () => {<div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.TINY }}>{[{ id: 'dcf', label: 'DCF MODEL', icon: Calculator },- { id: 'lbo', label: 'LBO RETURNS', icon: Building2 },+ { id: 'lbo', label: 'LBO ANALYSIS', icon: Building2 },{ id: 'comps', label: 'TRADING COMPS', icon: BarChart3 },+ { id: 'precedent', label: 'PRECEDENT TXNS', icon: Layers },].map((m) => {const Icon = m.icon;return (@@ -175,7 +410,7 @@ export const ValuationToolkit: React.FC = () => {key={m.id}onClick={() => { setMethod(m.id as ValuationMethod); setResult(null); }}style={{- ...COMMON_STYLES.tabButton(method === m.id),+ ...COMMON_STYLES.tabButton(method === m.id || (method === 'lbo' && m.id === 'lbo')),width: '100%',justifyContent: 'flex-start',}}@@ -186,180 +421,273 @@ export const ValuationToolkit: React.FC = () => {);})}</div>++ {/* LBO Sub-tabs */}+ {method === 'lbo' && (+ <div style={{ marginTop: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>+ LBO ANALYSIS TYPE+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.TINY }}>+ {[+ { id: 'returns', label: 'Returns', icon: TrendingUp },+ { id: 'full_model', label: 'Full Model', icon: Layers },+ { id: 'debt_schedule', label: 'Debt Sched', icon: Calendar },+ { id: 'sensitivity', label: 'Sensitivity', icon: Grid3X3 },+ ].map((t) => {+ const Icon = t.icon;+ return (+ <button+ key={t.id}+ onClick={() => { setLboSubTab(t.id as LBOSubTab); setResult(null); }}+ style={{+ ...COMMON_STYLES.tabButton(lboSubTab === t.id),+ padding: '6px 8px',+ fontSize: TYPOGRAPHY.TINY,+ }}+ >+ <Icon size={10} style={{ marginRight: '4px' }} />+ {t.label}+ </button>+ );+ })}+ </div>+ </div>+ )}</div>{/* Input Forms */}<div style={{ flex: 1, overflow: 'auto', padding: SPACING.DEFAULT }}>{method === 'dcf' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- DCF INPUTS+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>DCF INPUTS</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('EBIT ($M)', dcfInputs.ebit, (v) => setDcfInputs({ ...dcfInputs, ebit: parseFloat(v) || 0 }))}+ {renderInputField('Tax Rate', dcfInputs.taxRate, (v) => setDcfInputs({ ...dcfInputs, taxRate: parseFloat(v) || 0 }))}+ {renderInputField('Risk-Free Rate', dcfInputs.riskFreeRate, (v) => setDcfInputs({ ...dcfInputs, riskFreeRate: parseFloat(v) || 0 }))}+ {renderInputField('Beta', dcfInputs.beta, (v) => setDcfInputs({ ...dcfInputs, beta: parseFloat(v) || 0 }))}+ {renderInputField('Terminal Growth', dcfInputs.terminalGrowth, (v) => setDcfInputs({ ...dcfInputs, terminalGrowth: parseFloat(v) || 0 }))}+ {renderInputField('Shares Outstanding (M)', dcfInputs.shares, (v) => setDcfInputs({ ...dcfInputs, shares: parseFloat(v) || 0 }))}</div>+ </>+ )}++ {method === 'lbo' && lboSubTab === 'returns' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>LBO RETURNS ($M)</div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- EBIT ($M)- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.ebit || dcfInputs.ebit === 0 ? String(dcfInputs.ebit) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, ebit: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Tax Rate- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.taxRate || dcfInputs.taxRate === 0 ? String(dcfInputs.taxRate) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, taxRate: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Risk-Free Rate- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.riskFreeRate || dcfInputs.riskFreeRate === 0 ? String(dcfInputs.riskFreeRate) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, riskFreeRate: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Beta- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.beta || dcfInputs.beta === 0 ? String(dcfInputs.beta) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, beta: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Terminal Growth- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.terminalGrowth || dcfInputs.terminalGrowth === 0 ? String(dcfInputs.terminalGrowth) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, terminalGrowth: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Shares Outstanding (M)- </label>- <input- type="text"- inputMode="decimal"- value={dcfInputs.shares || dcfInputs.shares === 0 ? String(dcfInputs.shares) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setDcfInputs({ ...dcfInputs, shares: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>+ {renderInputField('Entry Valuation', lboInputs.entryValuation, (v) => setLboInputs({ ...lboInputs, entryValuation: parseFloat(v) || 0 }))}+ {renderInputField('Exit Valuation', lboInputs.exitValuation, (v) => setLboInputs({ ...lboInputs, exitValuation: parseFloat(v) || 0 }))}+ {renderInputField('Equity Invested', lboInputs.equityInvested, (v) => setLboInputs({ ...lboInputs, equityInvested: parseFloat(v) || 0 }))}+ {renderInputField('Holding Period (Years)', lboInputs.holdingPeriod, (v) => setLboInputs({ ...lboInputs, holdingPeriod: parseInt(v) || 0 }))}</div></>)}- {method === 'lbo' && (+ {method === 'lbo' && lboSubTab === 'full_model' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>COMPANY DATA ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Revenue', lboModelInputs.company_data.revenue, (v) => setLboModelInputs({+ ...lboModelInputs,+ company_data: { ...lboModelInputs.company_data, revenue: parseFloat(v) || 0 }+ }))}+ {renderInputField('EBITDA', lboModelInputs.company_data.ebitda, (v) => setLboModelInputs({+ ...lboModelInputs,+ company_data: { ...lboModelInputs.company_data, ebitda: parseFloat(v) || 0 }+ }))}+ {renderInputField('EBIT', lboModelInputs.company_data.ebit, (v) => setLboModelInputs({+ ...lboModelInputs,+ company_data: { ...lboModelInputs.company_data, ebit: parseFloat(v) || 0 }+ }))}+ {renderInputField('CapEx', lboModelInputs.company_data.capex, (v) => setLboModelInputs({+ ...lboModelInputs,+ company_data: { ...lboModelInputs.company_data, capex: parseFloat(v) || 0 }+ }))}+ {renderInputField('Net Working Capital', lboModelInputs.company_data.nwc, (v) => setLboModelInputs({+ ...lboModelInputs,+ company_data: { ...lboModelInputs.company_data, nwc: parseFloat(v) || 0 }+ }))}+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TRANSACTION ASSUMPTIONS</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Purchase Price ($M)', lboModelInputs.transaction_assumptions.purchase_price, (v) => setLboModelInputs({+ ...lboModelInputs,+ transaction_assumptions: { ...lboModelInputs.transaction_assumptions, purchase_price: parseFloat(v) || 0 }+ }))}+ {renderInputField('Entry Multiple', lboModelInputs.transaction_assumptions.entry_multiple, (v) => setLboModelInputs({+ ...lboModelInputs,+ transaction_assumptions: { ...lboModelInputs.transaction_assumptions, entry_multiple: parseFloat(v) || 0 }+ }))}+ {renderInputField('Exit Multiple', lboModelInputs.transaction_assumptions.exit_multiple, (v) => setLboModelInputs({+ ...lboModelInputs,+ transaction_assumptions: { ...lboModelInputs.transaction_assumptions, exit_multiple: parseFloat(v) || 0 }+ }))}+ {renderInputField('Debt %', lboModelInputs.transaction_assumptions.debt_percent, (v) => setLboModelInputs({+ ...lboModelInputs,+ transaction_assumptions: { ...lboModelInputs.transaction_assumptions, debt_percent: parseFloat(v) || 0 }+ }))}+ {renderInputField('Equity %', lboModelInputs.transaction_assumptions.equity_percent, (v) => setLboModelInputs({+ ...lboModelInputs,+ transaction_assumptions: { ...lboModelInputs.transaction_assumptions, equity_percent: parseFloat(v) || 0 }+ }))}+ </div>++ {renderInputField('Projection Years', lboModelInputs.projection_years, (v) => setLboModelInputs({+ ...lboModelInputs,+ projection_years: parseInt(v) || 5+ }))}+ </>+ )}++ {method === 'lbo' && lboSubTab === 'debt_schedule' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- LBO INPUTS ($M)+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>SENIOR DEBT</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Amount ($M)', debtScheduleInputs.seniorDebt, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, seniorDebt: parseFloat(v) || 0 }))}+ {renderInputField('Interest Rate', debtScheduleInputs.seniorRate, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, seniorRate: parseFloat(v) || 0 }))}+ {renderInputField('Term (Years)', debtScheduleInputs.seniorTerm, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, seniorTerm: parseInt(v) || 0 }))}</div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>SUBORDINATED DEBT</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Amount ($M)', debtScheduleInputs.subDebt, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, subDebt: parseFloat(v) || 0 }))}+ {renderInputField('Interest Rate', debtScheduleInputs.subRate, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, subRate: parseFloat(v) || 0 }))}+ {renderInputField('Term (Years)', debtScheduleInputs.subTerm, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, subTerm: parseInt(v) || 0 }))}+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>REVOLVER</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Amount ($M)', debtScheduleInputs.revolver, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, revolver: parseFloat(v) || 0 }))}+ {renderInputField('Interest Rate', debtScheduleInputs.revolverRate, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, revolverRate: parseFloat(v) || 0 }))}+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>CASH FLOWS ($M, comma-separated)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('EBITDA by Year', debtScheduleInputs.ebitdaYears, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, ebitdaYears: v }), '100,110,121,...')}+ {renderInputField('CapEx by Year', debtScheduleInputs.capexYears, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, capexYears: v }), '25,27,30,...')}+ </div>++ {renderInputField('Cash Sweep %', debtScheduleInputs.sweepPct, (v) => setDebtScheduleInputs({ ...debtScheduleInputs, sweepPct: parseFloat(v) || 0 }))}+ </>+ )}++ {method === 'lbo' && lboSubTab === 'sensitivity' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>BASE CASE</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Base Revenue ($M)', sensitivityInputs.baseRevenue, (v) => setSensitivityInputs({ ...sensitivityInputs, baseRevenue: parseFloat(v) || 0 }))}+ {renderInputField('EBITDA Margin', sensitivityInputs.baseEbitdaMargin, (v) => setSensitivityInputs({ ...sensitivityInputs, baseEbitdaMargin: parseFloat(v) || 0 }))}+ {renderInputField('Exit Multiple', sensitivityInputs.baseExitMultiple, (v) => setSensitivityInputs({ ...sensitivityInputs, baseExitMultiple: parseFloat(v) || 0 }))}+ {renderInputField('Debt %', sensitivityInputs.baseDebtPct, (v) => setSensitivityInputs({ ...sensitivityInputs, baseDebtPct: parseFloat(v) || 0 }))}+ {renderInputField('Holding Period', sensitivityInputs.holdingPeriod, (v) => setSensitivityInputs({ ...sensitivityInputs, holdingPeriod: parseInt(v) || 0 }))}+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>SENSITIVITY SCENARIOS</div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Entry Valuation- </label>- <input- type="text"- inputMode="decimal"- value={lboInputs.entryValuation || lboInputs.entryValuation === 0 ? String(lboInputs.entryValuation) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setLboInputs({ ...lboInputs, entryValuation: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Exit Valuation- </label>- <input- type="text"- inputMode="decimal"- value={lboInputs.exitValuation || lboInputs.exitValuation === 0 ? String(lboInputs.exitValuation) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setLboInputs({ ...lboInputs, exitValuation: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Equity Invested- </label>- <input- type="text"- inputMode="decimal"- value={lboInputs.equityInvested || lboInputs.equityInvested === 0 ? String(lboInputs.equityInvested) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) { setLboInputs({ ...lboInputs, equityInvested: parseFloat(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Holding Period (Years)- </label>- <input- type="text"- inputMode="numeric"- value={lboInputs.holdingPeriod || lboInputs.holdingPeriod === 0 ? String(lboInputs.holdingPeriod) : ''}- onChange={(e) => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) { setLboInputs({ ...lboInputs, holdingPeriod: parseInt(v) || 0 }); } }}- style={COMMON_STYLES.inputField}- />- </div>+ {renderInputField('Revenue Growth Rates (comma-sep)', sensitivityInputs.revenueGrowthScenarios, (v) => setSensitivityInputs({ ...sensitivityInputs, revenueGrowthScenarios: v }), '0.02,0.05,0.08,...')}+ {renderInputField('Exit Multiples (comma-sep)', sensitivityInputs.exitMultipleScenarios, (v) => setSensitivityInputs({ ...sensitivityInputs, exitMultipleScenarios: v }), '7.0,8.0,9.0,...')}</div></>)}{method === 'comps' && (<>- <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>- TRADING COMPS+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TRADING COMPS</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>+ {renderInputField('Target Ticker', compsInputs.targetTicker, (v) => setCompsInputs({ ...compsInputs, targetTicker: v.toUpperCase() }), 'AAPL')}+ {renderInputField('Comparable Tickers (comma-sep)', compsInputs.compTickers, (v) => setCompsInputs({ ...compsInputs, compTickers: v.toUpperCase() }), 'MSFT,GOOGL,META')}+ </div>+ </>+ )}++ {method === 'precedent' && (+ <>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>TARGET COMPANY ($M)</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>+ {renderInputField('Target Revenue', precedentInputs.targetRevenue, (v) => setPrecedentInputs({ ...precedentInputs, targetRevenue: parseFloat(v) || 0 }))}+ {renderInputField('Target EBITDA', precedentInputs.targetEbitda, (v) => setPrecedentInputs({ ...precedentInputs, targetEbitda: parseFloat(v) || 0 }))}+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span>PRECEDENT TRANSACTIONS ($M)</span>+ <button+ onClick={addPrecedentTransaction}+ style={{ ...COMMON_STYLES.tabButton(false), padding: '4px 8px' }}+ >+ <Plus size={12} />+ </button></div><div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL }}>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Target Ticker- </label>- <input- type="text"- placeholder="AAPL"- value={compsInputs.targetTicker}- onChange={(e) => setCompsInputs({ ...compsInputs, targetTicker: e.target.value.toUpperCase() })}- style={COMMON_STYLES.inputField}- />- </div>- <div>- <label style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY }}>- Comparable Tickers (comma-separated)- </label>- <input- type="text"- placeholder="MSFT,GOOGL,META"- value={compsInputs.compTickers}- onChange={(e) => setCompsInputs({ ...compsInputs, compTickers: e.target.value.toUpperCase() })}- style={COMMON_STYLES.inputField}- />- </div>+ {precedentInputs.transactions.map((txn, idx) => (+ <div key={idx} style={{+ backgroundColor: FINCEPT.HEADER_BG,+ padding: SPACING.SMALL,+ borderRadius: '4px',+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: SPACING.TINY }}>+ <input+ type="text"+ value={txn.name}+ onChange={(e) => {+ const updated = [...precedentInputs.transactions];+ updated[idx].name = e.target.value;+ setPrecedentInputs({ ...precedentInputs, transactions: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, width: '120px', marginBottom: 0 }}+ />+ <button+ onClick={() => removePrecedentTransaction(idx)}+ style={{ ...COMMON_STYLES.tabButton(false), padding: '4px', color: FINCEPT.RED }}+ >+ <Minus size={12} />+ </button>+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.TINY }}>+ <div>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>EV</label>+ <input+ type="text"+ value={txn.ev}+ onChange={(e) => {+ const updated = [...precedentInputs.transactions];+ updated[idx].ev = parseFloat(e.target.value) || 0;+ setPrecedentInputs({ ...precedentInputs, transactions: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, padding: '4px' }}+ />+ </div>+ <div>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Rev</label>+ <input+ type="text"+ value={txn.revenue}+ onChange={(e) => {+ const updated = [...precedentInputs.transactions];+ updated[idx].revenue = parseFloat(e.target.value) || 0;+ setPrecedentInputs({ ...precedentInputs, transactions: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, padding: '4px' }}+ />+ </div>+ <div>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>EBITDA</label>+ <input+ type="text"+ value={txn.ebitda}+ onChange={(e) => {+ const updated = [...precedentInputs.transactions];+ updated[idx].ebitda = parseFloat(e.target.value) || 0;+ setPrecedentInputs({ ...precedentInputs, transactions: updated });+ }}+ style={{ ...COMMON_STYLES.inputField, padding: '4px' }}+ />+ </div>+ </div>+ </div>+ ))}</div></>)}@@ -389,11 +717,15 @@ export const ValuationToolkit: React.FC = () => {<div><div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.DEFAULT }}>{method === 'dcf' && 'DCF VALUATION RESULTS'}- {method === 'lbo' && 'LBO RETURNS'}+ {method === 'lbo' && lboSubTab === 'returns' && 'LBO RETURNS'}+ {method === 'lbo' && lboSubTab === 'full_model' && 'FULL LBO MODEL'}+ {method === 'lbo' && lboSubTab === 'debt_schedule' && 'DEBT SCHEDULE ANALYSIS'}+ {method === 'lbo' && lboSubTab === 'sensitivity' && 'SENSITIVITY ANALYSIS'}{method === 'comps' && 'TRADING COMPS RESULTS'}+ {method === 'precedent' && 'PRECEDENT TRANSACTIONS'}</div>- {/* Key Metrics Cards */}+ {/* DCF Results */}{method === 'dcf' && result.equity_value_per_share && (<div style={{ marginBottom: SPACING.LARGE }}><div style={{@@ -435,7 +767,8 @@ export const ValuationToolkit: React.FC = () => {</div>)}- {method === 'lbo' && result.irr && (+ {/* LBO Returns Results */}+ {method === 'lbo' && lboSubTab === 'returns' && result.irr && (<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.LARGE }}><div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.GREEN}15` }}><div style={COMMON_STYLES.dataLabel}>IRR</div>@@ -458,6 +791,278 @@ export const ValuationToolkit: React.FC = () => {</div>)}+ {/* Full LBO Model Results */}+ {method === 'lbo' && lboSubTab === 'full_model' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ {result.data.returns && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.GREEN}15` }}>+ <div style={COMMON_STYLES.dataLabel}>IRR</div>+ <div style={{ fontSize: '24px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {(result.data.returns.irr * 100).toFixed(1)}%+ </div>+ </div>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.CYAN}15` }}>+ <div style={COMMON_STYLES.dataLabel}>MOIC</div>+ <div style={{ fontSize: '24px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {result.data.returns.moic.toFixed(2)}x+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>ENTRY EQUITY</div>+ <div style={{ fontSize: '18px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.returns.entry_equity || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>EXIT EQUITY</div>+ <div style={{ fontSize: '18px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.returns.exit_equity || 0)}+ </div>+ </div>+ </div>+ )}++ {result.data.sources_uses && (+ <div style={{ marginBottom: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>SOURCES & USES</div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>SOURCES</div>+ {Object.entries(result.data.sources_uses.sources || {}).map(([key, val]) => (+ <div key={key} style={{ display: 'flex', justifyContent: 'space-between', fontSize: TYPOGRAPHY.TINY }}>+ <span style={{ color: FINCEPT.GRAY }}>{key.replace(/_/g, ' ').toUpperCase()}</span>+ <span style={{ color: FINCEPT.WHITE }}>{formatCurrency(val as number)}</span>+ </div>+ ))}+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>USES</div>+ {Object.entries(result.data.sources_uses.uses || {}).map(([key, val]) => (+ <div key={key} style={{ display: 'flex', justifyContent: 'space-between', fontSize: TYPOGRAPHY.TINY }}>+ <span style={{ color: FINCEPT.GRAY }}>{key.replace(/_/g, ' ').toUpperCase()}</span>+ <span style={{ color: FINCEPT.WHITE }}>{formatCurrency(val as number)}</span>+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </div>+ )}++ {/* Debt Schedule Results */}+ {method === 'lbo' && lboSubTab === 'debt_schedule' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ {result.data.summary && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>TOTAL DEBT</div>+ <div style={{ fontSize: '20px', color: FINCEPT.WHITE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.summary.total_debt || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>TOTAL INTEREST</div>+ <div style={{ fontSize: '20px', color: FINCEPT.RED, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.summary.total_interest || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>TOTAL PAYDOWN</div>+ <div style={{ fontSize: '20px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.summary.total_paydown || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>EXIT DEBT</div>+ <div style={{ fontSize: '20px', color: FINCEPT.ORANGE, marginTop: SPACING.TINY }}>+ {formatCurrency(result.data.summary.exit_debt || 0)}+ </div>+ </div>+ </div>+ )}++ {result.data.schedule && Array.isArray(result.data.schedule) && (+ <div>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>YEAR-BY-YEAR SCHEDULE</div>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ overflow: 'auto',+ }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: TYPOGRAPHY.TINY }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Year</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Opening</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Interest</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Paydown</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>Closing</th>+ </tr>+ </thead>+ <tbody>+ {result.data.schedule.map((row: any, idx: number) => (+ <tr key={idx}>+ <td style={{ padding: '8px', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{row.year}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{formatCurrency(row.opening || 0)}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.RED, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{formatCurrency(row.interest || 0)}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GREEN, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{formatCurrency(row.paydown || 0)}</td>+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{formatCurrency(row.closing || 0)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ </div>+ )}++ {/* Sensitivity Results */}+ {method === 'lbo' && lboSubTab === 'sensitivity' && result.data && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>IRR SENSITIVITY TABLE</div>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ overflow: 'auto',+ marginBottom: SPACING.DEFAULT,+ }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: TYPOGRAPHY.TINY }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ IRR+ </th>+ {result.exitMultiples?.map((m: number) => (+ <th key={m} style={{ padding: '8px', textAlign: 'center', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {m.toFixed(1)}x Exit+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {result.revenueGrowths?.map((g: number, gIdx: number) => (+ <tr key={gIdx}>+ <td style={{ padding: '8px', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {(g * 100).toFixed(0)}% Growth+ </td>+ {result.exitMultiples?.map((m: number, mIdx: number) => {+ const irr = result.data?.irr_matrix?.[gIdx]?.[mIdx] || 0;+ const color = irr >= 0.25 ? FINCEPT.GREEN : irr >= 0.15 ? FINCEPT.YELLOW : FINCEPT.RED;+ return (+ <td key={mIdx} style={{ padding: '8px', textAlign: 'center', color, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {(irr * 100).toFixed(1)}%+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>MOIC SENSITIVITY TABLE</div>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ overflow: 'auto',+ }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: TYPOGRAPHY.TINY }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.CYAN, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ MOIC+ </th>+ {result.exitMultiples?.map((m: number) => (+ <th key={m} style={{ padding: '8px', textAlign: 'center', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {m.toFixed(1)}x Exit+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {result.revenueGrowths?.map((g: number, gIdx: number) => (+ <tr key={gIdx}>+ <td style={{ padding: '8px', color: FINCEPT.GRAY, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {(g * 100).toFixed(0)}% Growth+ </td>+ {result.exitMultiples?.map((m: number, mIdx: number) => {+ const moic = result.data?.moic_matrix?.[gIdx]?.[mIdx] || 0;+ const color = moic >= 3 ? FINCEPT.GREEN : moic >= 2 ? FINCEPT.YELLOW : FINCEPT.RED;+ return (+ <td key={mIdx} style={{ padding: '8px', textAlign: 'center', color, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {moic.toFixed(2)}x+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}++ {/* Precedent Transaction Results */}+ {method === 'precedent' && result.valuation && (+ <div style={{ marginBottom: SPACING.LARGE }}>+ {result.range && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: SPACING.DEFAULT, marginBottom: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>LOW IMPLIED EV</div>+ <div style={{ fontSize: '20px', color: FINCEPT.RED, marginTop: SPACING.TINY }}>+ {formatCurrency(result.range.min || 0)}+ </div>+ </div>+ <div style={{ ...COMMON_STYLES.metricCard, backgroundColor: `${FINCEPT.CYAN}15` }}>+ <div style={COMMON_STYLES.dataLabel}>MID IMPLIED EV</div>+ <div style={{ fontSize: '24px', color: FINCEPT.CYAN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.valuation || 0)}+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={COMMON_STYLES.dataLabel}>HIGH IMPLIED EV</div>+ <div style={{ fontSize: '20px', color: FINCEPT.GREEN, marginTop: SPACING.TINY }}>+ {formatCurrency(result.range.max || 0)}+ </div>+ </div>+ </div>+ )}++ {result.assumptions?.multiples && (+ <div style={{ marginBottom: SPACING.DEFAULT }}>+ <div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>TRANSACTION MULTIPLES</div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.DEFAULT }}>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>EV/REVENUE</div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GRAY }}>Mean:</span>+ <span style={{ color: FINCEPT.WHITE }}>{result.assumptions.multiples.ev_revenue?.mean?.toFixed(2)}x</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GRAY }}>Median:</span>+ <span style={{ color: FINCEPT.WHITE }}>{result.assumptions.multiples.ev_revenue?.median?.toFixed(2)}x</span>+ </div>+ </div>+ <div style={COMMON_STYLES.metricCard}>+ <div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.GRAY, marginBottom: SPACING.TINY }}>EV/EBITDA</div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GRAY }}>Mean:</span>+ <span style={{ color: FINCEPT.WHITE }}>{result.assumptions.multiples.ev_ebitda?.mean?.toFixed(2)}x</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: FINCEPT.GRAY }}>Median:</span>+ <span style={{ color: FINCEPT.WHITE }}>{result.assumptions.multiples.ev_ebitda?.median?.toFixed(2)}x</span>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ )}+{/* Full JSON Results */}<div style={COMMON_STYLES.dataLabel}>DETAILED RESULTS</div><pre style={{@@ -467,7 +1072,7 @@ export const ValuationToolkit: React.FC = () => {padding: SPACING.DEFAULT,borderRadius: '4px',overflow: 'auto',- maxHeight: '400px',+ maxHeight: '300px',}}>{JSON.stringify(result, null, 2)}</pre>@@ -479,7 +1084,7 @@ export const ValuationToolkit: React.FC = () => {Select a valuation method and configure inputs</div><div style={{ fontSize: TYPOGRAPHY.TINY, color: FINCEPT.MUTED, marginTop: SPACING.SMALL }}>- DCF, LBO Returns, Trading Comps+ DCF • LBO Analysis • Trading Comps • Precedent Transactions</div></div>)}