
const { useState, useCallback } = React;

// Normal CDF approximation
function normCDF(x) {
  const a1=0.254829592,a2=-0.284496736,a3=1.421413741,a4=-1.453152027,a5=1.061405429,p=0.3275911;
  const sign = x < 0 ? -1 : 1;
  x = Math.abs(x)/Math.sqrt(2);
  const t = 1/(1+p*x);
  const y = 1-(((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t)*Math.exp(-x*x);
  return 0.5*(1+sign*y);
}
function normPDF(x) { return Math.exp(-0.5*x*x)/Math.sqrt(2*Math.PI); }

function blackScholes(S, K, T, r, sigma, type) {
  if (T <= 0 || sigma <= 0 || S <= 0 || K <= 0) return null;
  const sqrtT = Math.sqrt(T);
  const d1 = (Math.log(S/K) + (r + 0.5*sigma*sigma)*T) / (sigma*sqrtT);
  const d2 = d1 - sigma*sqrtT;
  const Nd1 = normCDF(d1), Nd2 = normCDF(d2);
  const nNd1 = normCDF(-d1), nNd2 = normCDF(-d2);
  const nd1 = normPDF(d1);
  const disc = Math.exp(-r*T);
  if (type === 'call') {
    const price = S*Nd1 - K*disc*Nd2;
    const delta = Nd1;
    const gamma = nd1/(S*sigma*sqrtT);
    const theta = (-(S*nd1*sigma)/(2*sqrtT) - r*K*disc*Nd2)/365;
    const vega = S*nd1*sqrtT/100;
    const rho = K*T*disc*Nd2/100;
    return { price, delta, gamma, theta, vega, rho, d1, d2, breakeven: K+price };
  } else {
    const price = K*disc*nNd2 - S*nNd1;
    const delta = Nd1 - 1;
    const gamma = nd1/(S*sigma*sqrtT);
    const theta = (-(S*nd1*sigma)/(2*sqrtT) + r*K*disc*nNd2)/365;
    const vega = S*nd1*sqrtT/100;
    const rho = -K*T*disc*nNd2/100;
    return { price, delta, gamma, theta, vega, rho, d1, d2, breakeven: K-price };
  }
}

const T_OPT = {
  es: {
    title: 'Analizador de Opciones', sub: 'Calculadora Black-Scholes con griegos en tiempo real',
    symbol: 'Símbolo', spot: 'Precio Actual ($)', strike: 'Precio de Ejercicio ($)',
    expiry: 'Días hasta Expiración', iv: 'Volatilidad Implícita (%)', rate: 'Tasa Libre de Riesgo (%)',
    type: 'Tipo', call: 'Call', put: 'Put', calc: 'Calcular',
    premium: 'Prima', delta: 'Delta', gamma: 'Gamma', theta: 'Theta/día', vega: 'Vega', rho: 'Rho',
    breakeven: 'Punto de Equilibrio', itm: 'En el dinero', otm: 'Fuera del dinero', atm: 'Al precio',
    greeks: 'Griegos', payoff: 'Payoff al Vencimiento', result: 'Resultado',
    noResult: 'Ingresa los parámetros y presiona Calcular',
    ranges: 'Escenarios de Precio',
  },
  en: {
    title: 'Options Analyzer', sub: 'Black-Scholes calculator with real-time Greeks',
    symbol: 'Symbol', spot: 'Current Price ($)', strike: 'Strike Price ($)',
    expiry: 'Days to Expiration', iv: 'Implied Volatility (%)', rate: 'Risk-Free Rate (%)',
    type: 'Type', call: 'Call', put: 'Put', calc: 'Calculate',
    premium: 'Premium', delta: 'Delta', gamma: 'Gamma', theta: 'Theta/day', vega: 'Vega', rho: 'Rho',
    breakeven: 'Break-Even', itm: 'In the money', otm: 'Out of the money', atm: 'At the money',
    greeks: 'Greeks', payoff: 'Payoff at Expiration', result: 'Result',
    noResult: 'Enter parameters and press Calculate',
    ranges: 'Price Scenarios',
  }
};

function OptionsAnalyzer({ lang }) {
  const t = T_OPT[lang] || T_OPT.es;
  const [form, setForm] = useState({ symbol:'AAPL', spot:185, strike:190, expiry:30, iv:25, rate:5, type:'call' });
  const [result, setResult] = useState(null);

  const set = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  const calculate = () => {
    const { spot, strike, expiry, iv, rate, type } = form;
    const S = parseFloat(spot), K = parseFloat(strike), T = parseFloat(expiry)/365;
    const r = parseFloat(rate)/100, sigma = parseFloat(iv)/100;
    const res = blackScholes(S, K, T, r, sigma, type);
    setResult(res);
  };

  const moneyness = result ? (form.type === 'call'
    ? (form.spot > form.strike ? 'itm' : form.spot < form.strike ? 'otm' : 'atm')
    : (form.spot < form.strike ? 'itm' : form.spot > form.strike ? 'otm' : 'atm')) : null;

  const moneyColor = moneyness === 'itm' ? 'var(--green)' : moneyness === 'otm' ? 'var(--red)' : 'var(--gold)';

  // Price scenario range
  const scenarios = result ? [-20,-15,-10,-5,0,5,10,15,20].map(pct => {
    const S2 = form.spot * (1 + pct/100);
    const intrinsic = form.type === 'call' ? Math.max(0, S2 - form.strike) : Math.max(0, form.strike - S2);
    const pnl = intrinsic - result.price;
    return { pct, S2: S2.toFixed(2), intrinsic: intrinsic.toFixed(2), pnl: pnl.toFixed(2), profit: pnl >= 0 };
  }) : [];

  const inp = { style: { width: '100%' } };

  return (
    <div>
      <div className="sec-label">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 20V10M12 20V4M6 20v-6"/></svg>
        {t.title}
        <span style={{ fontSize: 10, fontWeight: 400, color: 'var(--muted)', letterSpacing: '0.02em', textTransform: 'none' }}>{t.sub}</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16 }} className="two-col">

        {/* Inputs */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Type toggle */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4, background: 'var(--bg2)', padding: 4, borderRadius: 8, border: '1px solid var(--border)' }}>
            {['call','put'].map(tp => (
              <button key={tp} onClick={() => set('type', tp)}
                style={{ padding: '8px', borderRadius: 6, border: 'none', cursor: 'pointer', fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 13, letterSpacing: '0.05em', transition: 'all 0.15s',
                  background: form.type === tp ? (tp==='call'?'var(--green)':'var(--red)') : 'transparent',
                  color: form.type === tp ? (tp==='call'?'#0a1a0a':'#1a0a0a') : 'var(--muted)' }}>
                {tp === 'call' ? t.call : t.put}
              </button>
            ))}
          </div>

          {[
            ['symbol', t.symbol, 'text', null],
            ['spot', t.spot, 'number', 0.01],
            ['strike', t.strike, 'number', 0.01],
            ['expiry', t.expiry, 'number', 1],
            ['iv', t.iv, 'number', 0.1],
            ['rate', t.rate, 'number', 0.1],
          ].map(([key, label, type, step]) => (
            <div key={key}>
              <label style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', display: 'block', marginBottom: 4 }}>{label}</label>
              <input className="inp" type={type} step={step} value={form[key]}
                onChange={e => set(key, type === 'number' ? parseFloat(e.target.value) || '' : e.target.value.toUpperCase())} />
            </div>
          ))}

          <button className="btn btn-gold" onClick={calculate} style={{ width: '100%', justifyContent: 'center', fontFamily: 'Barlow, sans-serif', fontWeight: 700, letterSpacing: '0.05em' }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
            {t.calc}
          </button>
        </div>

        {/* Results */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {result ? (
            <>
              {/* Premium + moneyness */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                {[
                  { label: t.premium, value: `$${result.price.toFixed(4)}`, color: 'var(--gold)', big: true },
                  { label: t.breakeven, value: `$${result.breakeven.toFixed(2)}`, color: 'var(--text)' },
                  { label: t.result, value: t[moneyness], color: moneyColor },
                ].map(({ label, value, color, big }) => (
                  <div key={label} style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 8, padding: '12px 14px' }}>
                    <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
                    <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 800, fontSize: big ? 22 : 16, color }}>{value}</div>
                  </div>
                ))}
              </div>

              {/* Greeks */}
              <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 8, padding: '14px' }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10 }}>{t.greeks}</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 8 }}>
                  {[
                    { l: t.delta, v: result.delta.toFixed(4), color: Math.abs(result.delta) > 0.5 ? 'var(--green)' : 'var(--text)' },
                    { l: t.gamma, v: result.gamma.toFixed(5), color: 'var(--text)' },
                    { l: t.theta, v: result.theta.toFixed(4), color: result.theta < 0 ? 'var(--red)' : 'var(--green)' },
                    { l: t.vega, v: result.vega.toFixed(4), color: 'var(--text)' },
                    { l: t.rho, v: result.rho.toFixed(4), color: 'var(--text)' },
                  ].map(({ l, v, color }) => (
                    <div key={l} style={{ textAlign: 'center', padding: '8px 4px', background: 'var(--bg2)', borderRadius: 6, border: '1px solid var(--border)' }}>
                      <div style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 4 }}>{l}</div>
                      <div style={{ fontFamily: 'Barlow, sans-serif', fontWeight: 700, fontSize: 14, color }}>{v}</div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Scenarios table */}
              <div style={{ background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
                <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)' }}>{t.ranges}</div>
                <div style={{ maxHeight: 200, overflow: 'auto' }}>
                  <table className="tbl">
                    <thead><tr>
                      <th>Escenario</th><th>Precio</th><th>Intrínseco</th><th>P&L</th>
                    </tr></thead>
                    <tbody>
                      {scenarios.map(sc => (
                        <tr key={sc.pct}>
                          <td><span style={{ color: sc.pct > 0 ? 'var(--green)' : sc.pct < 0 ? 'var(--red)' : 'var(--muted)' }}>{sc.pct > 0 ? '+' : ''}{sc.pct}%</span></td>
                          <td>${sc.S2}</td>
                          <td>${sc.intrinsic}</td>
                          <td style={{ color: sc.profit ? 'var(--green)' : 'var(--red)', fontWeight: 600 }}>{sc.profit ? '+' : ''}${sc.pnl}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          ) : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 10, padding: 40, background: 'var(--card2)', border: '1px solid var(--border)', borderRadius: 8, minHeight: 200 }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--muted)" strokeWidth="1.2"><path d="M18 20V10M12 20V4M6 20v-6"/></svg>
              <div style={{ color: 'var(--muted)', fontSize: 13, textAlign: 'center' }}>{t.noResult}</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OptionsAnalyzer });
