// 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'

interface User {
  username: string
  avatar: string | null
}

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

  // При монтировании пробуем загрузить профиль
  useEffect(() => {
    const token = localStorage.getItem('token')
    if (token) {
      fetch('/api/auth/user', {
        headers: { Authorization: `Bearer ${token}` },
      })
        .then(res => {
          if (!res.ok) throw new Error()
          return res.json()
        })
        .then(data => {
          // fullname или username
          const name = data.full_name?.trim() || data.username
          setUser({ username: name, avatar: data.avatar })
        })
        .catch(() => {
          // сбросить некорректный токен
          localStorage.removeItem('token')
          setUser(null)
        })
    }
  }, [])

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

  return (
    <>
      {/* Шапка не выводим на публичных страницах /[username] */}
      {!isPublicUserPage && (
        <nav className="navbar navbar-expand bg-light fixed-top shadow-sm">
          <div className="container">
            <Link href="/" className="navbar-brand d-flex align-items-center">
              <Image
                src="/assets/img/CAT.png"
                alt="CatLink"
                width={89}
                height={89}
              />
              <span className="ms-2">CatLink</span>
            </Link>
            <button
              className="navbar-toggler"
              type="button"
              data-bs-toggle="collapse"
              data-bs-target="#navcol-1"
            />
            <div className="collapse navbar-collapse" id="navcol-1">
              {!user && (
                <Link href="/auth/login" className="btn btn-primary ms-auto">
                  <i className="fa fa-user"></i>
                  <span className="d-none d-sm-inline"> Вход</span>
                </Link>
              )}
              {user && (
                <div className="ms-auto d-flex align-items-center gap-3">
                  <Image
                    src={
                      user.avatar && user.avatar.startsWith('http')
                        ? user.avatar
                        : user.avatar 
                          ? `http://localhost:8000${user.avatar}`
                          : '/assets/img/avatar-dhg.png'
                    }
                    alt="Avatar"
                    width={32}
                    height={32}
                    className="rounded-circle"
                  />
                  <span>{user.username}</span>
                  {!isDashboard && (
                    <Link href="/dashboard" className="btn btn-outline-secondary btn-sm">
                      Дашборд
                    </Link>
                  )}
                  <button
                    onClick={handleLogout}
                    className="btn btn-outline-danger btn-sm"
                  >
                    Выход
                  </button>
                </div>
              )}
            </div>
          </div>
        </nav>
      )}

      {/* отступ, чтобы контент не прятался под фиксированным хедером */}
      {!isPublicUserPage && <div style={{ height: 70 }} />}

      {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="#">About</Link></li>
                  <li className="list-inline-item">⋅</li>
                  <li className="list-inline-item"><Link href="#">Contact</Link></li>
                  <li className="list-inline-item">⋅</li>
                  <li className="list-inline-item"><Link href="#">Terms of Use</Link></li>
                  <li className="list-inline-item">⋅</li>
                  <li className="list-inline-item"><Link href="#">Privacy Policy</Link></li>
                </ul>
                <p className="text-muted small mb-0">© CatLink 2025</p>
              </div>
              <div className="col-lg-6 text-center text-lg-end">
                <ul className="list-inline mb-0">
                  <li className="list-inline-item"><Link href="#"><i className="fa fa-facebook fa-lg fa-fw"></i></Link></li>
                  <li className="list-inline-item"><Link href="#"><i className="fa fa-twitter fa-lg fa-fw"></i></Link></li>
                  <li className="list-inline-item"><Link href="#"><i className="fa fa-instagram fa-lg fa-fw"></i></Link></li>
                </ul>
              </div>
            </div>
          </div>
        </footer>
      )}

      {/* Bootstrap JS */}
      {/* Bootstrap JS: load after React hydrates to avoid DOM mutations during hydration */}
      <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" />
    </>
  )
}
