'use client'
import React, { useEffect, useRef, useState } from 'react'

export default function StandaloneTest() {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const [status, setStatus] = useState('Starting...')

  useEffect(() => {
    const initChart = async () => {
      try {
        setStatus('Testing CDN version...')
        
        // Try using the CDN version instead
        if (typeof window !== 'undefined' && !(window as any).LightweightCharts) {
          setStatus('Loading CDN script...')
          
          const script = document.createElement('script')
          script.src = 'https://unpkg.com/lightweight-charts@5.0.8/dist/lightweight-charts.standalone.production.js'
          script.onload = () => {
            setStatus('CDN loaded, creating chart...')
            createChartWithCDN()
          }
          script.onerror = () => {
            setStatus('CDN load failed')
          }
          document.head.appendChild(script)
        } else if ((window as any).LightweightCharts) {
          setStatus('CDN already loaded, creating chart...')
          createChartWithCDN()
        }
        
      } catch (error) {
        console.error('Error:', error)
        setStatus(`Error: ${error}`)
      }
    }

    const createChartWithCDN = () => {
      try {
        if (!chartContainerRef.current) {
          setStatus('No container')
          return
        }

        const { createChart, CandlestickSeries } = (window as any).LightweightCharts
        
        setStatus('Creating chart with CDN...')
        const chart = createChart(chartContainerRef.current, {
          width: 800,
          height: 400,
          layout: {
            background: { color: '#1a1a1a' },
            textColor: '#ffffff',
          },
        })
        
        setStatus('Adding series...')
        const series = chart.addSeries(CandlestickSeries, {
          upColor: '#26a69a',
          downColor: '#ef5350',
        })
        
        setStatus('Setting data...')
        series.setData([
          { time: '2025-07-14', open: 100, high: 105, low: 95, close: 102 },
          { time: '2025-07-15', open: 102, high: 107, low: 98, close: 104 },
          { time: '2025-07-16', open: 104, high: 109, low: 101, close: 106 },
        ])
        
        setStatus('Chart created successfully!')
        
      } catch (error) {
        console.error('CDN chart error:', error)
        setStatus(`CDN Error: ${error}`)
      }
    }

    initChart()
  }, [])

  return (
    <div className="min-h-screen bg-gray-900 p-8">
      <h1 className="text-white text-3xl mb-4">CDN Chart Test</h1>
      <div className="text-green-400 text-lg mb-4">Status: {status}</div>
      
      <div 
        ref={chartContainerRef}
        className="border-2 border-blue-500 bg-gray-800"
        style={{ 
          width: '800px', 
          height: '400px',
        }}
      />
    </div>
  )
}
