// Trade Axis — shared visual components (logo, chart, panels)
// NOTE: Global React; exports via window at bottom.

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

/* ---------- Logo mark (inspired by original) ---------- */
function LogoMark({ size = 28 }) {
  return (
    <svg className="ta-logo-mark" viewBox="0 0 64 64" width={size} height={size} aria-hidden>
      <defs>
        <linearGradient id="ta-axis" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#2B5BB8" />
          <stop offset=".5" stopColor="#0B1628" />
          <stop offset="1" stopColor="#2B5BB8" />
        </linearGradient>
      </defs>
      {/* diagonal line chart */}
      <polyline points="4,42 28,30 40,22 60,18" fill="none" stroke="var(--ta-blue)" strokeWidth="1.6" opacity=".7" />
      {/* dots */}
      <circle cx="4" cy="42" r="3" fill="var(--ta-green)" />
      <circle cx="60" cy="18" r="3" fill="var(--ta-green)" />
      <circle cx="22" cy="44" r="2" fill="var(--ta-green)" />
      {/* candle body 1 (green up) */}
      <rect x="17" y="30" width="6" height="14" fill="var(--ta-green)" rx="1"/>
      <line x1="20" y1="24" x2="20" y2="30" stroke="var(--ta-green)" strokeWidth="1.4"/>
      <line x1="20" y1="44" x2="20" y2="50" stroke="var(--ta-green)" strokeWidth="1.4"/>
      {/* candle body 2 (blue up) */}
      <rect x="29" y="22" width="6" height="14" fill="var(--ta-blue)" rx="1"/>
      <line x1="32" y1="16" x2="32" y2="22" stroke="var(--ta-blue)" strokeWidth="1.4"/>
      <line x1="32" y1="36" x2="32" y2="42" stroke="var(--ta-blue)" strokeWidth="1.4"/>
      {/* candle body 3 (green up) */}
      <rect x="41" y="18" width="6" height="14" fill="var(--ta-green)" rx="1"/>
      <line x1="44" y1="12" x2="44" y2="18" stroke="var(--ta-green)" strokeWidth="1.4"/>
      <line x1="44" y1="32" x2="44" y2="38" stroke="var(--ta-green)" strokeWidth="1.4"/>
      {/* central axis */}
      <path d="M32 2 L34 32 L32 62 L30 32 Z" fill="url(#ta-axis)" />
    </svg>
  );
}

function Logo() {
  return (
    <div className="ta-logo">
      <LogoMark size={28} />
      <span><span className="wd-1">Trade</span> <span className="wd-2">Axis</span></span>
    </div>
  );
}

/* ---------- Live candles chart ---------- */
// Generates a deterministic candle series that animates subtly
function useCandles(count = 40, seed = 7) {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1400);
    return () => clearInterval(id);
  }, []);
  return useMemo(() => {
    // simple LCG for deterministic "market"
    let s = seed + tick;
    const rnd = () => {
      s = (s * 1103515245 + 12345) & 0x7fffffff;
      return s / 0x7fffffff;
    };
    const candles = [];
    let price = 100;
    for (let i = 0; i < count; i++) {
      const drift = (rnd() - 0.48) * 2.5;
      const open = price;
      const close = Math.max(50, open + drift);
      const high = Math.max(open, close) + rnd() * 1.2;
      const low = Math.min(open, close) - rnd() * 1.2;
      candles.push({ open, close, high, low });
      price = close;
    }
    return candles;
  }, [tick, count, seed]);
}

function LiveChart({ width = 640, height = 320, symbol = "XAUUSD" }) {
  const candles = useCandles(48, 11);
  const max = Math.max(...candles.map(c => c.high));
  const min = Math.min(...candles.map(c => c.low));
  const pad = 20;
  const w = width - pad * 2;
  const h = height - pad * 2;
  const cw = w / candles.length;
  const y = (v) => pad + h - ((v - min) / (max - min || 1)) * h;

  const last = candles[candles.length - 1];
  const prev = candles[candles.length - 2] || last;
  const bid = (4834 + last.close / 100).toFixed(2);
  const ask = (4835 + last.close / 100).toFixed(2);
  const delta = ((last.close - prev.close)).toFixed(2);

  return (
    <svg viewBox={`0 0 ${width} ${height}`} width="100%" style={{ display: "block" }}>
      {/* gridlines */}
      {[0.2, 0.4, 0.6, 0.8].map(p => (
        <line key={p} x1={pad} x2={width - pad} y1={pad + h * p} y2={pad + h * p}
              stroke="var(--line)" strokeDasharray="2 4" opacity=".6" />
      ))}
      {/* candles */}
      {candles.map((c, i) => {
        const cx = pad + i * cw + cw / 2;
        const up = c.close >= c.open;
        const color = up ? "var(--ta-green)" : "var(--ta-red)";
        const bodyTop = y(Math.max(c.open, c.close));
        const bodyBot = y(Math.min(c.open, c.close));
        return (
          <g key={i}>
            <line x1={cx} x2={cx} y1={y(c.high)} y2={y(c.low)} stroke={color} strokeWidth="1" />
            <rect x={cx - cw * 0.35} y={bodyTop} width={cw * 0.7} height={Math.max(1.5, bodyBot - bodyTop)} fill={color} rx="0.5" />
          </g>
        );
      })}
      {/* price line */}
      <line x1={pad} x2={width - pad} y1={y(last.close)} y2={y(last.close)}
            stroke="var(--accent)" strokeDasharray="3 3" opacity=".8" />
      <g transform={`translate(${width - pad - 70}, ${y(last.close) - 11})`}>
        <rect width="64" height="22" rx="4" fill="var(--accent)" />
        <text x="32" y="15" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="11" fontWeight="600" fill="white">
          {last.close.toFixed(2)}
        </text>
      </g>
      {/* symbol */}
      <text x={pad + 8} y={pad + 18} fontFamily="JetBrains Mono" fontSize="12" fill="var(--text-2)" fontWeight="500">
        {symbol} · M1
      </text>
      <text x={pad + 8} y={pad + 36} fontFamily="JetBrains Mono" fontSize="10" fill={delta >= 0 ? "var(--ta-green)" : "var(--ta-red)"}>
        bid {bid} · ask {ask} · {delta >= 0 ? "+" : ""}{delta}
      </text>
    </svg>
  );
}

/* ---------- Mini sparkline equity curve ---------- */
function Sparkline({ width = 260, height = 70, trend = "up", seed = 3 }) {
  const pts = useMemo(() => {
    let s = seed;
    const rnd = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    const n = 40;
    const arr = [];
    let v = 50;
    for (let i = 0; i < n; i++) {
      const drift = (rnd() - (trend === "up" ? 0.35 : 0.65)) * 5;
      v = Math.max(10, Math.min(90, v + drift));
      arr.push(v);
    }
    return arr;
  }, [trend, seed]);
  const max = Math.max(...pts), min = Math.min(...pts);
  const path = pts.map((p, i) => {
    const x = (i / (pts.length - 1)) * width;
    const y = height - ((p - min) / (max - min || 1)) * (height - 6) - 3;
    return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  const color = trend === "up" ? "var(--ta-green)" : "var(--ta-red)";
  return (
    <svg viewBox={`0 0 ${width} ${height}`} width="100%" style={{ display: "block" }}>
      <defs>
        <linearGradient id={`sp-${seed}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity=".3" />
          <stop offset="1" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${path} L${width},${height} L0,${height} Z`} fill={`url(#sp-${seed})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="1.8" />
    </svg>
  );
}

/* ---------- Status pill ---------- */
function StatusPill({ kind = "active", label }) {
  const color = kind === "active" ? "var(--ta-green)" : "var(--ta-red)";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600,
      color: color, letterSpacing: ".08em"
    }}>
      <span style={{ width: 7, height: 7, borderRadius: 99, background: color }} className={kind === "active" ? "ta-blink" : ""} />
      {label}
    </span>
  );
}

/* ---------- Floating live number ---------- */
function LiveNumber({ base = 978.54, swing = 6, decimals = 2, prefix = "", suffix = "" }) {
  const [v, setV] = useState(base);
  useEffect(() => {
    const id = setInterval(() => {
      setV(base + (Math.random() - 0.5) * swing);
    }, 1800);
    return () => clearInterval(id);
  }, [base, swing]);
  return <span className="ta-num">{prefix}{v.toFixed(decimals)}{suffix}</span>;
}

Object.assign(window, { LogoMark, Logo, LiveChart, Sparkline, StatusPill, LiveNumber, useCandles });
