/* P20i · Multi-Timeframe Analysis Lab (M08 + capstone)
 * 3 charts apilados: monthly → weekly → daily. Crosshair sincronizado.
 * Forza orden top-down: weekly desbloqueado tras commit de monthly, daily tras weekly.
 */

function P20i_MultiTF(props = {}) {
  // En capstone los tickers SÍ son visibles
  const ticker = props.ticker || 'AAPL';
  const tickerName = props.tickerName || 'Apple Inc.';

  // Series para cada TF (mismo seed base, distintos n y vol)
  const monthlyBars = React.useMemo(() => window.synthetic.makeSeries({ seed: 21, n: 200, drift: 0.0024, vol: 0.018, cycles: 1.5, regime: 'uptrend' }), []);
  const weeklyBars = React.useMemo(() => window.synthetic.makeSeries({ seed: 31, n: 156, drift: 0.0015, vol: 0.014, cycles: 2.5, regime: 'uptrend', start: 130 }), []);
  const dailyBars = React.useMemo(() => window.synthetic.makeSeries({ seed: 41, n: 220, drift: 0.0008, vol: 0.011, cycles: 4, regime: 'uptrend', start: 170 }), []);

  // Commits por TF
  const [committed, setCommitted] = React.useState(props.committed || { monthly: true, weekly: false, daily: false });
  const [hoverIdx, setHoverIdx] = React.useState(null);

  // Drawings por TF
  const monthlySupport = React.useMemo(() => {
    const piv = window.synthetic.findPivots(monthlyBars, 8).filter(p => p.kind === 'low');
    if (piv.length < 2) return null;
    return {
      type: 'trendline',
      points: [{ x: piv[1].index, y: piv[1].price }, { x: piv[piv.length - 1].index, y: piv[piv.length - 1].price }],
      touches: 5, state: 'valid',
    };
  }, [monthlyBars]);

  const weeklySupport = React.useMemo(() => {
    const piv = window.synthetic.findPivots(weeklyBars, 6).filter(p => p.kind === 'low');
    if (piv.length < 2) return null;
    return {
      type: 'trendline',
      points: [{ x: piv[piv.length - 3].index, y: piv[piv.length - 3].price }, { x: piv[piv.length - 1].index, y: piv[piv.length - 1].price }],
      touches: 4, state: 'valid',
    };
  }, [weeklyBars]);

  // Markers ChoCh y BoS en monthly y weekly
  const monthlyMarkers = [
    { index: 110, kind: 'choch', price: monthlyBars[110].h },
    { index: 130, kind: 'bos', price: monthlyBars[130].l },
  ];
  const weeklyMarkers = [
    { index: 80, kind: 'choch', price: weeklyBars[80].h },
    { index: 100, kind: 'bos', price: weeklyBars[100].l },
  ];

  function commitTF(tf) {
    setCommitted({ ...committed, [tf]: true });
  }

  return (
    <div className="shell-main" style={{ height: '100%' }}>
      <div className="lab-header">
        <div>
          <div className="lab-header-id">M08 · CASE INTEGRAL · ANÁLISIS TOP-DOWN</div>
          <div className="lab-header-title">{tickerName} · {ticker} — Etiqueta tendencia primaria, secundaria y oportunidad de entrada en orden estricto.</div>
        </div>
        <div className="lab-header-counter">
          <div className="counter-pill"><span className="label">TFs cementados</span>{Object.values(committed).filter(Boolean).length}<span style={{ color: 'var(--text-muted)' }}>/3</span></div>
        </div>
      </div>

      <div className="lab-body" style={{ gridTemplateColumns: '1fr 56px 280px' }}>
        <div className="lab-canvas-area" style={{ flexDirection: 'column', gap: 6, padding: 12, alignItems: 'stretch', justifyContent: 'flex-start' }}>
          <TFChart
            bars={monthlyBars} tf="monthly" tfLabel="Monthly · Tendencia primaria"
            ticker={ticker} committed={committed.monthly} locked={false}
            drawings={committed.monthly && monthlySupport ? [monthlySupport] : []}
            markers={committed.monthly ? monthlyMarkers : []}
            onCommit={() => commitTF('monthly')}
            hoverIdx={hoverIdx}
            onHover={setHoverIdx}
          />
          <TFChart
            bars={weeklyBars} tf="weekly" tfLabel="Weekly · Tendencia secundaria"
            ticker={ticker} committed={committed.weekly} locked={!committed.monthly}
            drawings={committed.weekly && weeklySupport ? [weeklySupport] : []}
            markers={committed.weekly ? weeklyMarkers : []}
            onCommit={() => commitTF('weekly')}
            hoverIdx={hoverIdx}
            onHover={setHoverIdx}
            inProgress={committed.monthly && !committed.weekly}
            progressCount={!committed.weekly && committed.monthly ? '2/3' : null}
          />
          <TFChart
            bars={dailyBars} tf="daily" tfLabel="Daily · Oportunidad de entrada"
            ticker={ticker} committed={committed.daily} locked={!committed.weekly}
            drawings={[]}
            markers={[]}
            onCommit={() => commitTF('daily')}
            hoverIdx={hoverIdx}
            onHover={setHoverIdx}
          />
        </div>

        <LabToolbar tools={[
          { id: 'pivot', icon: Icon.pivot(16), label: 'Pivot marker' },
          { id: 'trendline', icon: Icon.trendline(16), label: 'Trendline' },
          { id: 'horizontal-support', icon: Icon.horizontal(16), label: 'Soporte' },
          { id: 'horizontal-resistance', icon: Icon.horizontal(16), label: 'Resistencia' },
          { id: 'zone', icon: Icon.zone(16), label: 'Zona' },
          { sep: true },
          { id: 'annotation', icon: Icon.annotation(16), label: 'Anotación' },
        ]} activeTool={null} onSelect={() => {}} />

        <div className="lab-side">
          <div className="side-section">
            <h4>Tu análisis hasta ahora</h4>
            <AnalysisOutline tf="monthly" committed={committed.monthly}
              text="Tendencia primaria alcista desde el inicio de la serie. ChoCh confirmado en barra 110. BoS en barra 130. Estructura HH/HL preservada, vuelta a la primaria." />
            <AnalysisOutline tf="weekly" committed={committed.weekly}
              text={committed.weekly ? 'Tendencia secundaria alcista con corrección 50%. Re-anchor de trendline en zona reciente.' : '—'}
              inProgress={!committed.weekly && committed.monthly} />
            <AnalysisOutline tf="daily" committed={committed.daily}
              text={committed.daily ? '...' : (committed.weekly ? 'Pendiente de análisis.' : 'Bloqueado.')} locked={!committed.weekly} />
          </div>
          <div className="side-section">
            <button className="btn btn-primary" disabled={!committed.monthly || !committed.weekly || !committed.daily} style={{ width: '100%' }}>
              Capturar análisis para informe
            </button>
            <div style={{ fontSize: 'var(--size-2xs)', color: 'var(--text-muted)', marginTop: 8, lineHeight: 'var(--lh-snug)' }}>
              Los drawings actuales de los 3 TF se incrustarán como evidencia citada en tu capstone.
            </div>
          </div>
        </div>
      </div>

      <div className="lab-footer">
        <FeedbackBanner
          kind="neutral"
          message="Top-down estricto activo. Daily se desbloqueará cuando cementes Weekly. Cementar es irreversible en esta sesión."
        />
      </div>
    </div>
  );
}

function TFChart({ bars, tf, tfLabel, ticker, committed, locked, drawings, markers, onCommit, hoverIdx, onHover, inProgress, progressCount }) {
  const tfColor = tf === 'monthly' ? '#C6A1FF' : tf === 'weekly' ? '#6BA3FF' : '#F0B86E';

  return (
    <div style={{ position: 'relative', filter: locked ? 'grayscale(0.6) opacity(0.5)' : 'none', pointerEvents: locked ? 'none' : 'auto', height: 198 }}>
      <ChartCanvas
        bars={bars}
        width={840}
        height={198}
        anonymized={false}
        ticker={ticker}
        tfBadge={tf}
        drawings={drawings}
        markers={markers}
        crosshairAt={hoverIdx != null ? { index: Math.floor(hoverIdx * bars.length / 220) } : null}
        onHover={(h) => onHover && onHover(h ? h.idx * 220 / bars.length : null)}
        showVolume={true}
        volumeRatio={0.18}
        padding={{ top: 14, right: 56, bottom: 22, left: 12 }}
      />
      {/* TF label + state badge */}
      <div style={{
        position: 'absolute', top: 6, left: 12,
        display: 'flex', alignItems: 'center', gap: 10,
        fontSize: 11, fontFamily: 'var(--font-sans)', fontWeight: 600, letterSpacing: '0.05em',
        color: tfColor, textTransform: 'uppercase',
      }}>
        {tfLabel}
      </div>
      <div style={{
        position: 'absolute', top: 6, right: 70,
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 11, fontFamily: 'var(--font-sans)',
      }}>
        {committed ? (
          <span className="chip chip-pass">{Icon.check(11)} Commit completo</span>
        ) : inProgress ? (
          <span className="chip chip-info">En progreso{progressCount ? ` · drawings ${progressCount}` : ''}</span>
        ) : locked ? (
          <span className="chip" style={{ background: 'transparent', border: '1px dashed var(--border-default)', color: 'var(--text-muted)' }}>{Icon.lock(11)} Bloqueado hasta TF superior</span>
        ) : null}
      </div>
    </div>
  );
}

function AnalysisOutline({ tf, committed, text, inProgress, locked }) {
  const tfColor = tf === 'monthly' ? 'var(--tf-monthly)' : tf === 'weekly' ? 'var(--tf-weekly)' : 'var(--tf-daily)';
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <div style={{ width: 4, height: 14, background: tfColor, borderRadius: 2, opacity: locked ? 0.3 : 1 }} />
        <span style={{ fontSize: 10, color: tfColor, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', opacity: locked ? 0.5 : 1 }}>{tf}</span>
        {committed && <span style={{ fontSize: 10, color: 'var(--signal-pass)' }}>✓</span>}
        {inProgress && <span style={{ fontSize: 10, color: 'var(--signal-info)' }}>•</span>}
      </div>
      <div style={{ fontSize: 'var(--size-xs)', color: committed ? 'var(--text-primary)' : 'var(--text-muted)', lineHeight: 'var(--lh-snug)', fontStyle: committed ? 'normal' : 'italic' }}>
        {text}
      </div>
    </div>
  );
}

window.P20i_MultiTF = P20i_MultiTF;
