"use client";
import { useContextElement } from "@/context/Context";
import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import countriesData from "@/data/countries.json";
import { ArrowBigLeft, MapPin, Plus, Star, Building2, User, CheckCircle } from "lucide-react";
import { fetchWrapper } from "@/helpers/fetch-wrapper";
import Swal from "sweetalert2";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import { useT, getProductCoin, getProductPrice, getRONtoEURRate, getProductLanguage } from "@/context/I18nContext";

const CountrySelect = ({ value, onChange }) => {
	const { t } = useT();

	return (
		<fieldset className='box fieldset'>
			<label htmlFor='country'>{t("checkout_tara")}</label>
			<div className='select-custom'>
				<select
					required
					className='tf-select w-100'
					id='country'
					name='address[country]'
					value={value}
					onChange={(e) => onChange(e.target.value)}>
					<option value=''>---</option>
					{countriesData.map((country) => (
						<option key={country.name} value={country.name}>
							{country.name}
						</option>
					))}
				</select>
			</div>
		</fieldset>
	);
};

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

     const isEN = t("variable_categorii") != 'name';
     const [eurRate, setEurRate] = useState(null);

     useEffect(() => {
          if (isEN) getRONtoEURRate().then(setEurRate);
     }, [isEN]);

     const convertPrice = (price) => {
          if (isEN && eurRate) return (Math.ceil(price * eurRate) - 0.01).toFixed(2);
          return parseFloat(price).toFixed(2);
     }; 

	const { cartProducts } = useContextElement();
	const [cartItems, setCartItems] = useState([]);
	const [totalPrice, setTotalPrice] = useState(0);
	const [billingType, setBillingType] = useState(false);
	const [paymentMethod, setPaymentMethod] = useState("card");
	const [formData, setFormData] = useState({
		country: "Romania",
	});

	const [savedAddresses, setSavedAddresses] = useState([]);
	const [saveAddress, setSaveAddress] = useState(false);
	const [addressLabel, setAddressLabel] = useState("");
	const [selectedAddressId, setSelectedAddressId] = useState(null);

	useEffect(() => {
		fetchWrapper
			.get("/api/users/addresses")
			.then((data) => setSavedAddresses(data.addresses || []))
			.catch(() => {});
	}, []);

	const applyAddress = (addr) => {
		if (!addr) return; // formular gol - user vrea adresă nouă
		setSelectedAddressId(addr.id);
		setBillingType(addr.billingType === 1);

		if (addr.billingType === 0) {
			console.log("Applying PF address:", addr);
			setFormData({
				"first-name": addr.pf_prenume,
				"last-name": addr.pf_nume_familie,
				country: addr.pf_tara || "Romania",
				city: addr.pf_judet_oras,
				address: addr.pf_adresa,
				phone: addr.pf_numar_telefon,
				email: addr.pf_email,
			});
		} else {
			setFormData({
				"nume-firma": addr.pj_nume_firma,
				cui: addr.pj_cui,
				"nr-inregistrare": addr.pj_nr_reg,
				banca: addr.pj_banca,
				iban: addr.pj_iban,
				judet: addr.pj_judet,
				localitate: addr.pj_localitate,
				adresa_firma: addr.pj_adresa,
				adresa_livrare: addr.pj_adresa_livrare,
				phone: addr.pj_numar_telefon,
				email: addr.pj_email,
			});
		}
		toast.success(`Adresă aplicată: ${addr.label || addr.pf_prenume || addr.pj_nume_firma}`);
	};

	const [errors, setErrors] = useState({});
	const [romaniaData, setRomaniaData] = useState(null);

	const [complianceTerms, setComplianceTerms] = useState(false);
	const [compliancePrivacy, setCompliancePrivacy] = useState(false);

	const [pjNames] = useState({
		"nume-firma": t("checkout_pj_nume_firma"),
		cui: t("checkout_pj_cui"),
		"nr-inregistrare": t("checkout_pj_nr_reg"),
		banca: t("checkout_pj_bank"),
		iban: t("checkout_pj_iban"),
		judet: t("checkout_pj_judet"),
		localitate: t("checkout_pj_localitate"),
		adresa_firma: t("checkout_pj_adresa_firma"),
		adresa_livrare: t("checkout_pj_adresa_livrare"),
		phone: t("checkout_numar_telefon"),
		email: "Email",
	});

	// Helper function pentru a calcula prețul corect
	const getFinalPrice = (product) => {
		if (product.priceReduced && parseFloat(product.priceReduced) < parseFloat(product.price)) {
			return parseFloat(product.priceReduced);
		}
		return parseFloat(product.price);
	};

	// Helper function pentru a verifica dacă produsul e la reducere
	const isReduced = (product) => {
		return product.priceReduced && parseFloat(product.priceReduced) < parseFloat(product.price);
	};

	function CartItemPrice({ elm }) {
		const price = getProductPrice(elm.price);
		const priceReduced = getProductPrice(elm.priceReduced);
		const coin = getProductCoin();

		if (isReduced(elm)) {
			return (
				<div className='price-wrapper'>
					<span className='price-original'>
						{price} {coin}
					</span>
					<span className='price-reduced'>
						{priceReduced} {coin}
					</span>
				</div>
			);
		}
		return (
			<span className='price'>
				{price} {coin}
			</span>
		);
	}

	// Fetch Romania data from local file
	useEffect(() => {
		fetch("/romania-regions.json")
			.then((res) => {
				if (!res.ok) throw new Error("Failed to load Romania data");
				return res.json();
			})
			.then((data) => {
				console.log("Romania data loaded:", Object.keys(data).length, "counties");
				setRomaniaData(data);
			})
			.catch((err) => {
				console.error("Error loading Romania data:", err);
				toast.error("Nu s-au putut încărca datele de localizare");
			});
	}, []);

	useEffect(() => {
		if (cartProducts && cartProducts.length > 0) {
			const validIds = cartProducts.map((item) => item.id).filter((id) => /^\d+$/.test(id));

			if (validIds.length > 0) {
				fetch(`/api/productsdatabyids?ids=${validIds.join(",")}`)
					.then((res) => res.json())
					.then((data) => {
						const itemsWithQty = data.wishlistProducts.map((product) => {
							const cartItem = cartProducts.find((item) => item.id == product.id);
							return {
								...product,
								quantity: cartItem ? cartItem.quantity : 1,
							};
						});

						setCartItems(itemsWithQty);

						// Calculăm prețul total cu priceReduced
						const newTotalPrice = data.wishlistProducts.reduce((sum, product) => {
							const cartItem = cartProducts.find((item) => item.id == product.id);
							const quantity = cartItem ? cartItem.quantity : 0;
							const price = getFinalPrice(product);
							return sum + price * quantity;
						}, 0);

						setTotalPrice(newTotalPrice + 22);
					})
					.catch((err) => console.error("Error fetching products:", err));
			} else {
				setCartItems([]);
				setTotalPrice(0);
			}
		} else {
			setCartItems([]);
			setTotalPrice(0);
		}
	}, [cartProducts]);

	const openLocationSelector = async () => {
		if (!romaniaData) {
			toast.error("Se încarcă datele de localizare. Încearcă din nou!");
			return;
		}

		const counties = Object.keys(romaniaData).sort();

		const { value: selectedCounty } = await Swal.fire({
			title: "Selectează județul",
			input: "select",
			inputOptions: counties.reduce((acc, county) => {
				acc[county] = county;
				return acc;
			}, {}),
			inputPlaceholder: "Alege județul",
			showCancelButton: true,
			cancelButtonText: "Anulează",
			confirmButtonText: "Următorul →",
			inputValidator: (value) => {
				if (!value) {
					return "Trebuie să selectezi un județ!";
				}
			},
			customClass: {
				confirmButton: "swal2-confirm swal2-styled",
				cancelButton: "swal2-cancel swal2-styled",
			},
		});

		if (selectedCounty) {
			const cities = romaniaData[selectedCounty]
				.map((city) => city.name)
				.filter((value, index, self) => self.indexOf(value) === index)
				.sort();

			const { value: selectedCity } = await Swal.fire({
				title: `Selectează orașul din ${selectedCounty}`,
				html: `
					<div style="margin-bottom: 15px;">
						<input 
							type="text" 
							id="city-search" 
							class="swal2-input" 
							placeholder="Caută oraș (ex: Cluj, Bucuresti)..." 
							style="margin: 0; width: 100%; font-size: 14px;"
						>
					</div>
					<select 
						id="city-select" 
						class="swal2-input" 
						size="12" 
						style="width: 100%; height: 350px; margin: 0; font-size: 14px; cursor: pointer;"
					>
						${cities.map((city) => `<option value="${city}">${city}</option>`).join("")}
					</select>
					<p style="margin-top: 10px; font-size: 12px; color: #666;">
						💡 Poți da dublu-click pe oraș pentru confirmare rapidă
					</p>
				`,
				showCancelButton: true,
				cancelButtonText: "← Înapoi",
				confirmButtonText: "Confirmă",
				width: "600px",
				didOpen: () => {
					const searchInput = document.getElementById("city-search");
					const citySelect = document.getElementById("city-select");

					searchInput.focus();

					searchInput.addEventListener("input", (e) => {
						const search = e.target.value.toLowerCase().trim();
						const options = citySelect.options;
						let firstVisible = null;

						for (let i = 0; i < options.length; i++) {
							const city = options[i].text.toLowerCase();
							const matches = city.includes(search);
							options[i].style.display = matches ? "" : "none";

							if (matches && !firstVisible) {
								firstVisible = options[i];
							}
						}

						if (firstVisible) {
							citySelect.value = firstVisible.value;
						}
					});

					citySelect.addEventListener("dblclick", () => {
						Swal.clickConfirm();
					});

					searchInput.addEventListener("keydown", (e) => {
						if (e.key === "Enter" && citySelect.value) {
							Swal.clickConfirm();
						}
					});
				},
				preConfirm: () => {
					const citySelect = document.getElementById("city-select");
					const selectedCity = citySelect.value;
					if (!selectedCity) {
						Swal.showValidationMessage("Trebuie să selectezi un oraș!");
						return false;
					}
					return selectedCity;
				},
			});

			if (selectedCity) {
				const locationString = `${selectedCounty}, ${selectedCity}`;
				setFormData((prev) => ({ ...prev, city: locationString }));

				setErrors((prev) => {
					const newErrors = { ...prev };
					delete newErrors.city;
					return newErrors;
				});

				toast.success(`Locație selectată: ${locationString}`);
			} else if (selectedCity === undefined) {
				openLocationSelector();
			}
		}
	};

	const handleInputChange = (e) => {
		setFormData((prev) => ({
			...prev,
			[e.target.id]: e.target.value,
		}));
	};

	const validateForm = () => {
		const newErrors = {};
		if (!billingType) {
			["first-name", "last-name", "country", "city", "address", "phone", "email"].forEach((field) => {
				if (!formData[field] || formData[field].trim() === "") {
					newErrors[field] = "Acest câmp este obligatoriu";
				}
			});
		} else {
			[
				"nume-firma",
				"cui",
				"nr-inregistrare",
				"banca",
				"iban",
				"judet",
				"localitate",
				"adresa_firma",
				"adresa_livrare",
				"phone",
				"email",
			].forEach((field) => {
				if (!formData[field] || formData[field].trim() === "") {
					newErrors[field] = "Acest câmp este obligatoriu";
				}
			});
		}

		setErrors(newErrors);
		return Object.keys(newErrors).length === 0;
	};

	const handleCheckout = async () => {
		if (!compliancePrivacy || !complianceTerms) {
			toast.error("Trebuie să acceptați termenii și condițiile și politica de confidențialitate.");
			return;
		}

		if (!validateForm()) {
			toast.error("Te rugăm să completezi toate câmpurile obligatorii!");
			return;
		}

		const loadingToast = toast.loading("Se procesează comanda...");

		try {
			if (saveAddress) {
				const addrPayload = billingType
					? {
							billingType: 1,
							label: addressLabel || "Adresă firmă",
							pj_nume_firma: formData["nume-firma"],
							pj_cui: formData.cui,
							pj_nr_reg: formData["nr-inregistrare"],
							pj_banca: formData.banca,
							pj_iban: formData.iban,
							pj_judet: formData.judet,
							pj_localitate: formData.localitate,
							pj_adresa: formData.adresa_firma,
							pj_adresa_livrare: formData.adresa_livrare,
							pj_numar_telefon: formData.phone,
							pj_email: formData.email,
						}
					: {
							billingType: 0,
							label: addressLabel || "Adresă personală",
							pf_prenume: formData["first-name"],
							pf_nume_familie: formData["last-name"],
							pf_tara: formData.country,
							pf_judet_oras: formData.city,
							pf_adresa: formData.address,
							pf_numar_telefon: formData.phone,
							pf_email: formData.email,
						};

				fetchWrapper.post("/api/users/addresses", addrPayload).catch(() => {});
			}

			const payload = {
				orderData: formData,
				cartProducts: cartItems,
				cartTotal: totalPrice,
				billingType: billingType ? 1 : 0,
				paymentMethod,
			};

			const orderResponse = await fetchWrapper.post("/api/netopia/order", payload);

			if (orderResponse.success === false) {
				toast.dismiss(loadingToast);
				toast.error("A apărut o eroare la crearea comenzii.");
				return;
			}

			const orderData = orderResponse;
			console.log("✅ Order created:", orderData.orderId);

			if (orderData.orderId) {
				localStorage.setItem("lastOrderId", orderData.orderId);

				if (paymentMethod === "ramburs") {
					toast.dismiss(loadingToast);
					toast.success("Comandă plasată! Vei plăti la livrare.");
	
					fetch("/api/netopia/process-order", {
						method: "POST",
						headers: { "Content-Type": "application/json" },
						body: JSON.stringify({ orderId: orderData.orderId }),
					}).catch(() => {});
					window.location.href = `/order-confirmation?orderId=${orderData.orderId}`;
					return;
				}

				const netopiaPayload = {
					...orderData.netopiaPayload,
					payment: {
						...orderData.netopiaPayload.payment,
						data: {
							BROWSER_USER_AGENT: navigator.userAgent,
							OS: navigator.platform,
							MOBILE: /Mobile|Android|iPhone/i.test(navigator.userAgent) ? "true" : "false",
							BROWSER_COLOR_DEPTH: screen.colorDepth?.toString() || "",
							BROWSER_SCREEN_HEIGHT: screen.height?.toString() || "",
							BROWSER_SCREEN_WIDTH: screen.width?.toString() || "",
							BROWSER_JAVA_ENABLED: navigator.javaEnabled?.()?.toString() || "false",
							BROWSER_LANGUAGE: navigator.language || "",
							BROWSER_TZ: Intl.DateTimeFormat().resolvedOptions().timeZone || "",
							BROWSER_TZ_OFFSET: new Date().getTimezoneOffset().toString(),
						},
					},
				};

				const netopiaResponse = await fetchWrapper.post("/api/netopia/start-payment", netopiaPayload);

				toast.dismiss();

				if (netopiaResponse.error.code !== "101") {
					const errorData = await netopiaResponse.json();
					console.error("Netopia API error:", errorData);
					toast.error("Eroare la inițializarea plății. Te rugăm să încerci din nou.");
					return;
				}

				const netopiaData = netopiaResponse;
				console.log("📥 Netopia response:", netopiaData);

				// Verificăm răspunsul de la Netopia
				if (netopiaData.error && netopiaData.error.code === "101") {
					if (netopiaData.payment?.ntpID) {
						const updatePayload = {
							orderId: orderData.orderId,
							ntpID: netopiaData.payment.ntpID,
							status: netopiaData.payment.status,
						};

						const updateOrder = await fetchWrapper.put("/api/netopia/order", updatePayload);

						if (updateOrder.success) {
							window.location.href = netopiaData.payment?.paymentURL;
						}
					}
					return;
				}
			}

			// Adăugăm datele browser-ului la payload Netopi

			toast.dismiss(loadingToast);
			toast.loading("Se inițializează plata...");
		} catch (err) {
			toast.dismiss();
			console.error("Checkout error:", err);
			toast.error("Eroare de rețea. Te rugăm să încerci din nou.");
		}
	};

	return (
		<section className='flat-spacing-11'>
			<style jsx>{`
				.price-wrapper {
					display: flex;
					align-items: center;
					gap: 6px;
					flex-wrap: wrap;
				}
				.price-original {
					text-decoration: line-through;
					color: #999;
					font-size: 13px;
				}
				.price-reduced {
					color: #ff4444;
					font-weight: 600;
					font-size: 15px;
				}
				.discount-badge-small {
					display: inline-block;
					background: linear-gradient(135deg, #ff4444 0%, #ff6b6b 100%);
					color: white;
					padding: 2px 6px;
					border-radius: 3px;
					font-size: 10px;
					font-weight: 600;
					text-transform: uppercase;
					letter-spacing: 0.3px;
				}
			`}</style>
			<div className='container'>
				<div className='tf-page-cart-wrap layout-2'>
					<div className='tf-page-cart-item'>
						<h5 className='fw-5 mb_20'>{t("checkout_details")}</h5>
						<select
							className='mb-4 p-2 border rounded'
							value={billingType}
							onChange={(e) => setBillingType(e.target.value === "true")}>
							<option value={false}>{t("checkout_pf")}</option>
							<option value={true}>{t("checkout_pj")}</option>
						</select>

						{savedAddresses.length > 0 && (
							<button
								type='button'
								onClick={() => openAddressSelector(savedAddresses, applyAddress)}
								style={{
									display: "flex",
									alignItems: "center",
									gap: 10,
									width: "100%",
									padding: "14px 18px",
									marginBottom: 20,
									background: "#f8f8f8",
									border: "2px solid #e5e5e5",
									borderRadius: 12,
									cursor: "pointer",
									transition: "all 0.2s",
									fontSize: 14,
									fontWeight: 600,
									color: "#000",
								}}>
								<MapPin size={18} />
								{selectedAddressId
									? `✓ Adresă selectată — schimbă`
									: t("checkout_address_use") + "(" + savedAddresses.length + ")"}
							</button>
						)}

						{!billingType ? (
							<div className='form-checkout'>
								<div className='box grid-2'>
									<fieldset className='fieldset'>
										<label htmlFor='first-name'>{t("checkout_prenume")}</label>
										<input
											required
											type='text'
											id='first-name'
											value={formData["first-name"] || ""}
											onChange={handleInputChange}
										/>
										{errors["first-name"] && (
											<small style={{ color: "red" }}>{errors["first-name"]}</small>
										)}
									</fieldset>
									<fieldset className='fieldset'>
										<label htmlFor='last-name'>{t("checkout_nume_de_familie")}</label>
										<input
											required
											type='text'
											id='last-name'
											value={formData["last-name"] || ""}
											onChange={handleInputChange}
										/>
										{errors["last-name"] && (
											<small style={{ color: "red" }}>{errors["last-name"]}</small>
										)}
									</fieldset>
								</div>
								<CountrySelect
									value={formData.country || "Romania"}
									onChange={(val) => setFormData((prev) => ({ ...prev, country: val }))}
								/>
								{errors["country"] && (
									<small style={{ color: "red" }}>{errors["country"]}</small>
								)}

								<fieldset className='box fieldset'>
									<label htmlFor='city'>{t("checkout_judet_oras")}</label>
									<div style={{ position: "relative" }}>
										<input
											required
											type='text'
											id='city'
											value={formData.city || ""}
											readOnly
											placeholder='Selectează județul și orașul'
											onClick={openLocationSelector}
											style={{
												cursor: "pointer",
												paddingRight: "40px",
												backgroundColor: "#fff",
											}}
										/>
										<button
											type='button'
											onClick={openLocationSelector}
											style={{
												position: "absolute",
												right: "10px",
												top: "50%",
												transform: "translateY(-50%)",
												background: "none",
												border: "none",
												cursor: "pointer",
												fontSize: "20px",
												padding: "5px",
											}}>
											📍
										</button>
									</div>
									{errors.city && <small style={{ color: "red" }}>{errors.city}</small>}
								</fieldset>

								<fieldset className='box fieldset'>
									<label htmlFor='address'>{t("checkout_address")}</label>
									<input
										required
										type='text'
										id='address'
										value={formData["address"] || ""}
										onChange={handleInputChange}
									/>
									{errors.address && (
										<small style={{ color: "red" }}>{errors.address}</small>
									)}
								</fieldset>
								<fieldset className='box fieldset'>
									<label htmlFor='phone'>{t("checkout_numar_telefon")}</label>
									<input
										required
										type='text'
										id='phone'
										value={formData["phone"] || ""}
										onChange={handleInputChange}
									/>
									{errors.phone && <small style={{ color: "red" }}>{errors.phone}</small>}
								</fieldset>
								<fieldset className='box fieldset'>
									<label htmlFor='email'>Email</label>
									<input
										required
										type='email'
										id='email'
										value={formData["email"] || ""}
										onChange={handleInputChange}
									/>
									{errors.email && <small style={{ color: "red" }}>{errors.email}</small>}
								</fieldset>
								<fieldset className='box fieldset'>
									<label htmlFor='note'>{t("checkout_alte_mentiuni")}</label>
									<textarea name='note' id='note' onChange={handleInputChange} />
								</fieldset>
							</div>
						) : (
							<div className='form-checkout'>
								<div className='box grid-2'>
									{[
										"nume-firma",
										"cui",
										"nr-inregistrare",
										"banca",
										"iban",
										"judet",
										"localitate",
										"adresa_firma",
										"adresa_livrare",
										"phone",
										"email",
									].map((field) => (
										<fieldset key={field} className='fieldset'>
											<label htmlFor={field}>{pjNames[field]}</label>
											<input
												required
												type={field === "email" ? "email" : "text"}
												id={field}
												onChange={handleInputChange}
											/>
											{errors[field] && (
												<small style={{ color: "red" }}>{errors[field]}</small>
											)}
										</fieldset>
									))}
								</div>
								<fieldset className='box fieldset'>
									<label htmlFor='note'>{t("checkout_alte_mentiuni")}</label>
									<textarea name='note' id='note' onChange={handleInputChange} />
								</fieldset>
							</div>
						)}
						<div
							style={{
								padding: "16px 18px",
								background: "#fafafa",
								border: "2px solid #e5e5e5",
								borderRadius: 12,
								marginTop: 8,
							}}>
							<label style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}>
								<input
									type='checkbox'
									checked={saveAddress}
									onChange={() => setSaveAddress((prev) => !prev)}
									style={{ width: 18, height: 18, accentColor: "#000", cursor: "pointer" }}
								/>
								<span style={{ fontSize: 14, fontWeight: 600, color: "#000" }}>
									{t("checkout_save_adress")}
								</span>
							</label>
							{saveAddress && (
								<input
									type='text'
									placeholder={t("checkout_save_adress_placeholder")}
									value={addressLabel}
									onChange={(e) => setAddressLabel(e.target.value)}
									style={{
										marginTop: 12,
										width: "100%",
										padding: "10px 14px",
										border: "1px solid #e5e5e5",
										borderRadius: 8,
										fontSize: 14,
										background: "#fff",
									}}
								/>
							)}
						</div>
					</div>

					<div className='tf-page-cart-footer'>
						<div className='tf-cart-footer-inner'>
							<h5 className='fw-5 mb_20'>{t("checkout_comanda_mea")}</h5>
							<div className='tf-page-cart-checkout widget-wrap-checkout'>
								<ul className='wrap-checkout-product'>
									{cartItems.map((elm, i) => (
										<li key={i} className='checkout-product-item'>
											<figure className='img-product'>
												<Image
													alt='product'
													src={elm.images?.split("|").filter(Boolean)[0]}
													width={720}
													height={1005}
												/>
											</figure>
											<div className='content'>
												<div className='info'>
													<p className='name'>
														{cartProducts.find((p) => p.id === elm.id)
															?.quantity || 1}{" "}
														x {getProductLanguage(elm)}
													</p>
													{isReduced(elm) && (
														<span className='discount-badge-small'>
															🔥 Reducere
														</span>
													)}
												</div>
												<CartItemPrice elm={elm} />
											</div>
										</li>
									))}
								</ul>

								{!cartProducts.length && (
									<div className='container'>
										<div className='row align-items-center mt-5 mb-5'>
											<div className='col-12 fs-18'>{t("shopping_cart_empty")}</div>
											<div className='col-12 mt-3'>
												<Link
													href={`/toate-produsele`}
													className='tf-btn btn-fill animate-hover-btn radius-3 w-100 justify-content-center'>
													{t("shopping_cart_vezi_produse")}
												</Link>
											</div>
										</div>
									</div>
								)}

								<div className='d-flex justify-content-between line pb_20'>
									<h6 className='fw-5'>{t("shopping_cart_transport")}</h6>
									<h6 className='total fw-5'>{convertPrice("22")} {getProductCoin()}</h6>
								</div>

								<div className='d-flex justify-content-between line pb_20'>
									<h6 className='fw-5'>Subtotal</h6>
									<h6 className='total fw-5'>
										{convertPrice(totalPrice.toFixed(2))} {getProductCoin()}
										<br />
										<small style={{ fontSize: 10 }}>{t("shopping_cart_included")}</small>
									</h6>
								</div>

								<div style={{ marginBottom: 16 }}>
									<h6 className='fw-5 mb_10'>{t("checkout_payment_method")}</h6>
									<div style={{ display: "flex", gap: 12 }}>
										<label
											style={{
												flex: 1,
												padding: "14px 16px",
												border: `2px solid ${paymentMethod === "card" ? "#000" : "#e5e5e5"}`,
												borderRadius: 12,
												cursor: "pointer",
												display: "flex",
												alignItems: "center",
												gap: 10,
												background:
													paymentMethod === "card" ? "#f5f5f5" : "#fafafa",
											}}>
											<input
												type='radio'
												name='payment'
												value='card'
												checked={paymentMethod === "card"}
												onChange={() => setPaymentMethod("card")}
												style={{ accentColor: "#000" }}
											/>
											<div>
												<div style={{ fontWeight: 600, fontSize: 14 }}>
													<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-credit-card-icon lucide-credit-card"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg> {t("checkout_payment_method_card")}
												</div>
											</div>
										</label>
										<label
											style={{
												flex: 1,
												padding: "14px 16px",
												border: `2px solid ${paymentMethod === "ramburs" ? "#000" : "#e5e5e5"}`,
												borderRadius: 12,
												cursor: "pointer",
												display: "flex",
												alignItems: "center",
												gap: 10,
												background:
													paymentMethod === "ramburs" ? "#f5f5f5" : "#fafafa",
											}}>
											<input
												type='radio'
												name='payment'
												value='ramburs'
												checked={paymentMethod === "ramburs"}
												onChange={() => setPaymentMethod("ramburs")}
												style={{ accentColor: "#000" }}
											/>
											<div>
												<div style={{ fontWeight: 600, fontSize: 14 }}>
													<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-van-icon lucide-van"><path d="M13 6v5a1 1 0 0 0 1 1h6.102a1 1 0 0 1 .712.298l.898.91a1 1 0 0 1 .288.702V17a1 1 0 0 1-1 1h-3"/><path d="M5 18H3a1 1 0 0 1-1-1V8a2 2 0 0 1 2-2h12c1.1 0 2.1.8 2.4 1.8l1.176 4.2"/><path d="M9 18h5"/><circle cx="16" cy="18" r="2"/><circle cx="7" cy="18" r="2"/></svg> {t("checkout_payment_method_cash")}
												</div>
											</div>
										</label>
									</div>
								</div>

								<button
									type='button'
									className='tf-btn radius-3 btn-fill btn-icon animate-hover-btn justify-content-center'
									onClick={handleCheckout}>
									{t("shopping_cart_button")}
								</button>

								<div className='mb_15 d-flex align-items-center'>
									<label className='checkbox-container text_black-2'>
										<input
											type='checkbox'
											onChange={() => setCompliancePrivacy(!compliancePrivacy)}
											checked={compliancePrivacy}
										/>
										<span className='checkmark' />
										{t("sunt_de_acord")}{" "}
										<a href='/politica-de-confidentialitate'>
											{t("politica_de_confidentialitate")}
										</a>
									</label>
								</div>
								<div className='mb_15 d-flex align-items-center'>
									<label className='checkbox-container text_black-2'>
										<input
											type='checkbox'
											onChange={() => setComplianceTerms(!complianceTerms)}
											checked={complianceTerms}
										/>
										<span className='checkmark' />
										{t("sunt_de_acord")}{" "}
										<a href='/termeni-si-conditii'>{t("termeni_si_conditii")}</a>
									</label>
								</div>

								<button
									type='button'
									onClick={() => (window.location.href = "/cos-de-cumparaturi")}
									className='tf-btn radius-3 btn-secondary btn-icon animate-hover-btn justify-content-center'>
									<ArrowBigLeft size={24} /> {t("checkout_vezi_cos")}
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
	);
}

async function openAddressSelector(addresses, onSelect) {
	const cardsHtml = addresses
		.map((addr) => {
			const isPJ = addr.billingType === 1;
			const name = isPJ ? addr.pj_nume_firma : `${addr.pf_prenume} ${addr.pf_nume_familie}`;
			const address = isPJ
				? `${addr.pj_adresa}, ${addr.pj_localitate}, ${addr.pj_judet}`
				: `${addr.pf_adresa}, ${addr.pf_judet_oras}`;
			const email = isPJ ? addr.pj_email : addr.pf_email;
			const phone = isPJ ? addr.pj_numar_telefon : addr.pf_numar_telefon;

			return `
        <div class="addr-card ${addr.isDefault ? "addr-card--default" : ""}"
             data-id="${addr.id}"
             data-addr='${JSON.stringify(addr).replace(/'/g, "&#39;")}'>
            <div class="addr-card-header">
                <div class="addr-card-icon">
                    ${
					isPJ
						? `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>`
						: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`
				}
                </div>
                <div>
                    <div class="addr-card-label">${addr.label || name}</div>
                    <div class="addr-card-type">${isPJ ? "Persoană juridică" : "Persoană fizică"}</div>
                </div>
                ${addr.isDefault ? '<span class="addr-card-badge">IMPLICIT</span>' : ""}
                <div class="addr-card-check">
                    <svg width="14" height="14" viewBox="0 0 20 20" fill="none">
                        <path d="M16.6667 5L7.50004 14.1667L3.33337 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
            </div>
            <div class="addr-card-body">
                <div class="addr-card-name">${name}</div>
                <div class="addr-card-detail">${address}</div>
                <div class="addr-card-detail">${email} · ${phone}</div>
                ${isPJ ? `<div class="addr-card-detail" style="color:#999;font-size:12px">CUI: ${addr.pj_cui}</div>` : ""}
            </div>
        </div>`;
		})
		.join("");

	const { value } = await Swal.fire({
		title: "",
		width: "780px",
		background: "#ffffff",
		showConfirmButton: false,
		showCancelButton: false,
		customClass: {
			popup: "addr-selector-popup",
			htmlContainer: "premium-html-container",
		},
		html: `
        <style>
            .addr-selector-popup { border-radius: 16px !important; padding: 0 !important; box-shadow: 0 20px 60px rgba(0,0,0,0.15) !important; }
            .addr-selector-container { padding: 40px; text-align: left; max-height: 80vh; overflow-y: auto; }
            .addr-selector-container::-webkit-scrollbar { width: 8px; }
            .addr-selector-container::-webkit-scrollbar-track { background: #f5f5f5; border-radius: 4px; }
            .addr-selector-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }
            .addr-selector-title { font-size: 26px; font-weight: 700; color: #000; margin: 0 0 6px 0; }
            .addr-selector-subtitle { font-size: 14px; color: #888; margin: 0 0 28px 0; }
            .addr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; margin-bottom: 20px; }
            .addr-card {
                background: #fafafa; border: 2px solid #e5e5e5; border-radius: 12px;
                padding: 18px; cursor: pointer; transition: all 0.2s ease; position: relative;
            }
            .addr-card:hover { border-color: #bbb; background: #f5f5f5; }
            .addr-card.selected { border-color: #000; background: #f0f0f0; }
            .addr-card--default { border-color: #cbd5e0; }
            .addr-card-header { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 12px; }
            .addr-card-icon {
                width: 36px; height: 36px; background: #f0f0f0; border-radius: 8px;
                display: flex; align-items: center; justify-content: center;
                color: #555; flex-shrink: 0;
            }
            .addr-card-label { font-size: 14px; font-weight: 700; color: #000; }
            .addr-card-type { font-size: 11px; color: #999; margin-top: 2px; }
            .addr-card-badge {
                margin-left: auto; background: #000; color: #fff;
                font-size: 10px; font-weight: 700; padding: 3px 9px;
                border-radius: 20px; letter-spacing: 0.05em; white-space: nowrap;
                flex-shrink: 0;
            }
            .addr-card-check {
                margin-left: auto; width: 22px; height: 22px;
                border: 2px solid #ddd; border-radius: 50%;
                display: flex; align-items: center; justify-content: center;
                color: #fff; background: transparent; transition: all 0.2s; flex-shrink: 0;
            }
            .addr-card.selected .addr-card-check { background: #000; border-color: #000; }
            .addr-card--default .addr-card-check { margin-left: 0; }
            .addr-card-name { font-size: 14px; font-weight: 600; color: #000; margin-bottom: 4px; }
            .addr-card-detail { font-size: 13px; color: #666; line-height: 1.5; }
            .addr-new-btn {
                display: flex; align-items: center; justify-content: center; gap: 10px;
                width: 100%; padding: 14px; border: 2px dashed #e5e5e5; border-radius: 12px;
                background: transparent; color: #999; font-size: 14px; font-weight: 600;
                cursor: pointer; transition: all 0.2s; margin-top: 8px;
            }
            .addr-new-btn:hover { border-color: #bbb; color: #555; }
            .addr-confirm-btn {
                width: 100%; margin-top: 20px; padding: 14px;
                background: #000; color: #fff; border: none; border-radius: 10px;
                font-size: 15px; font-weight: 600; cursor: pointer;
                transition: all 0.2s; display: none;
            }
            .addr-confirm-btn.visible { display: block; }
            .addr-confirm-btn:hover { background: #333; }
        </style>

        <div class="addr-selector-container">
            <h2 class="addr-selector-title">Adresele mele</h2>
            <p class="addr-selector-subtitle">Selectează o adresă de facturare și livrare</p>
            <div class="addr-grid">${cardsHtml}</div>
            <button class="addr-new-btn" id="btn-new-addr">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Adresă nouă
            </button>
            <button class="addr-confirm-btn" id="btn-confirm-addr">
                Folosește această adresă →
            </button>
        </div>
        `,
		didOpen: () => {
			let selectedAddr = null;

			// Auto-selectează implicit dacă există
			const defaultCard = document.querySelector(".addr-card--default");
			if (defaultCard) {
				defaultCard.classList.add("selected");
				selectedAddr = JSON.parse(defaultCard.dataset.addr);
				document.getElementById("btn-confirm-addr").classList.add("visible");
			}

			document.querySelectorAll(".addr-card").forEach((card) => {
				card.addEventListener("click", () => {
					document.querySelectorAll(".addr-card").forEach((c) => c.classList.remove("selected"));
					card.classList.add("selected");
					selectedAddr = JSON.parse(card.dataset.addr);
					document.getElementById("btn-confirm-addr").classList.add("visible");
				});
			});

			document.getElementById("btn-confirm-addr").addEventListener("click", () => {
				if (selectedAddr) {
					Swal.close();
					onSelect(selectedAddr);
				}
			});

			document.getElementById("btn-new-addr").addEventListener("click", () => {
				Swal.close();
				onSelect(null); // null = formular nou
			});
		},
	});
}
