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

export default function MinimalChartTest() {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const [status, setStatus] = useState('Starting...')
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!chartContainerRef.current) {
      setStatus('No container ref')
      return
    }

    const initChart = async () => {
      try {
        setStatus('Loading lightweight-charts...')
        console.log('Starting chart init...')
        
        const LightweightCharts = await import('lightweight-charts')
        console.log('Lightweight charts loaded:', LightweightCharts)
        setStatus('Charts library loaded')
        
        const { createChart } = LightweightCharts
        console.log('createChart:', typeof createChart)
        
        setStatus('Creating chart...')
        const chart = createChart(chartContainerRef.current!, {
          width: 800,
          height: 400,
        })
        console.log('Chart created:', chart)
        setStatus('Chart created')
        
        setStatus('Adding series...')
        const series = chart.addCandlestickSeries({})
        console.log('Series created:', series)
        setStatus('Series added')
        
        setStatus('Adding data...')
        const data = [
          { time: '2025-01-01', open: 100, high: 110, low: 90, close: 105 },
          { time: '2025-01-02', open: 105, high: 115, low: 95, close: 110 },
          { time: '2025-01-03', open: 110, high: 120, low: 100, close: 115 },
        ]
        series.setData(data)
        console.log('Data set')
        setStatus('Chart ready!')
        
      } catch (err) {
        console.error('Chart init error:', err)
        const errorMsg = err instanceof Error ? err.message : String(err)
        setError(errorMsg)
        setStatus(`Error: ${errorMsg}`)
      }
    }

    initChart()
  }, [])

  return (
    <div className="min-h-screen bg-gray-900 p-8">
      <h1 className="text-white text-2xl mb-4">Minimal Chart Test</h1>
      <div className="text-gray-300 mb-4">Status: {status}</div>
      {error && (
        <div className="text-red-400 mb-4 p-4 bg-red-900/20 rounded">
          Error: {error}
        </div>
      )}
      <div 
        ref={chartContainerRef} 
        className="bg-gray-800 border border-gray-600"
        style={{ width: '800px', height: '400px' }}
      />
    </div>
  )
}
