// SVG candlestick chart — Day Trader persona (GOLD realistic prices ~2600-2680)
const { useMemo, useEffect, useRef, useState } = React;

function genCandles(count, basePrice = 4600, vol = 12) {
  const candles = [];
  let price = basePrice;
  for (let i = 0; i < count; i++) {
    const drift = (Math.random() - 0.48) * vol;
    const open = price;
    const close = price + drift;
    const wickRange = vol * 0.6;
    const high = Math.max(open, close) + Math.random() * wickRange;
    const low = Math.min(open, close) - Math.random() * wickRange;
    candles.push({ open, close, high, low, vol: Math.random() * 2.5 + 0.5 });
    price = close;
  }
  return candles;
}

// H4 candles: GOLD weekly structure ~2560-2680
const H4_CANDLES = (() => {
  let candles = [];
  let p = 2558;
  // Gradual uptrend
  for (let i = 0; i < 25; i++) {
    const drift = (Math.random() - 0.30) * 22;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 18;
    const low  = Math.min(open, close) - Math.random() * 14;
    candles.push({ open, close, high, low, vol: Math.random() * 2 + 0.6 });
    p = close;
  }
  // Consolidation near 2620-2645
  for (let i = 0; i < 25; i++) {
    const drift = (Math.random() - 0.50) * 16;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 12;
    const low  = Math.min(open, close) - Math.random() * 13;
    candles.push({ open, close, high, low, vol: Math.random() * 2.4 + 0.8 });
    p = close;
  }
  // Recent bullish push
  for (let i = 0; i < 12; i++) {
    const drift = (Math.random() - 0.35) * 18;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 14;
    const low  = Math.min(open, close) - Math.random() * 9;
    candles.push({ open, close, high, low, vol: Math.random() * 1.8 + 0.5 });
    p = close;
  }
  return candles;
})();

// H1 candles: GOLD current session ~2615-2655 (execution timeframe)
const H1_CANDLES = (() => {
  let candles = [];
  let p = 2612;
  // Morning grind up
  for (let i = 0; i < 14; i++) {
    const drift = (Math.random() - 0.38) * 8;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 7;
    const low  = Math.min(open, close) - Math.random() * 5;
    candles.push({ open, close, high, low, vol: Math.random() * 1.6 + 0.5 });
    p = close;
  }
  // Consolidation before NFP (pre-event squeeze)
  for (let i = 0; i < 10; i++) {
    const drift = (Math.random() - 0.50) * 5;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 3.5;
    const low  = Math.min(open, close) - Math.random() * 3.5;
    candles.push({ open, close, high, low, vol: Math.random() * 1.0 + 0.3 });
    p = close;
  }
  return candles;
})();

// M5 candles: GOLD intraday ~2636-2648
const M5_CANDLES = (() => {
  let candles = [];
  let p = 2636;
  for (let i = 0; i < 80; i++) {
    const drift = (Math.random() - 0.45) * 1.8;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 1.2;
    const low  = Math.min(open, close) - Math.random() * 1.2;
    candles.push({ open, close, high, low, vol: Math.random() * 1.2 + 0.3 });
    p = close;
  }
  return candles;
})();

// Session box definitions for M5 chart
const M5_SESSION_BOXES = [
  { label: 'London', startIdx: 0,  endIdx: 79, color: 'rgba(59,130,246,0.05)',  border: 'rgba(59,130,246,0.18)' },
  { label: 'NY',     startIdx: 48, endIdx: 79, color: 'rgba(245,158,11,0.06)',  border: 'rgba(245,158,11,0.22)' },
];

// Calendar event bands for H1 chart (NFP ~14:00 area, FOMC ~16:00 area)
// H1 has 24 candles; x-axis maps 09:00-16:00, so candle idx for events:
// NFP 13:30 → idx = ((13.5-9)/7)*24 ≈ 15.4 → use 16
// FOMC 15:00 → idx = ((15-9)/7)*24 ≈ 20.6 → use 21
const H1_CALENDAR_BANDS = [
  { idx: 16, label: 'NFP',  impact: 'high',   countdown: '2h 14m' },
  { idx: 21, label: 'FOMC', impact: 'high',   countdown: '4h 44m' },
];

function CandleChart({ timeframe = 'H4', overlay = null, overlayStyle = {}, currentPrice = 2641.30,
                       calendarBands = null, width = 800, height = 420 }) {
  const candles = timeframe === 'M5' ? M5_CANDLES : timeframe === 'H1' ? H1_CANDLES : H4_CANDLES;
  const padL = 8, padR = 70, padT = 14, padB = 82;
  const chartW = width - padL - padR;
  const chartH = height - padT - padB;
  const volH = 56;
  const candleH = chartH - volH - 8;

  const { min, max } = useMemo(() => {
    let mn = Infinity, mx = -Infinity;
    candles.forEach(c => { mn = Math.min(mn, c.low); mx = Math.max(mx, c.high); });
    if (overlay) {
      ['entry','sl','tp'].forEach(k => {
        if (typeof overlay[k] === 'number') { mn = Math.min(mn, overlay[k]); mx = Math.max(mx, overlay[k]); }
      });
    }
    const pad = (mx - mn) * 0.08;
    return { min: mn - pad, max: mx + pad };
  }, [timeframe, overlay && overlay.entry, overlay && overlay.sl, overlay && overlay.tp]);

  const xStep = chartW / candles.length;
  const cw    = Math.max(2, xStep * 0.7);
  const range = max - min;
  const yFor  = (p) => padT + candleH - ((p - min) / range) * candleH;

  const gridSteps = 6;
  const gridLabels = [];
  for (let i = 0; i <= gridSteps; i++) {
    const p = min + (range * i / gridSteps);
    gridLabels.push({ y: yFor(p), label: p.toFixed(0) });
  }

  const xLabels = [];
  if (timeframe === 'H4') {
    const dates = ['Apr 4','Apr 7','Apr 10','Apr 13','Apr 16','Apr 19','Apr 22','Apr 25','Apr 28'];
    const stride = candles.length / dates.length;
    dates.forEach((d, i) => xLabels.push({ x: padL + i * stride * xStep, label: d }));
  } else {
    for (let h = 9; h <= 16; h++) {
      const idx = ((h - 9) / 7) * candles.length;
      xLabels.push({ x: padL + idx * xStep, label: `${h}:00` });
    }
  }

  const volMax = Math.max(...candles.map(c => c.vol));

  return (
    <svg width="100%" height="100%" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={{display:'block'}}>
      {/* Grid */}
      {gridLabels.map((g, i) => (
        <g key={i}>
          <line x1={padL} y1={g.y} x2={padL + chartW} y2={g.y} stroke="rgba(255,255,255,0.04)" strokeWidth="1" />
          <text x={width - 6} y={g.y + 3} textAnchor="end" fontSize="10" fill="#6B7280" fontFamily="JetBrains Mono, monospace">{g.label}</text>
        </g>
      ))}
      {xLabels.map((l, i) => (
        <line key={i} x1={l.x} y1={padT} x2={l.x} y2={padT + chartH} stroke="rgba(255,255,255,0.03)" strokeWidth="1" />
      ))}

      {/* Session boxes (M5 only) */}
      {timeframe === 'M5' && M5_SESSION_BOXES.map((s, i) => {
        const x1 = padL + s.startIdx * xStep, x2 = padL + (s.endIdx + 1) * xStep;
        return (
          <g key={i}>
            <rect x={x1} y={padT} width={x2 - x1} height={candleH} fill={s.color} />
            <line x1={x1} y1={padT} x2={x1} y2={padT + candleH} stroke={s.border} strokeWidth="1" strokeDasharray="3 2" />
            <text x={x1 + 4} y={padT + 12} fontSize="9" fill={s.border} fontFamily="Inter, sans-serif" fontWeight="700" style={{textTransform:'uppercase',letterSpacing:'0.08em'}}>{s.label}</text>
          </g>
        );
      })}

      {/* Calendar event bands */}
      {calendarBands && calendarBands.map((ev, i) => {
        const evX = padL + (ev.idx / candles.length) * chartW;
        const isHigh = ev.impact === 'high';
        const lineColor = isHigh ? 'rgba(239,68,68,0.65)' : 'rgba(245,158,11,0.65)';
        const bandFill  = isHigh ? 'rgba(239,68,68,0.06)'  : 'rgba(245,158,11,0.06)';
        return (
          <g key={i}>
            <rect x={evX - 10} y={padT} width={20} height={candleH} fill={bandFill} />
            <line x1={evX} y1={padT} x2={evX} y2={padT + candleH}
                  stroke={lineColor} strokeWidth="1.5" strokeDasharray="4 3" />
            <text x={evX + 3} y={padT + 13} fontSize="9" fill={lineColor}
                  fontFamily="JetBrains Mono, monospace" fontWeight="800">{ev.label}</text>
            <text x={evX + 3} y={padT + 23} fontSize="8" fill={lineColor}
                  fontFamily="Inter, sans-serif" opacity="0.85">{ev.countdown}</text>
          </g>
        );
      })}

      {/* Candles */}
      {candles.map((c, i) => {
        const x = padL + i * xStep + xStep / 2;
        const isUp = c.close >= c.open;
        const color = isUp ? '#22C55E' : '#EF4444';
        const yHigh = yFor(c.high), yLow = yFor(c.low);
        const yOpen = yFor(c.open), yClose = yFor(c.close);
        const bodyTop = Math.min(yOpen, yClose);
        const bodyH = Math.max(1, Math.abs(yClose - yOpen));
        return (
          <g key={i}>
            <line x1={x} y1={yHigh} x2={x} y2={yLow} stroke={color} strokeWidth="1" />
            <rect x={x - cw/2} y={bodyTop} width={cw} height={bodyH} fill={color} />
          </g>
        );
      })}

      {/* Volume bars */}
      {candles.map((c, i) => {
        const x = padL + i * xStep + xStep / 2;
        const isUp = c.close >= c.open;
        const color = isUp ? 'rgba(34,197,94,0.4)' : 'rgba(239,68,68,0.4)';
        const h = (c.vol / volMax) * volH;
        return <rect key={i} x={x - cw/2} y={padT + candleH + 8 + (volH - h)} width={cw} height={h} fill={color} />;
      })}

      {/* Current price line */}
      {overlayStyle.showCurrentPriceLine !== false && (
        <g>
          <line x1={padL} x2={padL + chartW} y1={yFor(currentPrice)} y2={yFor(currentPrice)}
                stroke="#3B82F6" strokeWidth="1" strokeDasharray="3 3" opacity="0.65" />
          <rect x={padL + chartW + 2} y={yFor(currentPrice) - 9} width={62} height={18} fill="#3B82F6" rx="3" />
          <text x={padL + chartW + 33} y={yFor(currentPrice) + 4} textAnchor="middle"
                fontSize="11" fill="white" fontFamily="JetBrains Mono, monospace" fontWeight="700">
            {currentPrice.toFixed(2)}
          </text>
        </g>
      )}

      {/* Overlay lines: entry / SL / TP */}
      {overlay && overlay.entry != null && (
        <g>
          <line x1={padL} x2={padL+chartW} y1={yFor(overlay.entry)} y2={yFor(overlay.entry)}
                stroke="#3B82F6" strokeWidth="1.5" strokeDasharray={overlayStyle.solid ? null : "5 3"} />
          {overlayStyle.showLabels !== false && (
            <g>
              <rect x={padL+4} y={yFor(overlay.entry)-18} width={76} height={16} fill="#3B82F6" rx="2" />
              <text x={padL+42} y={yFor(overlay.entry)-6} textAnchor="middle"
                    fontSize="10" fill="white" fontFamily="JetBrains Mono, monospace" fontWeight="700">
                ENTRY {overlay.entry.toFixed(0)}
              </text>
            </g>
          )}
        </g>
      )}
      {overlay && overlay.sl != null && (
        <g>
          <line x1={padL} x2={padL+chartW} y1={yFor(overlay.sl)} y2={yFor(overlay.sl)}
                stroke="#EF4444" strokeWidth="1.5" strokeDasharray={overlayStyle.solid ? null : "4 3"} />
          {overlayStyle.showLabels !== false && (
            <g>
              <rect x={padL+4} y={yFor(overlay.sl)-18} width={70} height={16} fill="#EF4444" rx="2" />
              <text x={padL+39} y={yFor(overlay.sl)-6} textAnchor="middle"
                    fontSize="10" fill="white" fontFamily="JetBrains Mono, monospace" fontWeight="700">
                SL {overlay.sl.toFixed(0)}
              </text>
            </g>
          )}
        </g>
      )}
      {overlay && overlay.tp != null && (
        <g>
          <line x1={padL} x2={padL+chartW} y1={yFor(overlay.tp)} y2={yFor(overlay.tp)}
                stroke="#22C55E" strokeWidth="1.5" strokeDasharray={overlayStyle.solid ? null : "4 3"} />
          {overlayStyle.showLabels !== false && (
            <g>
              <rect x={padL+4} y={yFor(overlay.tp)-18} width={70} height={16} fill="#22C55E" rx="2" />
              <text x={padL+39} y={yFor(overlay.tp)-6} textAnchor="middle"
                    fontSize="10" fill="white" fontFamily="JetBrains Mono, monospace" fontWeight="700">
                TP {overlay.tp.toFixed(0)}
              </text>
            </g>
          )}
        </g>
      )}

      {/* X-axis labels */}
      {xLabels.map((l, i) => (
        <text key={i} x={l.x} y={padT + chartH + volH + 24}
              fontSize="10" fill="#6B7280" fontFamily="JetBrains Mono, monospace">{l.label}</text>
      ))}

      {/* Watermark */}
      <text x={padL + 8} y={padT + chartH - 6} fontSize="14"
            fill="rgba(255,255,255,0.05)" fontWeight="800" fontFamily="Inter, sans-serif">
        ◢◣ Investabl
      </text>
    </svg>
  );
}

// Sparkline for instrument cards
function Sparkline({ data, color = '#22C55E', width = 280, height = 40 }) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = (max - min) || 1;
  const step = width / (data.length - 1);
  const path = data.map((v, i) => {
    const x = i * step, y = height - ((v - min) / range) * height;
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  const area = path + ` L ${width} ${height} L 0 ${height} Z`;
  const gid = `g${color.replace('#','')}`;
  return (
    <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" className="ic-spark">
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.25" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${gid})`} />
      <path d={path} stroke={color} strokeWidth="1.5" fill="none" />
    </svg>
  );
}

// P1 split pane: H1 context (38%) + M5 execution (62%)
function MultiTFChart({ overlay, overlayStyle, currentPrice, totalWidth = 900, height = 420 }) {
  const [zoomed, setZoomed] = React.useState(false);
  if (zoomed) {
    return (
      <div style={{position:'relative', width:'100%', height:'100%'}}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6, alignItems:'center'}}
             onClick={() => setZoomed(false)}>
          <div style={{background:'rgba(59,130,246,0.15)', border:'1px solid rgba(59,130,246,0.3)', borderRadius:4, padding:'2px 8px', fontSize:10, color:'#3B82F6', cursor:'pointer', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>
            ← Split
          </div>
          <div style={{background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.25)', borderRadius:4, padding:'2px 8px', fontSize:10, color:'#22C55E', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>
            M5 · Execution
          </div>
        </div>
        <CandleChart timeframe="M5" overlay={overlay} overlayStyle={overlayStyle} currentPrice={currentPrice} width={totalWidth} height={height} />
      </div>
    );
  }
  const h1W = Math.round(totalWidth * 0.38);
  const m5W = totalWidth - h1W - 1;
  return (
    <div style={{display:'flex', width:'100%', height:'100%'}}>
      <div style={{width:'38%', position:'relative', borderRight:'1px solid rgba(255,255,255,0.06)', flexShrink:0}}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6}}>
          <div style={{background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.1)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#9CA3AF', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>H1 · Context</div>
        </div>
        <CandleChart timeframe="H1" overlay={overlay} overlayStyle={{showCurrentPriceLine:false,showLabels:false}} currentPrice={currentPrice} width={h1W} height={height} />
      </div>
      <div style={{flex:1, position:'relative', cursor:'zoom-in'}} onClick={() => setZoomed(true)}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6, pointerEvents:'none'}}>
          <div style={{background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.25)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#22C55E', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>M5 · Execution</div>
          <div style={{background:'rgba(255,255,255,0.05)', border:'1px solid rgba(255,255,255,0.08)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#6B7280', fontFamily:'Inter,sans-serif'}}>Click to zoom</div>
        </div>
        <CandleChart timeframe="M5" overlay={overlay} overlayStyle={overlayStyle} currentPrice={currentPrice} width={m5W} height={height} />
      </div>
    </div>
  );
}

// P2 Day Trader split pane: H4 structure (40%) + H1 execution (60%)
// H1 pane has calendar event bands (NFP/FOMC) — key differentiator from P1
function DayMultiTFChart({ overlay, overlayStyle, currentPrice, totalWidth = 900, height = 420 }) {
  const [zoomed, setZoomed] = React.useState(false);

  if (zoomed) {
    return (
      <div style={{position:'relative', width:'100%', height:'100%'}}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6, alignItems:'center'}}>
          <div style={{background:'rgba(59,130,246,0.15)', border:'1px solid rgba(59,130,246,0.3)', borderRadius:4, padding:'2px 8px', fontSize:10, color:'#3B82F6', cursor:'pointer', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}
               onClick={() => setZoomed(false)}>
            ← Split
          </div>
          <div style={{background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.25)', borderRadius:4, padding:'2px 8px', fontSize:10, color:'#22C55E', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>
            H1 · Execution
          </div>
        </div>
        <CandleChart timeframe="H1" overlay={overlay} overlayStyle={overlayStyle} currentPrice={currentPrice}
                     calendarBands={H1_CALENDAR_BANDS} width={totalWidth} height={height} />
      </div>
    );
  }

  const h4W = Math.round(totalWidth * 0.40);
  const h1W = totalWidth - h4W - 1;

  return (
    <div style={{display:'flex', width:'100%', height:'100%'}}>
      {/* H4 — structure pane */}
      <div style={{width:'40%', position:'relative', borderRight:'1px solid rgba(255,255,255,0.06)', flexShrink:0}}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6}}>
          <div style={{background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.1)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#9CA3AF', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>H4 · Structure</div>
        </div>
        <CandleChart timeframe="H4"
                     overlay={overlay}
                     overlayStyle={{showCurrentPriceLine:false, showLabels:false}}
                     currentPrice={currentPrice}
                     width={h4W} height={height} />
      </div>
      {/* H1 — execution pane with event bands */}
      <div style={{flex:1, position:'relative', cursor:'zoom-in'}} onClick={() => setZoomed(true)}>
        <div style={{position:'absolute', top:6, left:8, zIndex:10, display:'flex', gap:6, pointerEvents:'none'}}>
          <div style={{background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.25)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#22C55E', fontFamily:'JetBrains Mono,monospace', fontWeight:700}}>H1 · Execution</div>
          <div style={{background:'rgba(255,255,255,0.05)', border:'1px solid rgba(255,255,255,0.08)', borderRadius:4, padding:'2px 7px', fontSize:9, color:'#6B7280', fontFamily:'Inter,sans-serif'}}>Click to zoom</div>
        </div>
        <CandleChart timeframe="H1"
                     overlay={overlay}
                     overlayStyle={overlayStyle}
                     currentPrice={currentPrice}
                     calendarBands={H1_CALENDAR_BANDS}
                     width={h1W} height={height} />
      </div>
    </div>
  );
}

window.CandleChart = CandleChart;
window.MultiTFChart = MultiTFChart;
window.DayMultiTFChart = DayMultiTFChart;
window.Sparkline = Sparkline;
