'use client'

import { useRef, useEffect, useState } from 'react'
import { Home, Code, FileText, Gamepad2, Folder, Settings, User, LogOut } from 'lucide-react'

const items = [
  { id: 'dashboard', label: 'Dashboard', icon: Home },
  { id: 'executor', label: 'Executor', icon: Code },
  { id: 'scripthub', label: 'Script Hub', icon: FileText },
  { id: 'games', label: 'Games', icon: Gamepad2 },
  { id: 'miscellaneous', label: 'Miscellaneous', icon: Folder },
  { id: 'settings', label: 'Settings', icon: Settings },
  { id: 'profile', label: 'Profile', icon: User },
]

export default function Sidebar({ tab, setTab }) {
  const refs = useRef({})
  const [style, setStyle] = useState({})
  const [clickCount, setClickCount] = useState(0)
  const clickTimer = useRef(null)
  const [currentAd, setCurrentAd] = useState(null)
  const [ads, setAds] = useState([])
  const [adFading, setAdFading] = useState(false)
  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
  })

  useEffect(() => {
    // loadAds
    fetch('/ads.json')
      .then(res => res.json())
      .then(data => {
        setAds(data)
        if (data.length > 0) {
          setCurrentAd(data[Math.floor(Math.random() * data.length)])
        }
      })
      .catch(err => console.error('Failed to load ads:', err))
  }, [])

  useEffect(() => {
    // rotateAds
    if (ads.length > 1) {
      const interval = setInterval(() => {
        setAdFading(true)
        setTimeout(() => {
          setCurrentAd(ads[Math.floor(Math.random() * ads.length)])
          setAdFading(false)
        }, 300)
      }, 15000)
      return () => clearInterval(interval)
    }
  }, [ads])

  // handleLogoClick
  const handleLogoClick = () => {
    setClickCount(prev => prev + 1)

    if (clickTimer.current) {
      clearTimeout(clickTimer.current)
    }

    clickTimer.current = setTimeout(() => {
      if (clickCount + 1 >= 5) {
        window.open('https://yaica.market/', '_blank')
      } else {
        setTab('dashboard')
      }
      setClickCount(0)
    }, 300)
  }

  useEffect(() => {
    const btn = refs.current[tab]
    if (btn) {
      const { offsetTop, offsetHeight } = btn
      setStyle({
        top: offsetTop,
        height: offsetHeight,
      })
    }
  }, [tab])

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

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

  const compactSidebar = settings?.interface?.compactSidebar || false
  const sidebarWidth = compactSidebar ? 200 : 280
  const enableAnimations = settings?.interface?.enableAnimations !== false

  return (
    <aside 
      className="fixed left-0 top-0 z-50 h-screen flex flex-col p-3"
      style={{ 
        backgroundColor: '#000000',
        width: `${sidebarWidth}px`,
        transition: enableAnimations ? 'width 300ms ease-out' : 'none',
      }}
    >
      <div 
        className="flex flex-col h-full rounded-xl border backdrop-blur-xl"
        style={{ 
          backgroundColor: 'rgba(10, 10, 10, 0.8)',
          borderColor: '#1a1a1a'
        }}
      >
        <div 
          className="flex h-16 items-center border-b px-6 flex-shrink-0"
          style={{ borderColor: '#1a1a1a' }}
        >
          <div
            onClick={handleLogoClick}
            className="flex items-center gap-2 text-xl font-bold transition-colors cursor-pointer"
            style={{ color: '#ffffff', userSelect: 'none' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.opacity = '0.8'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.opacity = '1'
            }}
          >
            <img 
              src="/aetheris.svg" 
              alt="Aetheris" 
              className="w-6 h-6"
              draggable="false"
            />
            Aetheris
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-4">
          <nav className="space-y-6">
            <div>
              <h3 
                className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider"
                style={{ color: '#606060' }}
              >
                Menu
              </h3>
              <div className="space-y-1 relative">
                <div
                  className="absolute left-0 rounded-lg pointer-events-none"
                  style={{
                    top: style.top,
                    height: style.height,
                    width: '100%',
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    boxShadow: '0 0 30px rgba(255, 255, 255, 0.25), 0 0 15px rgba(255, 255, 255, 0.15)',
                    transition: enableAnimations ? 'all 300ms ease-out' : 'none',
                  }}
                />
                
                {items.map((item) => {
                  const Icon = item.icon
                  const active = tab === item.id
                  
                  return (
                    <button
                      key={item.id}
                      ref={(el) => (refs.current[item.id] = el)}
                      onClick={() => setTab(item.id)}
                      className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium relative z-10"
                      style={{
                        color: active ? '#000000' : '#a0a0a0',
                        backgroundColor: 'transparent',
                        transition: enableAnimations ? 'color 300ms ease-out, background-color 200ms ease-out' : 'none',
                        cursor: 'pointer',
                        userSelect: 'none',
                      }}
                      onMouseEnter={(e) => {
                        if (!active) {
                          e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.03)';
                        }
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent';
                      }}
                    >
                      <Icon 
                        className="h-5 w-5 flex-shrink-0" 
                        style={{ 
                          color: active ? '#000000' : '#565656',
                          transition: enableAnimations ? 'color 300ms ease-out' : 'none',
                        }}
                      />
                      <span className="flex-1 text-left">{item.label}</span>
                    </button>
                  )
                })}
              </div>
            </div>
          </nav>
        </div>

        {currentAd && (
          <div className="px-4 pb-4">
            <a
              href={currentAd.href}
              target="_blank"
              rel="noopener noreferrer"
              className="block relative rounded-xl overflow-hidden transition-all duration-300"
              style={{
                backgroundColor: '#0a0a0a',
                border: '1px solid #1a1a1a',
                opacity: adFading ? 0 : 1,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = '#2a2a2a'
                e.currentTarget.style.transform = 'scale(1.02)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = '#1a1a1a'
                e.currentTarget.style.transform = 'scale(1)'
              }}
            >
              <div
                className="absolute top-2 right-2 px-1.5 py-0.5 rounded text-xs font-medium z-10"
                style={{
                  backgroundColor: 'rgba(0, 0, 0, 0.7)',
                  color: '#a0a0a0',
                  border: '1px solid #2a2a2a',
                  fontSize: '10px',
                }}
              >
                Ad
              </div>
              <img
                src={`/ads/${currentAd.file}`}
                alt="Advertisement"
                className="w-full h-auto"
                style={{
                  aspectRatio: '1 / 1',
                  objectFit: 'cover',
                }}
              />
            </a>
          </div>
        )}

        <div 
          className="border-t p-4"
          style={{ borderColor: '#1a1a1a' }}
        >
          <button
            className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200"
            style={{
              backgroundColor: 'transparent',
              color: '#a0a0a0',
              cursor: 'pointer',
              userSelect: 'none',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'rgba(239, 68, 68, 0.1)';
              e.currentTarget.style.color = '#ef4444';
              const icon = e.currentTarget.querySelector('svg');
              if (icon) icon.style.color = '#ef4444';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'transparent';
              e.currentTarget.style.color = '#a0a0a0';
              const icon = e.currentTarget.querySelector('svg');
              if (icon) icon.style.color = '#565656';
            }}
          >
            <LogOut 
              className="h-5 w-5 flex-shrink-0" 
              style={{ color: '#565656' }}
            />
            <span className="flex-1 text-left">Logout</span>
          </button>
        </div>
      </div>
    </aside>
  )
}
