"use client";

import React from "react";
import Nav from "./Nav";
import Image from "next/image";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import { useState, useEffect } from "react";

// Utils
import { userService } from "@/services/user.service";
import { fetchWrapper } from "@/helpers/fetch-wrapper";

// Context
import { useContextElement } from "@/context/Context";

// Lang Switcher 
import LanguageSwitcher from "@/components/LanguageSwitcher";

// Translation 
import { useT } from "@/context/I18nContext";

export default function Header4() {
     const { t } = useT();

	const [userData, setUserData] = useState([]);
	const [userState, setUserState] = useState(false);
	const [searchQuery, setSearchQuery] = useState("");
	const [isCategory, setIsCategory] = useState(false);
	const [settings, setSettings] = useState([]);
	const [bannerText, setBannerText] = useState("");

	const { cartProducts } = useContextElement();

	const router = useRouter();
	const pathname = usePathname();

	const cartCount = cartProducts.reduce((sum, item) => sum + (item.quantity || 0), 0);

	useEffect(() => {
		let alive = true;

		const safe = (fn) => alive && fn();

		const fetchUserData = async () => {
			try {
				const u = userService.userValue;

				// guest => nu chema endpoint-ul
				if (!u?.token) {
					safe(() => {
						setUserData([]);
						setUserState(false);
					});
					return;
				}

				const response = await fetchWrapper.get(`/api/users/getdata`);

				safe(() => {
					setUserData(response?.[0]?.userData ?? []);
					setUserState(true);
				});
			} catch (e) {
				safe(() => {
					setUserData([]);
					setUserState(false);
				});
			}
		};

		const fetchSiteSettings = async () => {
               try {
                    const response = await fetch(`/api/admin/settings`, {
                         method: "GET",
                         cache: "no-store",
                    });

                    if (!response.ok) return;

                    const data = await response.json();

                    const list = data?.settings ?? [];
                    setSettings(list);

                    const bannerSetting = list.find((s) => s.name === "bannerText");
                    if (bannerSetting?.value?.trim()) {
                         setBannerText(bannerSetting.value);
                    }
               } catch (e) {
                    console.error(e);
               }
          };

		fetchUserData();
		fetchSiteSettings();

		const sub = userService.user.subscribe(() => {
			fetchUserData();
			fetchSiteSettings();
		});

		return () => {
			alive = false;
			sub.unsubscribe();
		};
	}, []);

	// Verificăm dacă URL-ul curent este o categorie sau produs
	useEffect(() => {
		async function checkIfCategory() {
			if (!pathname || pathname === "/") {
				setIsCategory(false);
				return;
			}

			const slugPath = pathname.replace(/^\//, "");

			if (!slugPath) {
				setIsCategory(false);
				return;
			}

			try {
				const response = await fetch(`/api/categories/${slugPath}`);

				if (response.ok) {
					const data = await response.json();
					setIsCategory(data.productsData ? true : false);
				} else {
					setIsCategory(false);
				}
			} catch (error) {
				setIsCategory(false);
			}
		}

		checkIfCategory();
	}, [pathname]);

	const handleSearch = (e) => {
		e.preventDefault();

		if (!searchQuery.trim()) return;

		const sanitizedQuery = searchQuery.trim().slice(0, 100);

		if (pathname === "/" || pathname === "" || !isCategory) {
			router.push(`/?q=${encodeURIComponent(sanitizedQuery)}`);
		} else {
			router.push(`${pathname}?q=${encodeURIComponent(sanitizedQuery)}`);
		}
	};

	useEffect(() => {
		if (typeof window !== "undefined") {
			const params = new URLSearchParams(window.location.search);
			const currentQuery = params.get("q");
			if (currentQuery) {
				setSearchQuery(currentQuery);
			} else {
				setSearchQuery("");
			}
		}
	}, [pathname]);

	return (
		<>
			{/* Banner informativ */}
			{bannerText && (
				<div className='info-banner-wrapper'>
					<style jsx>{`
						.info-banner-wrapper {
							background: linear-gradient(135deg, #007bff 0%, #2da4d0ff 100%);
							position: relative;
							overflow: hidden;
						}

						.info-banner-wrapper::before {
							content: "";
							position: absolute;
							top: 0;
							left: -100%;
							width: 100%;
							height: 100%;
							background: linear-gradient(
								90deg,
								transparent,
								rgba(255, 255, 255, 0.1),
								transparent
							);
							animation: shine 3s infinite;
						}

						@keyframes shine {
							0% {
								left: -100%;
							}
							100% {
								left: 100%;
							}
						}

						.info-banner {
							padding: 12px 20px;
							animation: slideDown 0.4s ease-out;
						}

						@keyframes slideDown {
							from {
								transform: translateY(-100%);
								opacity: 0;
							}
							to {
								transform: translateY(0);
								opacity: 1;
							}
						}

						.banner-container {
							max-width: 1400px;
							margin: 0 auto;
							display: flex;
							align-items: center;
							justify-content: center;
							position: relative;
							gap: 12px;
						}

						.banner-icon {
							background: rgba(255, 255, 255, 0.2);
							width: 32px;
							height: 32px;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							flex-shrink: 0;
							backdrop-filter: blur(10px);
							box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
						}

						.banner-icon svg {
							width: 18px;
							height: 18px;
							color: white;
						}

						.banner-content {
							display: flex;
							align-items: center;
							gap: 8px;
						}

						.banner-text {
							color: white;
							font-size: 14px;
							font-weight: 500;
							letter-spacing: 0.3px;
							text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
							margin: 0;
							line-height: 1.4;
						}

						.close-button {
							position: absolute;
							right: 0;
							background: rgba(255, 255, 255, 0.15);
							border: none;
							width: 28px;
							height: 28px;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							cursor: pointer;
							transition: all 0.2s ease;
							backdrop-filter: blur(10px);
						}

						.close-button:hover {
							background: rgba(255, 255, 255, 0.25);
							transform: scale(1.1);
						}

						.close-button svg {
							width: 14px;
							height: 14px;
							color: white;
						}

						@media (max-width: 768px) {
							.info-banner {
								padding: 10px 15px;
							}

							.banner-text {
								font-size: 13px;
							}

							.banner-icon {
								width: 28px;
								height: 28px;
							}

							.banner-icon svg {
								width: 16px;
								height: 16px;
							}

							.close-button {
								width: 24px;
								height: 24px;
							}
						}

						@media (max-width: 480px) {
							.banner-container {
								gap: 8px;
							}

							.banner-text {
								font-size: 12px;
							}
						}
					`}</style>
					<div className='info-banner'>
						<div className='banner-container'>
							<div className='banner-icon'>
								<svg
									xmlns='http://www.w3.org/2000/svg'
									viewBox='0 0 24 24'
									fill='none'
									stroke='currentColor'
									strokeWidth='2.5'
									strokeLinecap='round'
									strokeLinejoin='round'>
									<circle cx='12' cy='12' r='10' />
									<line x1='12' y1='16' x2='12' y2='12' />
									<line x1='12' y1='8' x2='12.01' y2='8' />
								</svg>
							</div>

							<div className='banner-content'>
								<p className='banner-text'>{bannerText}</p>
							</div>
						</div>
					</div>
				</div>
			)}

			<header id='header' className='header-default header-style-2'>
				<style jsx>{`
					.info-banner {
						background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
						color: white;
						padding: 10px 0;
						text-align: center;
						font-size: 14px;
						font-weight: 500;
						box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
						animation: slideDown 0.3s ease-out;
					}

					.banner-content {
						display: flex;
						align-items: center;
						justify-content: center;
						gap: 8px;
					}

					.icon-info:before {
						content: "ℹ️";
						font-style: normal;
						margin-right: 4px;
					}

					@keyframes slideDown {
						from {
							transform: translateY(-100%);
							opacity: 0;
						}
						to {
							transform: translateY(0);
							opacity: 1;
						}
					}

					@media (max-width: 768px) {
						.info-banner {
							font-size: 13px;
							padding: 8px 0;
						}

						.banner-content span {
							padding: 0 10px;
						}
					}

					.tf-search-mobile {
						padding: 5px 6px 1px;
						background: transparent;
					}

					.tf-search-mobile form {
						display: flex;
						align-items: center;
						gap: 10px;
					}

					.tf-search-mobile input {
						flex: 1;
						height: 44px;
						border-radius: 10px;
						border: 1px solid #dcdcdc;
						background-color: #f7f7f7;
						padding: 0 14px;
						font-size: 15px;
						transition: all 0.2s ease-in-out;
					}

					.tf-search-mobile input:focus {
						outline: none;
						background-color: #fff;
						border-color: #0074d9;
						box-shadow: 0 0 0 2px rgba(0, 116, 217, 0.15);
					}

					.tf-search-mobile button {
						width: 44px;
						height: 44px;
						border: none;
						border-radius: 10px;
						background-color: #0074d9;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #fff;
						transition: background-color 0.2s ease-in-out;
					}

					.tf-search-mobile button:hover {
						background-color: #005bb5;
					}

					/* Badge pentru coș */
					.cart-badge-wrapper {
						position: relative;
						display: inline-block;
					}

					.cart-badge {
						position: absolute;
						top: -8px;
						right: -8px;
						background-color: #ff4444;
						color: white;
						border-radius: 50%;
						min-width: 20px;
						height: 20px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 11px;
						font-weight: 600;
						padding: 0 5px;
						box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
						z-index: 1;
					}

					@media (max-width: 992px) {
						.tf-search-mobile {
							margin-bottom: 16px;
						}
					}
				`}</style>
				<div className='main-header line'>
					<div className='container-full px_15 lg-px_40'>
						{/* Prima linie - Menu + Logo + Icons */}
						<div className='row wrapper-header align-items-center'>
							<div className='col-xl-2 tf-md-hidden'>
								<div className='tf-cur'>
									<Link href={`/`} className='logo-header'>
										<Image
											alt='logo'
											className='logo'
											src='/images/logo/emagyl.png'
											width={273}
											height={22}
										/>
									</Link>
								</div>
							</div>

							{/* Mobile: Menu burger */}
							<div className='col-4 tf-lg-hidden'>
								<a href='#mobileMenu' data-bs-toggle='offcanvas' aria-controls='offcanvasLeft'>
									<svg
										xmlns='http://www.w3.org/2000/svg'
										width={24}
										height={16}
										viewBox='0 0 24 16'
										fill='none'>
										<path
											d='M2.00056 2.28571H16.8577C17.1608 2.28571 17.4515 2.16531 17.6658 1.95098C17.8802 1.73665 18.0006 1.44596 18.0006 1.14286C18.0006 0.839753 17.8802 0.549063 17.6658 0.334735C17.4515 0.120408 17.1608 0 16.8577 0H2.00056C1.69745 0 1.40676 0.120408 1.19244 0.334735C0.978109 0.549063 0.857702 0.839753 0.857702 1.14286C0.857702 1.44596 0.978109 1.73665 1.19244 1.95098C1.40676 2.16531 1.69745 2.28571 2.00056 2.28571ZM0.857702 8C0.857702 7.6969 0.978109 7.40621 1.19244 7.19188C1.40676 6.97755 1.69745 6.85714 2.00056 6.85714H22.572C22.8751 6.85714 23.1658 6.97755 23.3801 7.19188C23.5944 7.40621 23.7148 7.6969 23.7148 8C23.7148 8.30311 23.5944 8.59379 23.3801 8.80812C23.1658 9.02245 22.8751 9.14286 22.572 9.14286H2.00056C1.69745 9.14286 1.40676 9.02245 1.19244 8.80812C0.978109 8.59379 0.857702 8.30311 0.857702 8ZM0.857702 14.8571C0.857702 14.554 0.978109 14.2633 1.19244 14.049C1.40676 13.8347 1.69745 13.7143 2.00056 13.7143H12.2863C12.5894 13.7143 12.8801 13.8347 13.0944 14.049C13.3087 14.2633 13.4291 14.554 13.4291 14.8571C13.4291 15.1602 13.3087 15.4509 13.0944 15.6653C12.8801 15.8796 12.5894 16 12.2863 16H2.00056C1.69745 16 1.40676 15.8796 1.19244 15.6653C0.978109 15.4509 0.857702 15.1602 0.857702 14.8571Z'
											fill='currentColor'
										/>
									</svg>
								</a>
							</div>

							{/* Mobile: Logo centrat */}
							<div className='col-4 tf-lg-hidden text-center'>
								<div className='tf-cur'>
									<Link href={`/`} className='logo-header only-mobile'>
										<Image
											alt='logo'
											className='logo'
											src='/images/logo/emagyl.png'
											width={136}
											height={21}
										/>
									</Link>
								</div>
							</div>

							{/* Desktop: Search bar */}
							<div className='col-xl-7 tf-md-hidden text-center'>
								<div className='tf-search-sticky nav-icon-text' style={{ width: "100%" }}>
									<form
										className='tf-mini-search-frm'
										onSubmit={handleSearch}
										style={{ display: "flex", alignItems: "center" }}>
										<fieldset className='tf-mini-search-frm' style={{ flexGrow: 1 }}>
											<input
												type='text'
												placeholder={t('cauta')}
												tabIndex='0'
												aria-required='true'
												required
												value={searchQuery}
												onChange={(e) => setSearchQuery(e.target.value)}
												style={{
													minHeight: "44px",
													width: "100%",
													padding: "10px 12px",
													fontSize: "16px",
												}}
											/>
										</fieldset>
									</form>
								</div>
							</div>

							{/* Icons - desktop full, mobile compressed */}
							<div className='col-xl-3 col-4'>
								<ul className='nav-icon d-flex justify-content-end align-items-center gap-20'>
									<li className='nav-cart tf-md-hidden'>
										<a
											href={userState ? "/contul-meu" : "/autentificare"}
											className='nav-icon-item'>
											<i className='icon icon-account' />{" "}
											<div className='nav-icon-text' style={{ marginLeft: 5 }}>
												{userState && userData ? (
													<>{userData.firstName + " " + userData.lastName}</>
												) : (
													<>{t("contul_meu")}</>
												)}
											</div>
										</a>
									</li>

									<li className='nav-cart'>
										<Link href={`/wishlist`} className='nav-icon-item'>
											<i className='icon icon-heart' style={{ fontSize: "20px" }} />
											<div
												className='nav-icon-text tf-md-hidden'
												style={{ marginLeft: 5 }}>
												{t('favorite')}
											</div>
										</Link>
									</li>

									<li className='nav-cart'>
										<Link href='/cos-de-cumparaturi' className='nav-icon-item'>
											<div className='cart-badge-wrapper'>
												<i className='icon icon-bag' style={{ fontSize: "20px" }} />
												{cartCount > 0 && (
													<span className='cart-badge'>{cartCount}</span>
												)}
											</div>
											<div
												className='nav-icon-text tf-md-hidden'
												style={{ marginLeft: 5 }}>
												{t('cosul_meu')}
											</div>
										</Link>
									</li>

                                             <li className='nav-cart tf-md-hidden' style={{ display: "flex", alignItems: "center" }}>
                                                  <LanguageSwitcher />
                                             </li>
								</ul>
							</div>
						</div>

						{/* A doua linie - Search bar DOAR pe mobile */}
						<div className='row tf-lg-hidden'>
							<div className='col-12'>
								<div className='tf-search-mobile'>
									<form onSubmit={handleSearch}>
										<input
											type='text'
											placeholder='Caută produse, branduri sau categorii'
											required
											value={searchQuery}
											onChange={(e) => setSearchQuery(e.target.value)}
										/>
										<button type='submit'>
											<svg
												xmlns='http://www.w3.org/2000/svg'
												width='18'
												height='18'
												viewBox='0 0 24 24'
												fill='none'
												stroke='currentColor'
												strokeWidth='2'
												strokeLinecap='round'
												strokeLinejoin='round'>
												<circle cx='11' cy='11' r='8'></circle>
												<path d='m21 21-4.35-4.35'></path>
											</svg>
										</button>
									</form>
								</div>
							</div>
						</div>
					</div>
				</div>

				{/* Desktop navigation */}
				<div className='header-bottom line tf-md-hidden'>
					<div className='container-full px_15 lg-px_40'>
						<div className='wrapper-header d-flex justify-content-start align-items-start'>
							<nav className='box-navigation text-center'>
								<ul className='box-nav-ul d-flex align-items-center justify-content-center gap-30'>
									<Nav />
								</ul>
							</nav>
						</div>
					</div>
				</div>
			</header>
		</>
	);
}
