// SVG candlestick chart drawn from realistic dummy GOLD H4 data
const { useMemo, useEffect, useRef, useState } = React;

// Generate realistic OHLC candle data for GOLD around 4600-4650 range
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;
}

// Pre-generate so the chart looks consistent across renders
const H4_CANDLES = (() => {
  // Roughly mimic the screenshot — drift up then crash down
  let candles = [];
  let p = 4500;
  // Up phase
  for (let i = 0; i < 25; i++) {
    const drift = (Math.random() - 0.3) * 18;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 15;
    const low = Math.min(open, close) - Math.random() * 12;
    candles.push({ open, close, high, low, vol: Math.random() * 2 + 0.6 });
    p = close;
  }
  // Down phase
  for (let i = 0; i < 25; i++) {
    const drift = (Math.random() - 0.65) * 22;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 14;
    const low = Math.min(open, close) - Math.random() * 16;
    candles.push({ open, close, high, low, vol: Math.random() * 2.4 + 0.8 });
    p = close;
  }
  // Recovery tail
  for (let i = 0; i < 12; i++) {
    const drift = (Math.random() - 0.4) * 14;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 10;
    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;
})();

const M5_CANDLES = (() => {
  // Tight range around 4615 with subtle drift
  let candles = [];
  let p = 4612;
  for (let i = 0; i < 80; i++) {
    const drift = (Math.random() - 0.45) * 2.4;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 1.5;
    const low = Math.min(open, close) - Math.random() * 1.5;
    candles.push({ open, close, high, low, vol: Math.random() * 1.2 + 0.3 });
    p = close;
  }
  return candles;
})();

const H1_CANDLES = (() => {
  // ~24 H1 candles providing higher-TF context, trending up then consolidating
  let candles = [];
  let p = 4580;
  for (let i = 0; i < 14; i++) {
    const drift = (Math.random() - 0.35) * 12;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 9;
    const low = Math.min(open, close) - Math.random() * 7;
    candles.push({ open, close, high, low, vol: Math.random() * 1.6 + 0.5 });
    p = close;
  }
  // Consolidation near 4612+
  for (let i = 0; i < 10; i++) {
    const drift = (Math.random() - 0.5) * 8;
    const open = p;
    const close = p + drift;
    const high = Math.max(open, close) + Math.random() * 5;
    const low = Math.min(open, close) - Math.random() * 5;
    candles.push({ open, close, high, low, vol: Math.random() * 1.2 + 0.4 });
    p = close;
  }
  return candles;
})();

// Session box definitions for M5 chart (80 candles ≈ 09:00–15:40 London time)
// London session spans most of the chart; NY opens at candle ~48 (13:00 LDN)
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)' },
];

function CandleChart({ timeframe = 'H4', overlay = null, overlayStyle = {}, currentPrice = 4615.30, width = 800, height = 420 }) {
  const candles = timeframe === 'M5' ? M5_CANDLES : timeframe === 'H1' ? H1_CANDLES : H4_CANDLES;
  const padL = 8, padR = 70, padT = 12, padB = 80;
  const chartW = width - padL - padR;
  const chartH = height - padT - padB;
  const volH = 60;
  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); });
    // Expand range to include overlay levels (SL/TP/entry) so they're always visible on chart
    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;

  // Y-axis labels (price grid)
  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) });
  }

  // X-axis labels (date stride)
  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` });
    }
  }

  // Volume bars
  const volMax = Math.max(...candles.map(c => c.vol));
  const volTop = padT + candleH + 8;

  return (
    <svg width="100%" height="100%" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={{display:'block'}}>
      {/* Background 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}.00</text>
        </g>
      ))}

      {/* Vertical grid */}
      {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;
        const 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>
        );
      })}

      {/* 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);
        const yLow = yFor(c.low);
        const yOpen = yFor(c.open);
        const 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 + label */}
      {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.6"
          />
          <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>
      )}

      {/* Overlays: entry / SL / TP lines */}
      {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={70} height={16} fill="#3B82F6" rx="2" />
              <text x={padL + 39} 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 + 26} 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.06)" fontWeight="800" fontFamily="Inter, sans-serif">
        ◢◣ Investabl
      </text>
    </svg>
  );
}

// Tiny sparkline for instrument cards
function Sparkline({ data, color = '#22C55E', width = 280, height = 40 }) {
  const min = Math.min(...data);
  const 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;
    const y = height - ((v - min) / range) * height;
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  // area fill under line
  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>
  );
}

// Multi-TF split pane: H1 (context, left 38%) + M5 (execution, right 62%)
// Clicking the M5 pane zooms it to full width; clicking again restores split.
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%', gap:0}}>
      {/* H1 — context pane */}
      <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>
      {/* M5 — execution pane (click to zoom) */}
      <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>
  );
}

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