// SVG candlestick chart — Swing & Position Trader persona (GOLD ~2400-2720)
const { useMemo } = React;

// 1W candles: GOLD multi-month uptrend ~2300 → 2640 (52 weeks)
const W1_CANDLES = (() => {
  const candles = []; let p = 2310;
  // Phase 1: Slow grind up (20 weeks)
  for (let i = 0; i < 20; i++) {
    const drift = (Math.random() - 0.35) * 38;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 28;
    const low  = Math.min(open, close) - Math.random() * 22;
    candles.push({ open, close, high, low, vol: Math.random() * 2 + 0.6 });
    p = close;
  }
  // Phase 2: Consolidation (12 weeks)
  for (let i = 0; i < 12; i++) {
    const drift = (Math.random() - 0.50) * 30;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 20;
    const low  = Math.min(open, close) - Math.random() * 20;
    candles.push({ open, close, high, low, vol: Math.random() * 1.5 + 0.4 });
    p = close;
  }
  // Phase 3: Breakout uptrend (20 weeks)
  for (let i = 0; i < 20; i++) {
    const drift = (Math.random() - 0.32) * 42;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 30;
    const low  = Math.min(open, close) - Math.random() * 18;
    candles.push({ open, close, high, low, vol: Math.random() * 2.5 + 0.8 });
    p = close;
  }
  return candles;
})();

// 1D candles: GOLD recent 90 days ~2520 → 2641 structure
const D1_CANDLES = (() => {
  const candles = []; let p = 2518;
  // Uptrend with pullback
  for (let i = 0; i < 35; i++) {
    const drift = (Math.random() - 0.38) * 16;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 12;
    const low  = Math.min(open, close) - Math.random() * 8;
    candles.push({ open, close, high, low, vol: Math.random() * 2 + 0.5 });
    p = close;
  }
  // Consolidation
  for (let i = 0; i < 28; i++) {
    const drift = (Math.random() - 0.50) * 12;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 9;
    const low  = Math.min(open, close) - Math.random() * 10;
    candles.push({ open, close, high, low, vol: Math.random() * 1.6 + 0.4 });
    p = close;
  }
  // Recent bullish push
  for (let i = 0; i < 27; i++) {
    const drift = (Math.random() - 0.36) * 14;
    const open = p, close = p + drift;
    const high = Math.max(open, close) + Math.random() * 10;
    const low  = Math.min(open, close) - Math.random() * 7;
    candles.push({ open, close, high, low, vol: Math.random() * 1.8 + 0.5 });
    p = close;
  }
  return candles;
})();

// 4H candles — same structure as GOLD H4 from v4
const H4_CANDLES = (() => {
  const candles = []; let p = 2558;
  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;
  }
  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;
  }
  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;
})();

function CandleChart({ timeframe = '1D', overlay = null, overlayStyle = {}, currentPrice = 2641.30, width = 800, height = 420 }) {
  const candles = timeframe === '1W' ? W1_CANDLES : timeframe === '4H' ? H4_CANDLES : D1_CANDLES;
  const padL = 8, padR = 70, padT = 14, padB = 82;
  const chartW = width - padL - padR;
  const chartH = height - padT - padB;
  const volH = 52;
  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(1.5, xStep * 0.65);
  const range = max - min;
  const yFor  = (p) => padT + candleH - ((p - min) / range) * candleH;

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

  const xLabels = [];
  if (timeframe === '1W') {
    const months = ['May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May'];
    const stride = candles.length / months.length;
    months.forEach((m, i) => xLabels.push({ x: padL + i * stride * xStep, label: m }));
  } else if (timeframe === '1D') {
    const dates = ['Feb 3','Feb 17','Mar 3','Mar 17','Mar 31','Apr 14','Apr 28'];
    const stride = candles.length / dates.length;
    dates.forEach((d, i) => xLabels.push({ x: padL + i * stride * xStep, label: d }));
  } else {
    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 }));
  }

  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'}}>
      {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" />
      ))}

      {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>
        );
      })}

      {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} />;
      })}

      {overlayStyle && 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 && 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 && overlayStyle.solid ? null : "5 3"} />
          {(!overlayStyle || 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 && overlayStyle.solid ? null : "4 3"} />
          {(!overlayStyle || 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 && overlayStyle.solid ? null : "4 3"} />
          {(!overlayStyle || 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>
      )}

      {xLabels.map((l, i) => (
        <text key={i} x={l.x} y={padT+chartH+volH+22} fontSize="10" fill="#6B7280" fontFamily="JetBrains Mono,monospace">{l.label}</text>
      ))}
      <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>
  );
}

// Swing + Position split: 1W structure (40%) + 1D execution (60%)
function SwingMultiTFChart({ 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}}>1D · Entry</div>
        </div>
        <CandleChart timeframe="1D" overlay={overlay} overlayStyle={overlayStyle} currentPrice={currentPrice} width={totalWidth} height={height} />
      </div>
    );
  }

  const w1W = Math.round(totalWidth * 0.38);
  const d1W = totalWidth - w1W - 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}}>1W · Macro Structure</div>
        </div>
        <CandleChart timeframe="1W" overlay={null} overlayStyle={{showCurrentPriceLine:false, showLabels:false}} currentPrice={currentPrice} width={w1W} 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}}>1D · Entry &amp; Thesis</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="1D" overlay={overlay} overlayStyle={overlayStyle} currentPrice={currentPrice} width={d1W} height={height} />
      </div>
    </div>
  );
}

// Sparkline for watchlist
function Sparkline({ data, color = '#22C55E', width = 80, height = 32 }) {
  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(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" className="ic-spark">
      <path d={path} stroke={color} strokeWidth="1.5" fill="none" />
    </svg>
  );
}

window.CandleChart = CandleChart;
window.SwingMultiTFChart = SwingMultiTFChart;
window.Sparkline = Sparkline;
