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

export default function ChartAPITest() {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const [logs, setLogs] = useState<string[]>([])

  const addLog = (message: string) => {
    console.log(message)
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
  }

  useEffect(() => {
    if (!chartContainerRef.current) return

    const testLightweightCharts = async () => {
      try {
        addLog('Importing lightweight-charts...')
        
        const LightweightCharts = await import('lightweight-charts')
        addLog('Import successful')
        
        // Log what's available in the import
        addLog('Available exports: ' + Object.keys(LightweightCharts).join(', '))
        
        const { createChart } = LightweightCharts
        addLog('createChart function available: ' + (typeof createChart))
        
        // Create chart
        const chart = createChart(chartContainerRef.current!, {
          width: 600,
          height: 300,
        })
        addLog('Chart created')
        
        // Log chart methods
        const chartMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(chart))
        addLog('Chart methods: ' + chartMethods.join(', '))
        
        // Try to find the correct method for adding series
        if ('addCandlestickSeries' in chart) {
          addLog('addCandlestickSeries method found!')
        } else if ('addCandles' in chart) {
          addLog('addCandles method found!')
        } else if ('addSeries' in chart) {
          addLog('addSeries method found!')
        } else {
          addLog('No obvious candlestick method found')
        }

      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error)
        addLog(`Error: ${errorMessage}`)
        console.error('Error:', error)
      }
    }

    testLightweightCharts()
  }, [])

  return (
    <div className="min-h-screen bg-gray-900 p-8">
      <h1 className="text-white text-2xl mb-4">Lightweight Charts API Test</h1>
      
      <div className="mb-4">
        <div 
          ref={chartContainerRef} 
          className="bg-gray-800 border border-gray-600 rounded"
          style={{ width: '600px', height: '300px' }}
        />
      </div>

      <div>
        <h2 className="text-white text-lg mb-2">API Investigation Logs</h2>
        <div className="bg-gray-800 p-4 rounded max-h-96 overflow-y-auto">
          {logs.map((log, index) => (
            <div key={index} className="text-gray-300 text-sm font-mono mb-1">
              {log}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
