/* global React, Button, Eyebrow, GridBG, Icon, LightweightCharts */
const { useState, useEffect, useRef } = React;

// ----------------------------------------------------------------------------
// Gráfico del 6E con motor pro (lightweight-charts, la librería open-source de
// TradingView) tematizado EXACTAMENTE a la marca: fondo de la tarjeta #141722,
// velas alcistas magenta (#FF007F) y bajistas cyan (#00E5FF), rejilla cyan muy
// sutil. Soporta zoom, arrastre y crosshair nativos + cambio de temporalidad.
// Datos reales vía la Edge Function `chart-6e` (Yahoo 6E=F). Si falla, usa un
// fallback sintético para no verse roto.
// ----------------------------------------------------------------------------

// Colores EXACTOS de la marca (colors_and_type.css): el fondo es --surface-2.
const C = {
  bg: '#12161D',                 // --surface-2 (mismo fondo que la tarjeta actual)
  up: '#FF007F',                 // --neon-magenta (velas alcistas, por manual de marca)
  down: '#00E5FF',               // --neon-cyan (velas bajistas)
  grid: 'rgba(0,229,255,0.06)',  // rejilla cyan muy sutil
  border: 'rgba(0,229,255,0.14)',// --hairline
  text: 'rgba(242,242,242,0.66)',// --fg-2
  crossCyan: 'rgba(0,229,255,0.45)',
};

const TFS = [['15m', '15M'], ['1h', '1H'], ['1d', '1D'], ['1wk', '1W']];

function fetchTf(tf) {
  const base = window.CDT_SUPABASE_URL, key = window.CDT_SUPABASE_KEY;
  if (!base || !key) return Promise.resolve(null);
  return fetch(base + '/functions/v1/chart-6e?tf=' + tf, { headers: { Authorization: 'Bearer ' + key, apikey: key } })
    .then((r) => (r.ok ? r.json() : null))
    .catch(() => null);
}

// Velas sintéticas de respaldo (estructura alcista suave) con timestamps reales.
function genFallback(n = 160) {
  let price = 1.082, seed = 42;
  const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
  const step = 900;
  let t = Math.floor(Date.now() / 1000) - (n - 1) * step;
  const out = [];
  for (let i = 0; i < n; i++) {
    const drift = 0.0011 * (rnd() - 0.4);
    const o = price, c = o + drift;
    const h = Math.max(o, c) + 0.0006 * rnd();
    const l = Math.min(o, c) - 0.0006 * rnd();
    out.push({ t, o, h, l, c });
    price = c; t += step;
  }
  return out;
}

function Chart6E() {
  const wrapRef = useRef(null);
  const chartRef = useRef(null);
  const seriesRef = useRef(null);
  const cacheRef = useRef({});
  const [tf, setTf] = useState('15m');
  const [ready, setReady] = useState(false);
  const [info, setInfo] = useState({ last: null, changePct: 0, up: true, live: false, loading: true });

  // Crea el chart una sola vez.
  useEffect(() => {
    if (!window.LightweightCharts || !wrapRef.current) return;
    const LC = window.LightweightCharts;
    const chart = LC.createChart(wrapRef.current, {
      // autoSize ajusta el lienzo al contenedor (ancho Y alto) con su propio
      // ResizeObserver: así en móvil el eje de precios de la derecha nunca se
      // recorta y el alto sigue al definido por CSS (.cdt-chart-canvas).
      autoSize: true,
      layout: { background: { type: 'solid', color: C.bg }, textColor: C.text, fontFamily: 'Inter, sans-serif', fontSize: 11 },
      grid: { vertLines: { color: C.grid }, horzLines: { color: C.grid } },
      rightPriceScale: { borderColor: C.border, scaleMargins: { top: 0.12, bottom: 0.12 } },
      timeScale: { borderColor: C.border, rightOffset: 6, timeVisible: true, secondsVisible: false },
      crosshair: {
        mode: LC.CrosshairMode.Normal,
        vertLine: { color: C.crossCyan, width: 1, style: 2, labelBackgroundColor: C.down },
        horzLine: { color: C.crossCyan, width: 1, style: 2, labelBackgroundColor: C.up },
      },
      // En táctil: arrastre horizontal = mover el gráfico; arrastre vertical =
      // desplazar la PÁGINA (vertTouchDrag:false), para no atrapar el scroll.
      handleScroll: { mouseWheel: true, pressedMouseMove: true, horzTouchDrag: true, vertTouchDrag: false },
      handleScale: true,
    });
    const series = chart.addCandlestickSeries({
      upColor: C.up, downColor: C.down, wickUpColor: C.up, wickDownColor: C.down,
      borderVisible: false, priceFormat: { type: 'price', precision: 4, minMove: 0.0001 },
    });
    chartRef.current = chart; seriesRef.current = series;
    setReady(true);
    return () => { chart.remove(); chartRef.current = null; seriesRef.current = null; setReady(false); };
  }, []);

  // Carga / cambia los datos según la temporalidad.
  useEffect(() => {
    if (!ready) return;
    let alive = true;
    const apply = (candles, live) => {
      if (!alive || !seriesRef.current) return;
      const data = candles.map((c) => ({ time: c.t, open: c.o, high: c.h, low: c.l, close: c.c }));
      seriesRef.current.setData(data);
      const n = data.length;
      if (chartRef.current) {
        const from = Math.max(0, n - 20);   // zoom por defecto: últimas 20 velas
        chartRef.current.timeScale().setVisibleLogicalRange({ from, to: n + 2 });
      }
      const last = candles[n - 1].c;
      const ref = candles[Math.max(0, n - 20)].c;
      const changePct = ref ? ((last - ref) / ref) * 100 : 0;
      setInfo({ last, changePct, up: changePct >= 0, live, loading: false });
    };
    if (cacheRef.current[tf]) { apply(cacheRef.current[tf], true); }
    else {
      setInfo((s) => ({ ...s, loading: true }));
      fetchTf(tf).then((j) => {
        if (!alive) return;
        if (j && Array.isArray(j.candles) && j.candles.length >= 5) { cacheRef.current[tf] = j.candles; apply(j.candles, true); }
        else { apply(genFallback(160), false); }
      });
    }
    return () => { alive = false; };
  }, [tf, ready]);

  const tfLabel = (TFS.find(([v]) => v === tf) || [])[1] || '15M';
  const up = info.up;
  const accent = up ? C.up : C.down;

  return (
    <div className="cdt-chart-card" style={{ position: 'relative', background: 'var(--surface-2)', border: '1px solid var(--hairline)',
      borderRadius: 'var(--r-lg)', padding: 18, boxShadow: 'var(--shadow-card)' }}>

      {/* cabecera: símbolo + precio + temporalidades */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12, marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <span style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 15, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--fg-1)' }}>
            6E · {tfLabel}
          </span>
          {info.live && (
            <span title="Datos reales en vivo" style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
              background: 'var(--neon-cyan)', boxShadow: 'var(--glow-cyan-sm)' }} />
          )}
          {info.last != null && (
            <span style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 15, color: 'var(--fg-1)' }}>{info.last.toFixed(4)}</span>
          )}
          {info.last != null && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 12.5,
              color: accent, textShadow: up ? 'var(--text-glow-magenta)' : 'var(--text-glow-cyan)' }}>
              <Icon name={up ? 'trending-up' : 'trending-down'} size={14} color={accent} stroke={2.4} />
              {(info.changePct >= 0 ? '+' : '') + info.changePct.toFixed(2)}%
            </span>
          )}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {TFS.map(([v, l]) => {
            const active = tf === v;
            return (
              <button key={v} type="button" onClick={() => setTf(v)}
                style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 12, letterSpacing: '.05em',
                  cursor: 'pointer', borderRadius: 'var(--r-pill)', padding: '5px 12px', transition: 'all 150ms ease',
                  background: active ? 'var(--neon-magenta)' : 'var(--surface-3)',
                  color: active ? '#fff' : 'var(--fg-2)',
                  border: `1px solid ${active ? 'var(--neon-magenta)' : 'var(--hairline)'}`,
                  boxShadow: active ? 'var(--glow-magenta-sm)' : 'none' }}>
                {l}
              </button>
            );
          })}
        </div>
      </div>

      {/* el gráfico */}
      <div style={{ position: 'relative' }}>
        <div ref={wrapRef} className="cdt-chart-canvas" />
        {info.loading && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-head)', fontSize: 13, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>
            Cargando 6E…
          </div>
        )}
      </div>

      {/* etiquetas de marca + ayuda */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {['VAL', 'VAH', 'Liquidez', 'Gap'].map((t, i) => (
            <span key={i} style={{ fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 11,
              letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--neon-cyan)',
              background: 'var(--cyan-soft)', border: '1px solid rgba(0,229,255,.25)',
              borderRadius: 'var(--r-pill)', padding: '5px 11px' }}>{t}</span>
          ))}
        </div>
        <span className="cdt-chart-hint" style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-3)' }}>Arrastra para mover · rueda para zoom</span>
      </div>
    </div>
  );
}

function Hero({ onApply, onJoin }) {
  return (
    <section id="top" style={{ position: 'relative', overflow: 'hidden',
      background: 'radial-gradient(120% 80% at 80% 10%, rgba(255,0,127,.10), transparent 50%), radial-gradient(120% 90% at 10% 30%, rgba(0,229,255,.10), transparent 50%), var(--surface-1)' }}>
      <GridBG opacity={0.05} style={{ maskImage: 'radial-gradient(circle at 50% 30%, #000 20%, transparent 75%)', WebkitMaskImage: 'radial-gradient(circle at 50% 30%, #000 20%, transparent 75%)' }} />
      <div style={{ maxWidth: 1180, margin: '0 auto', padding: 'clamp(96px,11vw,150px) 24px clamp(56px,7vw,90px)',
        position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.05fr)',
        gap: 'clamp(32px,5vw,56px)', alignItems: 'center' }} className="cdt-hero-grid">

        <div>
          <Eyebrow>Comunidad gratuita · Discord del gremio</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900,
            fontSize: 'clamp(38px,5.6vw,68px)', lineHeight: 1.03, letterSpacing: '.005em',
            textTransform: 'uppercase', color: 'var(--fg-1)', margin: '20px 0 0' }}>
            Forjando la <span className="cdt-gradient-text">nueva era</span> del trading
          </h1>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(16px,1.5vw,19px)',
            lineHeight: 1.6, color: 'var(--fg-2)', margin: '24px 0 0', maxWidth: 520 }}>
            Todo empieza en nuestra <strong style={{ color: 'var(--fg-1)', fontWeight: 600 }}>comunidad gratuita</strong>:
            análisis diario, clases puntuales y la cultura del gremio. Desde dentro escalas hasta la
            formación y la mentoría 1 a 1. Cero indicadores mágicos. Cero dinero fácil.
          </p>
          <div className="cdt-hero-cta" style={{ display: 'flex', gap: 14, marginTop: 36, flexWrap: 'wrap' }}>
            <Button size="lg" onClick={onJoin} icon="message-circle">Únete gratis al Discord</Button>
            <Button size="lg" variant="secondary" onClick={onApply}>Aplica a la Cámara</Button>
          </div>
          <div style={{ display: 'flex', gap: 22, marginTop: 34, flexWrap: 'wrap' }}>
            {[['gift', 'Acceso gratuito'], ['bar-chart-3', 'Análisis diario'], ['users', 'Discord del gremio']].map(([ic, t], i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--fg-3)', fontSize: 13.5, fontFamily: 'var(--font-body)' }}>
                <Icon name={ic} size={17} color="var(--neon-cyan)" /> {t}
              </div>
            ))}
          </div>
        </div>

        <div className="cdt-hero-visual" style={{ position: 'relative' }}>
          <Chart6E />
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
