// src/components/LayoutWrapper.tsx
'use client'

import React, { ReactNode, useEffect, useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'
import Script from 'next/script'
import { useLocale } from '../contexts/LocaleContext'
import ThemeToggle from './ThemeToggle'
import LanguageSelector from './LanguageSelector'
import '../layout.css'

interface User {
  id: number
  username: string
  email: string
  full_name: string
  avatar: string | null
}

export function LayoutWrapper({ children }: { children: ReactNode }) {
  const pathname = usePathname() || ''
  const isPublicUserPage = /^\/[^\/]+$/.test(pathname)
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const router = useRouter()
  const { t } = useLocale()

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const response = await fetch('/api/auth/user', {
            headers: { Authorization: `Bearer ${token}` },
          })
          if (response.ok) {
            const data = await response.json()
            setUser({
              id: data.id,
              username: data.username,
              email: data.email,
              full_name: data.full_name || '',
              avatar: data.avatar
            })
          } else {
            localStorage.removeItem('token')
            setUser(null)
          }
        } catch (error) {
          console.error('Auth check failed:', error)
          localStorage.removeItem('token')
          setUser(null)
        }
      }
      setIsLoading(false)
    }

    checkAuth()
  }, [])

  const handleLogout = () => {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('token')
    }
    setUser(null)
    router.push('/')
  }

  return (
    <>
      {!isPublicUserPage && (
        <nav className="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm border-bottom">
          <div className="container">
            <Link href="/" className="navbar-brand d-flex align-items-center">
              <Image
                src="/assets/img/CAT.png"
                alt="CatLink"
                width={32}
                height={32}
                className="me-2"
              />
              <span className="fw-bold">CatLink</span>
            </Link>
            
            {/* Убираем navbar-toggler и делаем всё всегда видимым */}
            <div className="d-flex justify-content-between align-items-center flex-grow-1">
              {/* Левое меню */}
              <ul className="navbar-nav d-flex flex-row me-auto">
                {user && (
                  <>
                    <li className="nav-item me-3">
                      <Link href="/dashboard" className="nav-link">
                        <i className="bi bi-speedometer2 me-1"></i>
                        {t('dashboard.title')}
                      </Link>
                    </li>
                    <li className="nav-item me-3">
                      <Link href="/profile" className="nav-link">
                        <i className="bi bi-person-gear me-1"></i>
                        {t('common.profile')}
                      </Link>
                    </li>
                  </>
                )}
              </ul>

              {/* Правое меню */}
              <div className="d-flex align-items-center gap-2">
                {/* Компоненты контекстов */}
                <ThemeToggle />
                <LanguageSelector />
                
                {isLoading ? (
                  <div className="spinner-border spinner-border-sm ms-2" role="status">
                    <span className="visually-hidden">{t('common.loading')}</span>
                  </div>
                ) : !user ? (
                  <div className="d-flex gap-2 ms-2">
                    <Link href="/auth/login" className="btn btn-outline-primary btn-sm">
                      <i className="bi bi-box-arrow-in-right me-1"></i>
                      <span className="d-none d-sm-inline">{t('common.login')}</span>
                    </Link>
                    <Link href="/auth/register" className="btn btn-primary btn-sm">
                      <i className="bi bi-person-plus me-1"></i>
                      <span className="d-none d-sm-inline">{t('common.register')}</span>
                    </Link>
                  </div>
                ) : (
                  <div className="dropdown ms-2">
                    <button
                      className="btn btn-outline-secondary dropdown-toggle d-flex align-items-center"
                      type="button"
                      data-bs-toggle="dropdown"
                    >
                      {user.avatar ? (
                        <Image
                          src={
                            user.avatar.startsWith('http')
                              ? user.avatar
                              : `http://localhost:8000${user.avatar}`
                          }
                          alt="Avatar"
                          width={24}
                          height={24}
                          className="rounded-circle me-2"
                        />
                      ) : (
                        <i className="bi bi-person-circle me-2"></i>
                      )}
                      <span className="d-none d-md-inline">
                        {user.full_name?.trim() || user.username}
                      </span>
                    </button>
                    <ul className="dropdown-menu dropdown-menu-end">
                      <li>
                        <Link href="/dashboard" className="dropdown-item">
                          <i className="bi bi-speedometer2 me-2"></i>
                          {t('dashboard.title')}
                        </Link>
                      </li>
                      <li>
                        <Link href="/profile" className="dropdown-item">
                          <i className="bi bi-person-gear me-2"></i>
                          {t('common.profile')}
                        </Link>
                      </li>
                      <li><hr className="dropdown-divider" /></li>
                      <li>
                        <button 
                          onClick={handleLogout}
                          className="dropdown-item text-danger"
                        >
                          <i className="bi bi-box-arrow-right me-2"></i>
                          {t('common.logout')}
                        </button>
                      </li>
                    </ul>
                  </div>
                )}
              </div>
            </div>
          </div>
        </nav>
      )}

      {!isPublicUserPage && <div style={{ height: '76px' }} />}

      {children}

      {!isPublicUserPage && (
        <footer className="bg-light footer border-top mt-5">
          <div className="container py-4">
            <div className="row">
              <div className="col-lg-6 text-center text-lg-start mb-2 mb-lg-0">
                <ul className="list-inline mb-1">
                  <li className="list-inline-item"><Link href="#">{t('footer.about')}</Link></li>
                  <li className="list-inline-item">⋅</li>
                  <li className="list-inline-item"><Link href="#">{t('footer.contact')}</Link></li>
                </ul>
                <p className="text-muted small mb-0">{t('footer.copyright')}</p>
              </div>
            </div>
          </div>
        </footer>
      )}

      <Script
        src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
        strategy="afterInteractive"
      />
      <Script src="/assets/js/bs-init.js" strategy="afterInteractive" />
    </>
  )
}
