'use client'

import { useState, useEffect } from 'react'

export default function Dashboard() {
  const [greeting, setGreeting] = useState('')
  const [username] = useState('user')
  const [terms, setTerms] = useState('')
  const [loadingTerms, setLoadingTerms] = useState(true)
  const [time, setTime] = useState(new Date())
  const [settings, setSettings] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('settings')
      if (saved) {
        try {
          return JSON.parse(saved)
        } catch (e) {
          return null
        }
      }
    }
    return null
  })

  // getGreeting
  useEffect(() => {
    const updateGreeting = () => {
      const timeBasedGreeting = settings?.interface?.timeBasedGreeting !== false
      
      if (timeBasedGreeting) {
        const hour = new Date().getHours()
        if (hour >= 5 && hour < 12) {
          setGreeting('Good morning')
        } else if (hour >= 12 && hour < 18) {
          setGreeting('Good afternoon')
        } else if (hour >= 18 && hour < 22) {
          setGreeting('Good evening')
        } else {
          setGreeting('Good night')
        }
      } else {
        setGreeting('Hello')
      }
    }

    updateGreeting()
    const interval = setInterval(updateGreeting, 60000)
    return () => clearInterval(interval)
  }, [settings])

  // updateTime
  useEffect(() => {
    const interval = setInterval(() => {
      setTime(new Date())
    }, 1000)
    return () => clearInterval(interval)
  }, [])

  // parseMarkdown
  const parseMarkdown = (text) => {
    const lines = text.split('\n')
    const elements = []
    
    lines.forEach((line, index) => {
      if (line.startsWith('# ')) {
        elements.push(
          <h3 
            key={index} 
            className="text-xl font-bold mt-6 mb-3"
            style={{ color: '#ffffff' }}
          >
            {parseInlineMarkdown(line.substring(2))}
          </h3>
        )
      } else if (line.startsWith('## ')) {
        elements.push(
          <h4 
            key={index} 
            className="text-lg font-semibold mt-4 mb-2"
            style={{ color: '#ffffff' }}
          >
            {parseInlineMarkdown(line.substring(3))}
          </h4>
        )
      } else if (line.startsWith('### ')) {
        elements.push(
          <h5 
            key={index} 
            className="text-base font-semibold mt-3 mb-2"
            style={{ color: '#ffffff' }}
          >
            {parseInlineMarkdown(line.substring(4))}
          </h5>
        )
      } else if (line.trim().startsWith('- ')) {
        elements.push(
          <div 
            key={index} 
            className="flex gap-2 mb-1 ml-4"
          >
            <span style={{ color: '#565656' }}>•</span>
            <span style={{ color: '#a0a0a0' }}>
              {parseInlineMarkdown(line.trim().substring(2))}
            </span>
          </div>
        )
      } else if (line.trim() === '') {
        elements.push(<div key={index} className="h-2" />)
      } else {
        elements.push(
          <p 
            key={index} 
            className="mb-2"
            style={{ color: '#a0a0a0' }}
          >
            {parseInlineMarkdown(line)}
          </p>
        )
      }
    })
    
    return elements
  }

  // parseInlineMarkdown
  const parseInlineMarkdown = (text) => {
    const parts = []
    let currentIndex = 0
    let key = 0

    const boldRegex = /\*\*(.+?)\*\*/g
    const italicRegex = /\*(.+?)\*/g
    const codeRegex = /`(.+?)`/g
    
    const allMatches = []
    
    let match
    while ((match = boldRegex.exec(text)) !== null) {
      allMatches.push({ type: 'bold', index: match.index, length: match[0].length, content: match[1] })
    }
    
    while ((match = italicRegex.exec(text)) !== null) {
      const isBold = allMatches.some(m => m.type === 'bold' && match.index >= m.index && match.index < m.index + m.length)
      if (!isBold) {
        allMatches.push({ type: 'italic', index: match.index, length: match[0].length, content: match[1] })
      }
    }
    
    while ((match = codeRegex.exec(text)) !== null) {
      allMatches.push({ type: 'code', index: match.index, length: match[0].length, content: match[1] })
    }
    
    allMatches.sort((a, b) => a.index - b.index)
    
    allMatches.forEach(match => {
      if (match.index > currentIndex) {
        parts.push(text.substring(currentIndex, match.index))
      }
      
      if (match.type === 'bold') {
        parts.push(
          <strong key={key++} style={{ color: '#ffffff', fontWeight: 600 }}>
            {match.content}
          </strong>
        )
      } else if (match.type === 'italic') {
        parts.push(
          <em key={key++} style={{ fontStyle: 'italic' }}>
            {match.content}
          </em>
        )
      } else if (match.type === 'code') {
        parts.push(
          <code 
            key={key++} 
            className="px-1.5 py-0.5 rounded text-xs"
            style={{ 
              backgroundColor: 'rgba(255, 255, 255, 0.05)',
              color: '#3b82f6',
              fontFamily: 'monospace',
            }}
          >
            {match.content}
          </code>
        )
      }
      
      currentIndex = match.index + match.length
    })
    
    if (currentIndex < text.length) {
      parts.push(text.substring(currentIndex))
    }
    
    return parts.length > 0 ? parts : text
  }

  // loadTerms
  useEffect(() => {
    fetch('https://raw.githubusercontent.com/Aetheris-Softworks/Some-Database/refs/heads/main/terms.txt')
      .then(res => res.text())
      .then(data => {
        setTerms(data)
        setLoadingTerms(false)
      })
      .catch(err => {
        console.error('Failed to load terms:', err)
        setTerms('Failed to load Terms of Service. Please try again later.')
        setLoadingTerms(false)
      })
  }, [])

  useEffect(() => {
    // handleSettingsChange
    const handleSettingsChange = (e) => {
      setSettings(e.detail)
    }

    window.addEventListener('settingsChanged', handleSettingsChange)
    return () => {
      window.removeEventListener('settingsChanged', handleSettingsChange)
    }
  }, [])

  return (
    <div className="flex justify-center p-8">
      <div className="max-w-[1100px] w-full">
        <div 
          className="relative rounded-2xl border p-8 mb-6 overflow-hidden"
          style={{
            backgroundColor: 'rgba(10, 10, 10, 0.6)',
            borderColor: '#1a1a1a',
            backdropFilter: 'blur(20px)',
          }}
        >
          <div 
            className="absolute inset-0 opacity-30"
            style={{
              background: 'radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.15), transparent 50%), radial-gradient(circle at 80% 50%, rgba(168, 85, 247, 0.15), transparent 50%)',
            }}
          />
          
          <div className="relative z-10 flex items-center justify-between">
            <div>
              <h1 
                className="text-4xl font-bold mb-2 transition-opacity duration-500"
                style={{ 
                  color: '#ffffff',
                  textShadow: '0 0 30px rgba(255, 255, 255, 0.1)',
                }}
              >
                {greeting}, {username}.
              </h1>
              <p 
                className="text-sm"
                style={{ color: '#6b7280' }}
              >
                Welcome back to Aetheris Dashboard
              </p>
            </div>
            
            <div className="text-right">
              <div 
                className="text-3xl font-bold mb-1"
                style={{ color: '#ffffff' }}
              >
                {time.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
              </div>
              <div 
                className="text-sm"
                style={{ color: '#6b7280' }}
              >
                {time.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-3 mb-6">
          <div 
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm backdrop-blur-xl transition-all duration-200"
            style={{
              backgroundColor: 'rgba(34, 197, 94, 0.1)',
              border: '1px solid rgba(34, 197, 94, 0.3)',
              boxShadow: '0 0 20px rgba(34, 197, 94, 0.1)',
            }}
          >
            <div 
              className="w-2 h-2 rounded-full animate-pulse"
              style={{ 
                backgroundColor: '#22c55e',
                boxShadow: '0 0 8px rgba(34, 197, 94, 0.8)',
              }}
            />
            <span style={{ color: '#22c55e', fontWeight: 600 }}>
              Aetheris Online
            </span>
          </div>

          <div 
            className="px-4 py-2 rounded-xl text-sm backdrop-blur-xl"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.8)',
              border: '1px solid #1a1a1a',
              color: '#9ca3af',
            }}
          >
            Subscription: <span style={{ color: '#ffffff', fontWeight: 600 }}>Basic</span>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div 
            className="relative rounded-2xl border p-6 overflow-hidden group transition-all duration-300"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.6)',
              borderColor: '#1a1a1a',
              backdropFilter: 'blur(20px)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = 'rgba(59, 130, 246, 0.3)'
              e.currentTarget.style.transform = 'translateY(-2px)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = '#1a1a1a'
              e.currentTarget.style.transform = 'translateY(0)'
            }}
          >
            <div 
              className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
              style={{
                background: 'radial-gradient(circle at 50% 0%, rgba(59, 130, 246, 0.1), transparent 70%)',
              }}
            />
            <div className="relative z-10">
              <div 
                className="text-sm mb-3 font-medium"
                style={{ color: '#6b7280' }}
              >
                Total Executed Scripts
              </div>
              <div 
                className="text-5xl font-bold"
                style={{ 
                  color: '#3b82f6',
                  textShadow: '0 0 30px rgba(59, 130, 246, 0.3)',
                }}
              >
                28
              </div>
            </div>
          </div>

          <div 
            className="relative rounded-2xl border p-6 overflow-hidden group transition-all duration-300"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.6)',
              borderColor: '#1a1a1a',
              backdropFilter: 'blur(20px)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = 'rgba(168, 85, 247, 0.3)'
              e.currentTarget.style.transform = 'translateY(-2px)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = '#1a1a1a'
              e.currentTarget.style.transform = 'translateY(0)'
            }}
          >
            <div 
              className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
              style={{
                background: 'radial-gradient(circle at 50% 0%, rgba(168, 85, 247, 0.1), transparent 70%)',
              }}
            />
            <div className="relative z-10">
              <div 
                className="text-sm mb-3 font-medium"
                style={{ color: '#6b7280' }}
              >
                Quick Actions
              </div>
              <div className="flex flex-wrap gap-2">
                {[
                  { label: 'Executor', id: 'executor' },
                  { label: 'Script Hub', id: 'scripthub' },
                  { label: 'Games', id: 'games' }
                ].map((action) => (
                  <button
                    key={action.id}
                    onClick={() => {
                      const event = new CustomEvent('changeTab', { detail: action.id })
                      window.dispatchEvent(event)
                    }}
                    className="px-4 py-2 rounded-xl text-sm font-semibold transition-all duration-200"
                    style={{
                      backgroundColor: 'rgba(168, 85, 247, 0.1)',
                      border: '1px solid rgba(168, 85, 247, 0.2)',
                      color: '#a855f7',
                      cursor: 'pointer',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = 'rgba(168, 85, 247, 0.2)'
                      e.currentTarget.style.borderColor = 'rgba(168, 85, 247, 0.4)'
                      e.currentTarget.style.transform = 'scale(1.05)'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = 'rgba(168, 85, 247, 0.1)'
                      e.currentTarget.style.borderColor = 'rgba(168, 85, 247, 0.2)'
                      e.currentTarget.style.transform = 'scale(1)'
                    }}
                  >
                    {action.label}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div 
            className="relative rounded-2xl border p-6 overflow-hidden group transition-all duration-300"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.6)',
              borderColor: '#1a1a1a',
              backdropFilter: 'blur(20px)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = 'rgba(236, 72, 153, 0.3)'
              e.currentTarget.style.transform = 'translateY(-2px)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = '#1a1a1a'
              e.currentTarget.style.transform = 'translateY(0)'
            }}
          >
            <div 
              className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
              style={{
                background: 'radial-gradient(circle at 50% 0%, rgba(236, 72, 153, 0.1), transparent 70%)',
              }}
            />
            <div className="relative z-10">
              <div 
                className="text-sm mb-3 font-medium"
                style={{ color: '#6b7280' }}
              >
                Social
              </div>
              <div className="flex flex-wrap gap-2">
                {[
                  { label: 'Discord', url: 'https://discord.gg/getaetheris' },
                  { label: 'Tiktok', url: 'https://tiktok.com/@aetheris.bestside.lol' },
                  { label: 'Website', url: 'https://aetheris.lol' }
                ].map((social) => (
                  <a
                    key={social.label}
                    href={social.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="px-4 py-2 rounded-xl text-sm font-semibold transition-all duration-200 block"
                    style={{
                      backgroundColor: 'rgba(236, 72, 153, 0.1)',
                      border: '1px solid rgba(236, 72, 153, 0.2)',
                      color: '#ec4899',
                      textDecoration: 'none',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = 'rgba(236, 72, 153, 0.2)'
                      e.currentTarget.style.borderColor = 'rgba(236, 72, 153, 0.4)'
                      e.currentTarget.style.transform = 'scale(1.05)'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = 'rgba(236, 72, 153, 0.1)'
                      e.currentTarget.style.borderColor = 'rgba(236, 72, 153, 0.2)'
                      e.currentTarget.style.transform = 'scale(1)'
                    }}
                  >
                    {social.label}
                  </a>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div 
          className="relative rounded-2xl border p-6 overflow-hidden"
          style={{
            backgroundColor: 'rgba(10, 10, 10, 0.6)',
            borderColor: '#1a1a1a',
            backdropFilter: 'blur(20px)',
          }}
        >
          <div 
            className="absolute top-0 left-0 right-0 h-px"
            style={{
              background: 'linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.5), transparent)',
            }}
          />
          
          <div className="flex items-center justify-between mb-4">
            <h2 
              className="text-xl font-bold"
              style={{ color: '#ffffff' }}
            >
              Terms of Service
            </h2>
          </div>

          {loadingTerms ? (
            <div className="flex flex-col items-center justify-center py-16">
              <div 
                className="w-12 h-12 border-3 rounded-full animate-spin mb-4"
                style={{
                  borderColor: '#1a1a1a',
                  borderTopColor: '#3b82f6',
                  borderWidth: '3px',
                }}
              />
              <div 
                className="text-sm"
                style={{ color: '#6b7280' }}
              >
                Loading terms...
              </div>
            </div>
          ) : (
            <div 
              className="text-sm overflow-y-auto p-4 rounded-xl"
              style={{ 
                lineHeight: '1.7',
                maxHeight: '400px',
                backgroundColor: 'rgba(0, 0, 0, 0.3)',
                border: '1px solid #1a1a1a',
              }}
            >
              {parseMarkdown(terms)}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
