/* InteractiveChart — TriPhase-styled wrapper for the 3-bot demo engine.
 *
 * Renders 3 phases (Sideway / Trend / Pullback) in a single chart. User can:
 *   - Click phase tabs to switch bot
 *   - Use prev/next/play to step through scenarios
 *   - Scrub via the timeline cells
 *   - Keyboard: ← → space, 1/2/3 for phases
 */

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

const PHASE_COLORS = {
  sideway:  "#F5B544",   // amber — grid bot's range/TP color
  trend:    "#F08A3E",   // orange — momentum
  pullback: "#5B8DEF",   // blue — measured retrace
};

// Map TriPhase chart theme tokens onto ChartEngine.THEME (read by renderer + layer fns).
// IMPORTANT: bot layer code does `T.buy + "AA"` to add hex alpha — so every accent
// MUST be a 6-digit hex string. OKLCH won't survive string concatenation.
function patchChartTheme() {
  if (!window.ChartEngine || window.__icThemed) return;
  const T = window.ChartEngine.THEME;

  // Detect light mode via CSS var on root
  const isLight = document.documentElement.classList.contains("light");

  // Background / structure
  T.bg = isLight ? "#ffffff" : "#050507";
  T.bgPanel = isLight ? "#fafaf9" : "#0a0a0d";
  T.grid = isLight ? "rgba(0,0,0,0.06)" : "rgba(255,255,255,0.05)";
  T.gridStrong = isLight ? "rgba(0,0,0,0.10)" : "rgba(255,255,255,0.10)";
  T.border = isLight ? "rgba(0,0,0,0.08)" : "rgba(255,255,255,0.08)";
  T.crosshair = isLight ? "rgba(0,0,0,0.35)" : "rgba(255,255,255,0.35)";
  T.text = isLight ? "rgba(10,10,12,0.55)" : "rgba(245,245,247,0.55)";
  T.textBr = isLight ? "#0a0a0c" : "#f5f5f7";
  T.textHi = isLight ? "#000000" : "#ffffff";

  // Candles — hex (so layer code can do `+ "AA"` for alpha)
  T.bull = "#3FB97A";       // green
  T.bear = "#E25C4A";       // coral
  T.bullDim = "#3FB97A";
  T.bearDim = "#E25C4A";

  // Bot accents — hex, matched to TriPhase phase palette
  T.buy   = "#3FB97A";  // sideway buys = green
  T.sell  = "#E25C4A";  // sideway sells = coral
  T.tp    = "#F5B544";  // take-profit = amber
  T.trend = "#F08A3E";  // trend bot = orange
  T.pb    = "#5B8DEF";  // pullback bot = blue
  T.fib   = "#A98BE5";  // fib levels = purple
  T.grid3 = "#F5B544";  // grid lines = amber

  T.badgeBg = isLight ? "#ffffff" : "#0a0a0d";

  window.__icThemed = true;
}

// Re-patch on light/dark toggle
function watchThemeToggle() {
  const obs = new MutationObserver(() => {
    window.__icThemed = false;
    patchChartTheme();
  });
  obs.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
}

// Build the 3 bot configs (lazy — bots load their data into window globals on script eval).
function getBotConfigs() {
  return [
    { id: "sideway",  cfg: window.GRID_BOT,     color: PHASE_COLORS.sideway },
    { id: "trend",    cfg: window.TREND_BOT,    color: PHASE_COLORS.trend },
    { id: "pullback", cfg: window.PULLBACK_BOT, color: PHASE_COLORS.pullback },
  ];
}

// Mini sparkline for each phase tab — drawn from that bot's closes
function PhaseSpark({ closes, color }) {
  const ref = useRef(null);
  useEffect(() => {
    const c = ref.current; if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const r = c.getBoundingClientRect();
    c.width = r.width * dpr; c.height = r.height * dpr;
    const ctx = c.getContext("2d");
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, r.width, r.height);
    if (!closes || !closes.length) return;
    const step = Math.max(1, Math.floor(closes.length / 80));
    const sub = []; for (let i = 0; i < closes.length; i += step) sub.push(closes[i]);
    let mn = Math.min(...sub), mx = Math.max(...sub);
    const pad = (mx - mn) * 0.1 + 0.1; mn -= pad; mx += pad;
    const px = (i) => (i / (sub.length - 1)) * r.width;
    const py = (v) => r.height - ((v - mn) / (mx - mn)) * r.height;
    ctx.strokeStyle = color;
    ctx.lineWidth = 1.4;
    ctx.lineJoin = "round";
    ctx.beginPath();
    sub.forEach((v, i) => { const x = px(i), y = py(v); if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); });
    ctx.stroke();
    // soft fill — color is hex (#RRGGBB), append alpha as hex
    ctx.lineTo(r.width, r.height);
    ctx.lineTo(0, r.height);
    ctx.closePath();
    ctx.fillStyle = color + "1A"; // ~10% alpha
    ctx.fill();
  }, [closes, color]);
  return <canvas ref={ref} className="ic-phase-spark" />;
}

// Chart canvas — pure rendering, controlled by parent via props
function ChartCanvas({ phase, step, mouseRef, onCrosshair }) {
  const ref = useRef(null);
  const rendererRef = useRef(null);
  const animRef = useRef(null);

  // Build / rebuild renderer when phase changes
  useEffect(() => {
    patchChartTheme();
    if (!ref.current || !phase) return;
    rendererRef.current = new window.ChartEngine.ChartRenderer({
      canvas: ref.current,
      ohlcv: phase.cfg.ohlcv,
      symbol: phase.cfg.symbol,
      exchange: phase.cfg.exchange,
    });
  }, [phase]);

  // Animation loop — setInterval (rAF can be throttled in offscreen iframes)
  useEffect(() => {
    let start = performance.now();
    const drawOnce = () => {
      const r = rendererRef.current;
      const cfg = phase?.cfg;
      if (!r || !cfg) return;
      const s = cfg.steps[step];
      if (!s) return;
      const ts = performance.now() - start;
      const pulse = (ts * 0.0014) % 1;
      const preIdx = cfg.preIdx || 0;
      // View window: show ~50 candles centered on the action
      const viewStart = Math.max(0, preIdx - 18);
      const viewEnd = Math.min(cfg.ohlcv.length, Math.max(s.pathTo + 8, preIdx + 36));
      const ext = [];
      for (const o of (s.open || [])) { ext.push(o.entry); if (o.tp) ext.push(o.tp); }
      for (const c of (s.closed || [])) { ext.push(c.entry); ext.push(c.exit); }
      if (s.fibLevels) { ext.push(s.fibLevels.peak); ext.push(s.fibLevels.bot); for (const lv of s.fibLevels.levels) ext.push(lv.price); }
      if (s.zone) { ext.push(s.zone.lo); ext.push(s.zone.hi); }
      try {
        r.draw({
          endIdx: s.pathTo,
          viewStart, viewEnd,
          priceExtents: ext,
          crosshair: mouseRef.current,
          pulse,
          onCrosshair,
          layers: cfg.makeLayers(s),
        });
      } catch (e) { /* ignore intermittent draw errors */ }
    };
    drawOnce();
    const id = setInterval(drawOnce, 1000 / 30);
    return () => clearInterval(id);
  }, [phase, step, onCrosshair, mouseRef]);

  return <canvas ref={ref} className="ic-canvas" />;
}

const InteractiveChart = ({ t }) => {
  const [phaseIdx, setPhaseIdx] = useState(0);
  const [step, setStep] = useState(0);
  const [playing, setPlaying] = useState(false);
  const [hoverIdx, setHoverIdx] = useState(null);
  const [phases, setPhases] = useState(null);
  const mouseRef = useRef({ x: null, y: null });
  const playTimerRef = useRef(null);

  // Wait for bot data scripts to load
  useEffect(() => {
    const check = () => {
      if (window.GRID_BOT && window.TREND_BOT && window.PULLBACK_BOT && window.ChartEngine?.ChartRenderer) {
        setPhases(getBotConfigs());
      } else {
        setTimeout(check, 80);
      }
    };
    check();
  }, []);

  useEffect(() => { watchThemeToggle(); }, []);

  const phase = phases ? phases[phaseIdx] : null;
  const cfg = phase?.cfg;
  const steps = cfg?.steps || [];
  const s = steps[step];
  const lang = (t.nav?.bots === "Bot") ? "vi" : "en";

  // Reset step when phase changes
  useEffect(() => { setStep(0); setHoverIdx(null); }, [phaseIdx]);

  // Auto-play
  useEffect(() => {
    if (!playing) return;
    playTimerRef.current = setInterval(() => {
      setStep(prev => {
        if (prev + 1 >= steps.length) {
          setPlaying(false);
          return prev;
        }
        return prev + 1;
      });
    }, 2400);
    return () => clearInterval(playTimerRef.current);
  }, [playing, steps.length]);

  // Keyboard
  useEffect(() => {
    const onKey = (e) => {
      // only when chart section is visible
      const el = document.getElementById("demo");
      if (!el) return;
      const r = el.getBoundingClientRect();
      if (r.bottom < 0 || r.top > window.innerHeight) return;
      if (e.key === "ArrowLeft") { setPlaying(false); setStep(p => Math.max(0, p - 1)); }
      else if (e.key === "ArrowRight") { setPlaying(false); setStep(p => Math.min(steps.length - 1, p + 1)); }
      else if (e.key === " " && document.activeElement.tagName !== "INPUT") { e.preventDefault(); setPlaying(p => !p); }
      else if (e.key === "1") { setPhaseIdx(0); setPlaying(false); }
      else if (e.key === "2") { setPhaseIdx(1); setPlaying(false); }
      else if (e.key === "3") { setPhaseIdx(2); setPlaying(false); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [steps.length]);

  // Mouse tracking on chart
  const onMouseMove = useCallback((e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    mouseRef.current = { x: e.clientX - rect.left, y: e.clientY - rect.top };
  }, []);
  const onMouseLeave = useCallback(() => {
    mouseRef.current = { x: null, y: null };
    setHoverIdx(null);
  }, []);
  const onCrosshair = useCallback((i) => { setHoverIdx(i); }, []);

  const titleParts = t.demo.title;
  const i18n = cfg?.i18n[lang] || {};

  // OHLC display
  const idx = hoverIdx != null ? hoverIdx : (s?.pathTo ?? 0);
  const candle = cfg?.ohlcv[idx];
  const prev = (idx > 0 && cfg) ? cfg.ohlcv[idx - 1].close : candle?.close;
  const chg = candle ? candle.close - prev : 0;
  const chgPct = prev ? (chg / prev) * 100 : 0;
  const isUp = candle ? candle.close >= candle.open : false;

  if (!phases) {
    return (
      <section id="demo" className="ic-section">
        <div className="container">
          <div className="ic-head">
            <span className="eyebrow">{t.demo.eyebrow}</span>
            <h2 className="h-section">
              {titleParts[0]}<span className="serif-it accent-fg">{titleParts[1]}</span>.
            </h2>
            <p className="lead">{t.demo.lead}</p>
          </div>
          <div style={{
            border: "1px solid var(--line)",
            background: "var(--bg-2)",
            height: 600,
            display: "grid",
            placeItems: "center",
            color: "var(--fg-mute)",
            fontFamily: "var(--font-mono)",
            fontSize: 11,
            letterSpacing: "0.18em",
          }}>LOADING CHART ENGINE…</div>
        </div>
      </section>
    );
  }

  // Per-phase localized labels (read from each bot's cfg + i18n + i18n.js botsData)
  const phaseLabels = [
    { en: "Sideway",  vi: "Đi ngang",         tag: lang === "vi" ? "BOT-01 · Đi ngang" : "BOT-01 · Sideways" },
    { en: "Trend",    vi: "Theo xu hướng",    tag: lang === "vi" ? "BOT-02 · Xu hướng" : "BOT-02 · Trend" },
    { en: "Pullback", vi: "Mua khi điều chỉnh", tag: lang === "vi" ? "BOT-03 · Điều chỉnh" : "BOT-03 · Pullback" },
  ];

  return (
    <section id="demo" className="ic-section">
      <div className="container">
        <div className="ic-head">
          <span className="eyebrow">{t.demo.eyebrow}</span>
          <h2 className="h-section">
            {titleParts[0]}<span className="serif-it accent-fg">{titleParts[1]}</span>.
          </h2>
          <p className="lead">{lang === "vi"
            ? "Quan sát từng bot ra quyết định trên chính loại thị trường của nó. Chuyển pha bằng tab phía trên — hoặc dùng phím 1 · 2 · 3. ← → để xem từng bước, phím cách để chạy tự động."
            : "Watch each bot make decisions in its own market regime. Switch phases via the tabs above — or press 1 · 2 · 3. Use ← → to step, space to autoplay."
          }</p>
        </div>

        <div>
          {/* Phase tabs */}
          <div className="ic-phases">
            {phases.map((p, i) => (
              <button
                key={p.id}
                className={`ic-phase ${phaseIdx === i ? "active" : ""}`}
                onClick={() => { setPhaseIdx(i); setPlaying(false); }}
                style={{ "--phase-color": p.color }}
              >
                <span className="ic-phase-num">0{i + 1} · Phase</span>
                <span className="ic-phase-name">
                  <span className="ic-phase-name-en">{phaseLabels[i].en}</span>
                  <span className="ic-phase-name-vi">{phaseLabels[i].vi}</span>
                </span>
                <span className="ic-phase-tag">{phaseLabels[i].tag}</span>
                <PhaseSpark closes={p.cfg.ohlcv.map(c => c.close)} color={p.color} />
              </button>
            ))}
          </div>

          {/* Symbol meta bar */}
          <div className="ic-meta" style={{ "--phase-color": phase.color }}>
            <span className="ic-symbol">
              {cfg.symbol}
              <span className="ic-symbol-exch">{cfg.exchange || ""}</span>
            </span>
            <div className="ic-tf-pills">
              <span className="pill">5m</span>
              <span className="pill active">15m</span>
              <span className="pill">1h</span>
              <span className="pill">4h</span>
              <span className="pill">1D</span>
            </div>
            <div className="ic-ohlc">
              <div className="pair"><span className="lbl">O</span><span className="val">{candle?.open.toFixed(2)}</span></div>
              <div className="pair"><span className="lbl">H</span><span className="val up">{candle?.high.toFixed(2)}</span></div>
              <div className="pair"><span className="lbl">L</span><span className="val dn">{candle?.low.toFixed(2)}</span></div>
              <div className="pair"><span className="lbl">C</span><span className={`val ${isUp ? "up" : "dn"}`}>{candle?.close.toFixed(2)}</span></div>
              <div className="pair"><span className="lbl">VOL</span><span className="val">{candle?.volume.toFixed(0)}</span></div>
              <div className="pair"><span className="lbl">CHG</span><span className={`val ${chg >= 0 ? "up" : "dn"}`}>
                {chg >= 0 ? "+" : ""}{chg.toFixed(2)} ({chg >= 0 ? "+" : ""}{chgPct.toFixed(2)}%)
              </span></div>
            </div>
          </div>

          {/* Chart */}
          <div className="ic-shell" style={{ "--phase-color": phase.color }}
            onMouseMove={onMouseMove} onMouseLeave={onMouseLeave}>
            <span className="ic-overlay-tag">
              <span className="dot" />
              {phaseLabels[phaseIdx].tag} · LIVE
            </span>
            <ChartCanvas phase={phase} step={step} mouseRef={mouseRef} onCrosshair={onCrosshair} />
          </div>

          {/* Caption */}
          <div className={`ic-caption ${s?.tpNow ? "tp" : ""}`} style={{ "--phase-color": phase.color }}>
            <span className="ic-step-num">{step + 1} / {steps.length}</span>
            <div className="ic-step-body">
              <span className="ic-step-title">{s?.title[lang]}</span>
              <span className="ic-step-sub">{s?.sub[lang]}</span>
            </div>
            {(() => {
              const total = (s?.closed || []).reduce((a, c) => a + c.profit, 0);
              return total > 0
                ? <span className="ic-total">{i18n.total || "Total"}: +{total.toFixed(2)}</span>
                : <span />;
            })()}
          </div>

          {/* Player */}
          <div className="ic-player" style={{ "--phase-color": phase.color }}>
            <button className="ic-btn" disabled={step === 0}
              onClick={() => { setPlaying(false); setStep(s => Math.max(0, s - 1)); }}>
              <span className="icon">◀</span> {i18n.prev || "Prev"}
            </button>
            <button className={`ic-btn play ${playing ? "playing" : ""}`}
              onClick={() => setPlaying(p => !p)}>
              <span className="icon">{playing ? "⏸" : "▶"}</span> {playing ? (i18n.pause || "Pause") : (i18n.play || "Auto-play")}
            </button>
            <button className="ic-btn" disabled={step >= steps.length - 1}
              onClick={() => { setPlaying(false); setStep(s => Math.min(steps.length - 1, s + 1)); }}>
              {i18n.next || "Next"} <span className="icon">▶</span>
            </button>
            <div className="ic-scrub">
              {steps.map((stp, i) => (
                <div
                  key={i}
                  className={`ic-scrub-cell ${i < step ? "past" : ""} ${i === step ? "current" : ""} ${i === step && stp.tpNow ? "tp" : ""}`}
                  onClick={() => { setPlaying(false); setStep(i); }}
                  title={stp.title[lang]}
                />
              ))}
            </div>
          </div>

          {/* Legend */}
          <div className="ic-legend">
            {(cfg.legend || []).map((l, i) => (
              <span key={i} className="item">
                <span className={`swatch ${l.shape === "dash" ? "dash" : ""}`}
                  style={{ background: l.shape === "dash" ? "transparent" : l.color, color: l.color }} />
                <span>{i18n[l.i18nKey] || l.i18nKey}</span>
              </span>
            ))}
          </div>

          {/* Hint */}
          <div className="ic-hint">
            <span>← → {lang === "vi" ? "BƯỚC" : "STEP"} · <kbd>SPACE</kbd> {lang === "vi" ? "TỰ ĐỘNG" : "AUTO"} · <kbd>1</kbd> <kbd>2</kbd> <kbd>3</kbd> {lang === "vi" ? "CHUYỂN PHA" : "SWITCH PHASE"}</span>
            <span>{i18n.foot || "Demo data — strategy illustration"}</span>
          </div>
        </div>
      </div>
    </section>
  );
};

window.InteractiveChart = InteractiveChart;
