/* Master AI — components */

const { useState, useEffect, useRef, useMemo } = React;

// ============== CANDLESTICK CHART ==============
const Candles = ({ data, buy = true, tps = [], sl, entry, width = 480, height = 180 }) => {
  const max = Math.max(...data.map(d => d.h));
  const min = Math.min(...data.map(d => d.l));
  const range = max - min || 1;
  const pad = 10;
  const w = width;
  const h = height;
  const cw = (w - pad * 2) / data.length;
  const y = v => pad + (1 - (v - min) / range) * (h - pad * 2);

  const pathD = data.map((d, i) => {
    const x = pad + i * cw + cw / 2;
    return `${i === 0 ? 'M' : 'L'} ${x} ${y(d.c)}`;
  }).join(' ');

  const areaD = `${pathD} L ${pad + (data.length - 1) * cw + cw / 2} ${h - pad} L ${pad + cw / 2} ${h - pad} Z`;

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height="100%" preserveAspectRatio="none" style={{display: 'block'}}>
      <defs>
        <linearGradient id={`area-${buy ? 'b' : 's'}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={buy ? '#3ddc8a' : '#ff5e7a'} stopOpacity="0.3" />
          <stop offset="100%" stopColor={buy ? '#3ddc8a' : '#ff5e7a'} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaD} fill={`url(#area-${buy ? 'b' : 's'})`} />
      {data.map((d, i) => {
        const x = pad + i * cw + cw / 2;
        const up = d.c >= d.o;
        const color = up ? '#3ddc8a' : '#ff5e7a';
        return (
          <g key={i}>
            <line x1={x} x2={x} y1={y(d.h)} y2={y(d.l)} stroke={color} strokeWidth="1" opacity="0.7" />
            <rect
              x={x - cw * 0.32}
              y={y(Math.max(d.o, d.c))}
              width={cw * 0.64}
              height={Math.max(1, Math.abs(y(d.o) - y(d.c)))}
              fill={color}
              opacity="0.9"
            />
          </g>
        );
      })}
      <path d={pathD} stroke="#d4a84a" strokeWidth="1.2" fill="none" opacity="0.6" strokeDasharray="2 3" />
      {/* entry / sl / tps */}
      {entry != null && (
        <g>
          <line x1={pad} x2={w - pad} y1={y(entry)} y2={y(entry)} stroke="#f5d67a" strokeWidth="1" strokeDasharray="4 4" opacity="0.9" />
          <rect x={w - 52} y={y(entry) - 8} width="44" height="16" fill="#f5d67a" rx="3" />
          <text x={w - 30} y={y(entry) + 4} textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono" fill="#1a1405" fontWeight="600">ENTRY</text>
        </g>
      )}
      {sl != null && (
        <g>
          <line x1={pad} x2={w - pad} y1={y(sl)} y2={y(sl)} stroke="#ff5e7a" strokeWidth="1" strokeDasharray="2 3" opacity="0.7" />
          <rect x={w - 40} y={y(sl) - 8} width="32" height="16" fill="rgba(255, 94, 122, 0.2)" stroke="#ff5e7a" rx="3" />
          <text x={w - 24} y={y(sl) + 4} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="#ff5e7a" fontWeight="600">SL</text>
        </g>
      )}
      {tps.map((tp, i) => (
        <g key={i}>
          <line x1={pad} x2={w - pad} y1={y(tp)} y2={y(tp)} stroke="#3ddc8a" strokeWidth="1" strokeDasharray="2 3" opacity={0.4 + 0.2 * i} />
          <rect x={w - 40} y={y(tp) - 8} width="32" height="16" fill="rgba(61, 220, 138, 0.15)" stroke="#3ddc8a" rx="3" opacity={0.6 + 0.1 * i} />
          <text x={w - 24} y={y(tp) + 4} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="#3ddc8a" fontWeight="600">TP{i + 1}</text>
        </g>
      ))}
    </svg>
  );
};

// Generate candlestick data
const genCandles = (n, trend = 1, start = 100) => {
  const arr = [];
  let p = start;
  for (let i = 0; i < n; i++) {
    const o = p;
    const drift = trend * (0.3 + Math.random() * 0.4);
    const vol = 0.6 + Math.random() * 0.8;
    const c = o + drift + (Math.random() - 0.5) * vol * 2;
    const h = Math.max(o, c) + Math.random() * vol;
    const l = Math.min(o, c) - Math.random() * vol;
    arr.push({ o, c, h, l });
    p = c;
  }
  return arr;
};

// ============== CONFIDENCE RING ==============
const ConfidenceRing = ({ value = 87, size = 80 }) => {
  const r = size / 2 - 6;
  const c = 2 * Math.PI * r;
  const dash = c * (value / 100);
  return (
    <svg width={size} height={size} style={{transform: 'rotate(-90deg)'}}>
      <circle cx={size/2} cy={size/2} r={r} stroke="rgba(255,255,255,0.06)" strokeWidth="4" fill="none" />
      <circle cx={size/2} cy={size/2} r={r} stroke="url(#goldGrad)" strokeWidth="4" fill="none"
        strokeDasharray={`${dash} ${c}`} strokeLinecap="round" />
      <defs>
        <linearGradient id="goldGrad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#f5d67a" />
          <stop offset="100%" stopColor="#8a6a1f" />
        </linearGradient>
      </defs>
    </svg>
  );
};

// ============== SIGNAL CARD (for carousel / hero) ==============
const SignalCard = ({ pair, action, flags, entry, sl, tps, confidence, pattern, style, candles, note }) => {
  const isBuy = action === 'BUY';
  return (
    <div style={{display: 'flex', flexDirection: 'column', height: '100%'}}>
      <div className="signal-header">
        <div className="signal-pair">
          <div className="pair-flags">
            {flags.map((f, i) => <div key={i} className={`flag ${f}`}>{f === 'xau' ? 'Au' : f.toUpperCase().slice(0, 2)}</div>)}
          </div>
          {pair}
        </div>
        <div className={`badge ${isBuy ? 'badge-buy' : 'badge-sell'}`}>
          <span style={{width: 6, height: 6, borderRadius: '50%', background: 'currentColor'}}></span>
          {action} • {style}
        </div>
      </div>

      <div className="mini-chart" style={{flex: 1, minHeight: 180}}>
        <Candles data={candles} buy={isBuy} tps={tps} sl={sl} entry={entry} />
      </div>

      <div className="signal-grid">
        <div className="signal-cell gold">
          <div className="signal-cell-label">Entry</div>
          <div className="signal-cell-value">{entry.toFixed(pair.includes('JPY') ? 2 : 4)}</div>
        </div>
        <div className="signal-cell sl">
          <div className="signal-cell-label">Stop Loss</div>
          <div className="signal-cell-value">{sl.toFixed(pair.includes('JPY') ? 2 : 4)}</div>
        </div>
        <div className="signal-cell tp1">
          <div className="signal-cell-label">TP1 / TP2 / TP3</div>
          <div className="signal-cell-value" style={{fontSize: 11}}>
            {tps.map(t => t.toFixed(pair.includes('JPY') ? 1 : 3).slice(-5)).join(' · ')}
          </div>
        </div>
      </div>

      {pattern && (
        <div style={{
          marginTop: 14,
          padding: '12px 14px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid var(--border)',
          borderRadius: 10,
          display: 'flex',
          gap: 12,
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <div>
            <div style={{fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 3}}>Pattern</div>
            <div style={{fontSize: 13, color: 'var(--ink)'}}>{pattern}</div>
          </div>
          <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
            <ConfidenceRing value={confidence} size={48} />
            <div>
              <div style={{fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 3}}>Confidence</div>
              <div style={{fontSize: 18, fontFamily: 'JetBrains Mono', color: 'var(--gold-1)', fontWeight: 500}}>{confidence}<span style={{fontSize: 11, color: 'var(--ink-faint)'}}> / 100</span></div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============== HERO 3D STACK ==============
const HeroStack = () => {
  const candles = useMemo(() => genCandles(30, 0.8, 2680), []);
  const [tilt, setTilt] = useState({ x: 0, y: 0 });

  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width - 0.5) * 2;
    const y = ((e.clientY - rect.top) / rect.height - 0.5) * 2;
    setTilt({ x: -y * 4, y: x * 6 });
  };
  const onLeave = () => setTilt({ x: 0, y: 0 });

  return (
    <div className="hero-right" onMouseMove={onMove} onMouseLeave={onLeave}
      style={{transform: `rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`}}>

      {/* Main signal card */}
      <div className="stack-card main">
        <SignalCard
          pair="XAU/USD"
          action="BUY"
          flags={['xau', 'usd']}
          entry={2684.50}
          sl={2678.20}
          tps={[2692.00, 2701.50, 2715.00]}
          confidence={87}
          pattern="Bullish Flag · H1"
          style="Intraday"
          candles={candles}
        />
      </div>

      {/* Back layer: confidence */}
      <div className="stack-card back">
        <div style={{fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-faint)'}}>Signal Strength</div>
        <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
          <ConfidenceRing value={87} size={64} />
          <div style={{textAlign: 'right'}}>
            <div style={{fontSize: 22, fontFamily: 'JetBrains Mono', color: 'var(--gold-1)', fontWeight: 500, letterSpacing: '-0.02em'}}>87<span style={{fontSize: 11, color: 'var(--ink-faint)'}}>/100</span></div>
            <div style={{fontSize: 10, color: 'var(--buy)', letterSpacing: '0.08em', textTransform: 'uppercase'}}>HIGH CONFLUENCE</div>
          </div>
        </div>
      </div>

      {/* Behind duplicate */}
      <div className="stack-card behind" />

      {/* Side: multi-timeframe chip */}
      <div className="stack-card side">
        <div style={{fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 12}}>Multi-timeframe</div>
        <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
          {[
            {tf: 'M5',  trend: 'BULL',  c: 'var(--buy)'},
            {tf: 'M15', trend: 'BULL',  c: 'var(--buy)'},
            {tf: 'H1',  trend: 'BULL',  c: 'var(--buy)'},
            {tf: 'H4',  trend: 'RANGE', c: 'var(--neutral)'},
          ].map(r => (
            <div key={r.tf} className="tf-chip" style={{justifyContent: 'space-between'}}>
              <span style={{color: 'var(--ink)', fontWeight: 500}}>{r.tf}</span>
              <span style={{color: r.c, fontSize: 10, letterSpacing: '0.1em'}}>● {r.trend}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============== 3D CAROUSEL ==============
const Carousel3D = ({ signals }) => {
  const [active, setActive] = useState(0);
  const n = signals.length;

  const next = () => setActive((a) => (a + 1) % n);
  const prev = () => setActive((a) => (a - 1 + n) % n);

  useEffect(() => {
    const id = setInterval(next, 5000);
    return () => clearInterval(id);
  }, [n]);

  return (
    <div className="carousel-wrap">
      <button className="carousel-arrow left" onClick={prev} aria-label="Prev">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
      </button>
      <div className="carousel-stage">
        {signals.map((s, i) => {
          let offset = i - active;
          if (offset > n / 2) offset -= n;
          if (offset < -n / 2) offset += n;
          const abs = Math.abs(offset);
          const tx = offset * 280;
          const tz = -abs * 240;
          const ry = offset * -22;
          const op = abs > 2 ? 0 : 1 - abs * 0.25;
          return (
            <div
              key={i}
              className={`carousel-card ${i === active ? 'active' : ''}`}
              style={{
                transform: `translate(-50%, -50%) translate3d(${tx}px, 0, ${tz}px) rotateY(${ry}deg)`,
                opacity: op,
                zIndex: 100 - abs,
                pointerEvents: abs <= 1 ? 'auto' : 'none',
              }}
              onClick={() => setActive(i)}
            >
              <SignalCard {...s} />
            </div>
          );
        })}
      </div>
      <button className="carousel-arrow right" onClick={next} aria-label="Next">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
      </button>
      <div className="carousel-nav">
        {signals.map((_, i) => (
          <button key={i} className={`carousel-dot ${i === active ? 'active' : ''}`} onClick={() => setActive(i)} />
        ))}
      </div>
    </div>
  );
};

// ============== UPLOAD → ANALYSIS DEMO ==============
const AnalysisDemo = () => {
  const [style, setStyle] = useState('Intraday');
  const [uploaded, setUploaded] = useState(false);
  const [analyzing, setAnalyzing] = useState(false);
  const [done, setDone] = useState(false);
  const [lineIdx, setLineIdx] = useState(0);
  const candles = useMemo(() => genCandles(50, -0.5, 1.0850), []);

  const steps = [
    'Reading chart structure…',
    'Detecting support & resistance',
    'Pattern match: Double Top',
    'Computing EMA confluence (21 / 50 / 200)',
    'Confirming H4 bias',
    'Calibrating Intraday SL/TP envelope',
    'Generating entry zone',
    'Signal ready',
  ];

  const run = () => {
    setUploaded(true);
    setDone(false);
    setAnalyzing(true);
    setLineIdx(0);
  };

  const reset = () => {
    setUploaded(false);
    setDone(false);
    setAnalyzing(false);
    setLineIdx(0);
  };

  useEffect(() => {
    if (!analyzing) return;
    if (lineIdx >= steps.length) {
      setAnalyzing(false);
      setDone(true);
      return;
    }
    const t = setTimeout(() => setLineIdx(l => l + 1), 450);
    return () => clearTimeout(t);
  }, [analyzing, lineIdx]);

  return (
    <div className="demo-wrap">
      {/* LEFT panel: input */}
      <div className="demo-panel">
        <div className="demo-panel-title"><span className="dot"></span>INPUT — EUR/USD H1</div>

        <div className="chart-preview">
          {/* subtle candles preview */}
          <Candles data={candles} buy={false} tps={[]} sl={null} entry={null} width={500} height={320} />
          <div className={`chart-preview-overlay ${uploaded ? 'hidden' : ''}`}>
            <div style={{textAlign: 'center'}}>
              <div style={{
                width: 72, height: 72,
                margin: '0 auto 16px',
                borderRadius: 16,
                background: 'linear-gradient(135deg, rgba(212, 168, 74, 0.15), rgba(212, 168, 74, 0.02))',
                border: '1px solid var(--border-strong)',
                display: 'grid', placeItems: 'center',
                color: 'var(--gold-1)',
              }}>
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                  <path d="M12 3v14m-5-9l5-5 5 5M5 21h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div style={{fontSize: 16, marginBottom: 6, color: 'var(--ink)'}}>Drop a chart screenshot</div>
              <div style={{fontSize: 12, color: 'var(--ink-faint)', fontFamily: 'JetBrains Mono'}}>PNG · JPG · up to 4 timeframes</div>
            </div>
          </div>
        </div>

        <div style={{marginBottom: 16}}>
          <div style={{fontSize: 10, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 10, fontFamily: 'JetBrains Mono'}}>TRADING STYLE</div>
          <div className="style-picker">
            {[
              {k: 'Scalping', sl: '10-15 pip'},
              {k: 'Intraday', sl: '20-40 pip'},
              {k: 'Swing',    sl: '50-100'},
              {k: 'Position', sl: '100-200'},
            ].map(s => (
              <div key={s.k} className={`style-chip ${style === s.k ? 'active' : ''}`} onClick={() => setStyle(s.k)}>
                {s.k}
                <div className="style-chip-label">{s.sl}</div>
              </div>
            ))}
          </div>
        </div>

        <button className="btn btn-primary" style={{width: '100%', justifyContent: 'center'}} onClick={uploaded ? reset : run}>
          {uploaded ? (done ? 'Run again' : 'Analyzing…') : 'Analyze chart'}
        </button>
      </div>

      {/* RIGHT panel: output */}
      <div className="demo-panel">
        <div className="demo-panel-title"><span className="dot"></span>MASTER AI OUTPUT</div>

        {!uploaded && (
          <div style={{display: 'grid', placeItems: 'center', height: 440, textAlign: 'center'}}>
            <div>
              <div style={{fontSize: 13, color: 'var(--ink-faint)', fontFamily: 'JetBrains Mono', letterSpacing: '0.08em'}}>
                AWAITING CHART · <span style={{color: 'var(--gold-2)'}}>●</span> IDLE
              </div>
            </div>
          </div>
        )}

        {uploaded && (
          <div className="analysis-scroll">
            {steps.slice(0, lineIdx).map((s, i) => (
              <div key={i} className={`analysis-line ${i < lineIdx - 1 || done ? 'done' : ''}`}>
                <span className="chev">{i < lineIdx - 1 || done ? '✓' : '›'}</span>
                <span>{s}</span>
              </div>
            ))}

            {done && (
              <div className="analysis-result" style={{marginTop: 16}}>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14, paddingBottom: 14, borderBottom: '1px dashed var(--border)'}}>
                  <div>
                    <div style={{fontSize: 11, color: 'var(--ink-faint)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4}}>Primary Setup · {style}</div>
                    <div style={{fontFamily: 'JetBrains Mono', fontSize: 18, letterSpacing: '0.02em'}}>EUR/USD</div>
                  </div>
                  <div className="badge badge-sell">
                    <span style={{width: 6, height: 6, borderRadius: '50%', background: 'currentColor'}}></span>
                    SELL · Limit
                  </div>
                </div>

                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14}}>
                  <div className="signal-cell gold"><div className="signal-cell-label">Entry Zone</div><div className="signal-cell-value">1.0865 – 1.0872</div></div>
                  <div className="signal-cell sl"><div className="signal-cell-label">Stop Loss</div><div className="signal-cell-value">1.0895</div></div>
                  <div className="signal-cell tp1"><div className="signal-cell-label">TP1</div><div className="signal-cell-value">1.0840</div></div>
                  <div className="signal-cell tp1"><div className="signal-cell-label">TP2 / TP3</div><div className="signal-cell-value" style={{fontSize: 11}}>1.0818 · 1.0790</div></div>
                </div>

                <div style={{display: 'flex', gap: 14, alignItems: 'center', padding: '12px 0', borderTop: '1px dashed var(--border)'}}>
                  <ConfidenceRing value={82} size={52} />
                  <div style={{flex: 1}}>
                    <div style={{fontSize: 11, color: 'var(--ink-faint)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 3}}>Pattern</div>
                    <div style={{fontSize: 13}}>Double Top · H1 · Bearish divergence on H4 RSI</div>
                  </div>
                  <div style={{textAlign: 'right'}}>
                    <div style={{fontFamily: 'JetBrains Mono', fontSize: 22, color: 'var(--gold-1)', fontWeight: 500}}>82</div>
                    <div style={{fontSize: 10, color: 'var(--buy)', letterSpacing: '0.08em', textTransform: 'uppercase'}}>CONFIDENCE</div>
                  </div>
                </div>

                <div style={{marginTop: 10, padding: '10px 12px', background: 'rgba(74, 140, 255, 0.06)', border: '1px solid rgba(74, 140, 255, 0.18)', borderRadius: 8, fontSize: 12, color: 'var(--ink-dim)', lineHeight: 1.5}}>
                  <span style={{color: 'var(--neutral)', fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.1em'}}>AI·</span>{' '}
                  Price rejected 1.0895 twice with weakening H4 momentum. Scale in at the 1.0865–1.0872 pullback; invalidate above 1.0900.
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

// ============== MARQUEE TICKER ==============
const Ticker = () => {
  const items = [
    {pair: 'XAU/USD', pct: '+1.24%', dir: 'up', conf: '87'},
    {pair: 'EUR/USD', pct: '-0.42%', dir: 'down', conf: '82'},
    {pair: 'GBP/JPY', pct: '+0.88%', dir: 'up', conf: '76'},
    {pair: 'BTC/USD', pct: '+3.12%', dir: 'up', conf: '91'},
    {pair: 'USD/JPY', pct: '-0.18%', dir: 'down', conf: '68'},
    {pair: 'NAS100',  pct: '+0.94%', dir: 'up', conf: '79'},
    {pair: 'ETH/USD', pct: '+2.04%', dir: 'up', conf: '84'},
    {pair: 'USOIL',   pct: '-1.10%', dir: 'down', conf: '72'},
    {pair: 'AUD/USD', pct: '+0.26%', dir: 'up', conf: '66'},
    {pair: 'SPX500',  pct: '+0.52%', dir: 'up', conf: '80'},
  ];
  const doubled = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {doubled.map((it, i) => (
          <div key={i} className="marquee-item">
            <span className="pair">{it.pair}</span>
            <span className={`pct ${it.dir}`}>{it.pct}</span>
            <span style={{color: 'var(--ink-faint)', fontSize: 11}}>AI {it.conf}</span>
            <span style={{color: 'var(--ink-faint)'}}>—</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// Expose to global scope
Object.assign(window, { Candles, ConfidenceRing, SignalCard, HeroStack, Carousel3D, AnalysisDemo, Ticker, genCandles });
