// ===== Pine Script Viewer Page =====
// Displays auto-generated PineScript from the ML training pipeline.
// Fetches from /api/pine-script/{index} and shows code + metadata.

function PineScriptPage() {
  const [index, setIndex] = React.useState('nifty');
  const [pineCode, setPineCode] = React.useState('');
  const [metadata, setMetadata] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [copied, setCopied] = React.useState(false);
  const [training, setTraining] = React.useState(false);
  const toast = useToast();

  const fetchPineScript = React.useCallback(async (idx) => {
    setLoading(true);
    setError('');
    setPineCode('');
    setMetadata(null);
    try {
      const [scriptRes, metaRes] = await Promise.allSettled([
        API.get(`/api/pine-script/${idx}`),
        API.get(`/api/pine-script/${idx}/metadata`),
      ]);

      if (scriptRes.status === 'fulfilled' && scriptRes.value.pineScript) {
        setPineCode(scriptRes.value.pineScript);
      } else {
        const msg = scriptRes.status === 'rejected'
          ? (scriptRes.reason?.message || 'Failed to load PineScript')
          : 'No PineScript available';
        setError(msg);
      }

      if (metaRes.status === 'fulfilled' && metaRes.value.metadata) {
        setMetadata(metaRes.value.metadata);
      }
    } catch (err) {
      setError(err.message || 'Failed to load PineScript');
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchPineScript(index);
  }, [index, fetchPineScript]);

  const handleCopy = React.useCallback(() => {
    if (!pineCode) return;
    navigator.clipboard.writeText(pineCode).then(() => {
      setCopied(true);
      toast('PineScript copied to clipboard!', 'success');
      setTimeout(() => setCopied(false), 2000);
    }).catch(() => {
      toast('Failed to copy', 'error');
    });
  }, [pineCode, toast]);

  const handleDownload = React.useCallback(() => {
    if (!pineCode) return;
    const blob = new Blob([pineCode], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${index}-ml-signal-generator.pine`;
    a.click();
    URL.revokeObjectURL(url);
    toast('PineScript downloaded', 'success');
  }, [pineCode, index, toast]);

  const handleTrain = React.useCallback(async () => {
    if (training) return;
    setTraining(true);
    try {
      const jobName = `${index}-pine`;
      const data = await API.post(`/api/logs/cron/trigger/${jobName}`);
      toast(data.message || `${index.toUpperCase()} Pine ML pipeline queued! Check Training Logs for progress.`, 'success');
    } catch (err) {
      toast(err.message || 'Failed to trigger pipeline', 'error');
    } finally {
      setTraining(false);
    }
  }, [index, training, toast]);

  return React.createElement('div', { style: { maxWidth: '1200px', margin: '0 auto' } },
    // Header
    React.createElement('div', {
      style: {
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: '20px', flexWrap: 'wrap', gap: '12px'
      }
    },
      React.createElement('h2', { style: { margin: 0 } }, '🌲 Pine ML Signal Generator'),
      React.createElement('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
        // Index selector
        React.createElement('select', {
          value: index,
          onChange: (e) => setIndex(e.target.value),
          className: 'form-control',
          style: { width: '120px' }
        },
          React.createElement('option', { value: 'nifty' }, 'NIFTY'),
          React.createElement('option', { value: 'sensex' }, 'SENSEX')
        ),
        React.createElement('button', {
          className: 'btn btn-primary',
          onClick: handleTrain,
          disabled: training,
          title: 'Fetches candle data from Angel One + trains model + generates PineScript',
          style: { fontSize: '13px' }
        }, training ? '⏳ Queuing...' : '🚀 Run Pipeline'),
        React.createElement('button', {
          className: 'btn btn-secondary',
          onClick: () => fetchPineScript(index),
          disabled: loading
        }, loading ? '⏳ Loading...' : '🔄 Refresh'),
      )
    ),

    // Metadata cards
    metadata && React.createElement('div', {
      style: {
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
        gap: '12px', marginBottom: '20px'
      }
    },
      _metaCard('🎯 LightGBM F1', metadata.lgb_macro_f1 != null ? (metadata.lgb_macro_f1 * 100).toFixed(1) + '%' : '—'),
      _metaCard('🌳 Tree F1', metadata.dt_macro_f1 != null ? (metadata.dt_macro_f1 * 100).toFixed(1) + '%' : '—'),
      _metaCard('📊 Train Rows', metadata.train_rows != null ? metadata.train_rows.toLocaleString() : '—'),
      _metaCard('📅 Trained', metadata.trained_at ? metadata.trained_at.substring(0, 10) : '—'),
      _metaCard('🌳 Tree Depth', metadata.tree_depth ?? '—'),
      _metaCard('⭐ Top Features', metadata.top_features ? metadata.top_features.length : '—'),
    ),

    // Top features list
    metadata && metadata.top_features && React.createElement('div', {
      className: 'card', style: { marginBottom: '20px', padding: '16px' }
    },
      React.createElement('h4', { style: { margin: '0 0 8px 0' } }, '⭐ Top Features (by LightGBM importance)'),
      React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '8px' } },
        metadata.top_features.map((f, i) =>
          React.createElement('span', {
            key: f,
            style: {
              padding: '4px 10px', borderRadius: '12px', fontSize: '13px',
              background: i < 3 ? '#1b5e20' : '#333', color: '#fff'
            }
          }, `${i + 1}. ${f}`)
        )
      )
    ),

    // Error
    error && React.createElement('div', {
      className: 'card', style: { padding: '20px', textAlign: 'center', color: '#ff9800' }
    },
      React.createElement('p', null, '⚠️ ' + error),
      React.createElement('p', { style: { fontSize: '13px', color: '#999' } },
        'Click ',
        React.createElement('strong', null, '🚀 Run Pipeline'),
        ' above to fetch candle data, train the model, and generate PineScript.',
        ' Progress can be tracked in ',
        React.createElement('a', {
          href: '#/worker-logs', style: { color: '#64b5f6' }
        }, 'Training Logs'),
        '.'
      )
    ),

    // PineScript code
    pineCode && React.createElement('div', { className: 'card', style: { padding: '16px' } },
      React.createElement('div', {
        style: {
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginBottom: '12px'
        }
      },
        React.createElement('h4', { style: { margin: 0 } }, '📝 PineScript v5 Code'),
        React.createElement('div', { style: { display: 'flex', gap: '8px' } },
          React.createElement('button', {
            className: 'btn btn-primary',
            onClick: handleCopy,
            style: { fontSize: '13px' }
          }, copied ? '✅ Copied!' : '📋 Copy to Clipboard'),
          React.createElement('button', {
            className: 'btn btn-secondary',
            onClick: handleDownload,
            style: { fontSize: '13px' }
          }, '💾 Download .pine')
        )
      ),
      React.createElement('pre', {
        style: {
          background: '#1a1a2e', color: '#e0e0e0', padding: '16px',
          borderRadius: '8px', overflow: 'auto', maxHeight: '600px',
          fontSize: '12px', lineHeight: '1.5', whiteSpace: 'pre',
          fontFamily: "'Fira Code', 'Cascadia Code', 'Consolas', monospace'",
          border: '1px solid #333'
        }
      }, pineCode),
      React.createElement('p', {
        style: { marginTop: '12px', fontSize: '13px', color: '#888' }
      }, `${pineCode.split('\n').length} lines · ${pineCode.length.toLocaleString()} chars · Copy and paste into TradingView Pine Editor`)
    ),

    // Label distribution
    metadata && metadata.label_distribution && React.createElement('div', {
      className: 'card', style: { marginTop: '20px', padding: '16px' }
    },
      React.createElement('h4', { style: { margin: '0 0 12px 0' } }, '📊 Label Distribution'),
      React.createElement('div', { style: { display: 'flex', gap: '16px', flexWrap: 'wrap' } },
        Object.entries(metadata.label_distribution).map(([label, count]) => {
          const total = Object.values(metadata.label_distribution).reduce((a, b) => a + b, 0);
          const pct = ((count / total) * 100).toFixed(1);
          const color = label === 'BUY' ? '#4caf50' : label === 'SELL' ? '#f44336' : '#9e9e9e';
          return React.createElement('div', {
            key: label, style: { textAlign: 'center', minWidth: '80px' }
          },
            React.createElement('div', {
              style: { fontSize: '24px', fontWeight: 'bold', color }
            }, pct + '%'),
            React.createElement('div', { style: { fontSize: '13px', color: '#aaa' } },
              `${label} (${count.toLocaleString()})`)
          );
        })
      )
    )
  );
}

function _metaCard(label, value) {
  return React.createElement('div', {
    className: 'card',
    style: { padding: '12px', textAlign: 'center' }
  },
    React.createElement('div', {
      style: { fontSize: '11px', color: '#888', marginBottom: '4px' }
    }, label),
    React.createElement('div', {
      style: { fontSize: '18px', fontWeight: 'bold' }
    }, value)
  );
}
