if we add an address from cart checkout then when we save a new address it should automatically navigates again to cart checkout not choose address and automatically choose the address we just saved... Also if there are saved addresses use the latest used one... just set storage item "lastUsedAddress" each time we choose a new address...
Improve stability and performance...
Make it more smooth.
CartCheckout.jsx:
'use client';

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { CircleArrowLeft, FileText } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useNotification } from '@/components/NotificationContext';
import './NotificationStyles.css';

const CartCheckout = ({ subTotal, discount }) => {
    const [note, setNote] = useState('');
    const [orderData, setOrderData] = useState({
        shippingAddress: null,
        coupon_id: null,
        items: [],
    });
    const [userInfo, setUserInfo] = useState({ userId: null });
    const router = useRouter();
    const { addNotification } = useNotification();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState('');

    useEffect(() => {
        if (typeof window !== 'undefined') {
            try {
                const storedOrder = JSON.parse(localStorage.getItem('orderData') || 'null');
                const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || 'null');
                setOrderData(storedOrder || {
                    shippingAddress: null,
                    coupon_id: null,
                    items: [],
                });
                setUserInfo(storedUserInfo || { userId: null });
            } catch (err) {
                console.error('Failed to load order data:', err);
                addNotification('error', 'Failed to load order data.');
            }
            router.prefetch("/cart/order/confirm")
        }
    }, [addNotification, router]);

    const delivery = useMemo(() => {
        if (subTotal > 100000) {
            return 0; // Free delivery for orders over 100,000 IQD
        }
        if (orderData.shippingAddress?.governorate) {
            return orderData.shippingAddress.governorate.toLowerCase() === 'karbala' ? 0 : 5000;
        }
        return 5000; // Default delivery fee if governorate not specified
    }, [subTotal, orderData.shippingAddress]);

    const totalPrice = useMemo(() => subTotal + delivery - discount, [subTotal, delivery, discount]);

    const renderShippingAddress = useCallback(() => {
        if (orderData.shippingAddress) {
            const { governorate, city, address, phone_number } = orderData.shippingAddress;
            return (
                <>
                    <div className="border border-gray-200 rounded-lg p-4">
                        <p>{`${governorate}, ${city}`}</p>
                        <p>{address}</p>
                        <p>{phone_number}</p>
                    </div>
                    <Link
                        href="/cart/choose-address"
                        className="w-full border mt-2 border-[#37474F] rounded-lg p-3 flex items-center justify-center text-[#3B5345] bg-[rgba(59,83,69,0.05)]"
                        aria-label="Choose another address"
                    >
                        <span className="text-base font-semibold">Choose another address</span>
                    </Link>
                </>
            );
        } else {
            return (
                <Link
                    href="/cart/choose-address"
                    prefetch={false}
                    className="w-full border border-[#37474F] rounded-lg p-3 flex items-center justify-center text-[#3B5345] bg-[rgba(59,83,69,0.05)]"
                    aria-label="Choose address"
                >
                    <span className="text-base font-semibold">Choose address</span>
                </Link>
            );
        }
    }, [orderData.shippingAddress]);

    const handleSubmitOrder = useCallback(async () => {
        if (!orderData.shippingAddress) {
            addNotification('error', 'Please provide a shipping address.');
            return;
        }

        setIsSubmitting(true);

        const submitData = {
            user_id: userInfo.userId || null,
            notes: note,
            full_name: orderData.shippingAddress.full_name || '',
            governorate: orderData.shippingAddress.governorate || '',
            city: orderData.shippingAddress.city || '',
            address: orderData.shippingAddress.address || '',
            closest_point: orderData.shippingAddress.closest_point || '',
            phone_number: orderData.shippingAddress.phone_number || '',
            type: orderData.shippingAddress.type || '',
            coupon_id: orderData.coupon_id || null,
            items: orderData.items.map(item => ({
                product_id: item.product_id,
                size_id: item.size_id || null,
                color_id: item.color_id || null,
                quantity: item.quantity,
            })),
        };

        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API}/cart`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(submitData),
            });

            if (response.ok) {
                const data = await response.json();
                router.push(`/cart/order/confirm?id=${data.cart.id}`);
            } else {
                const errorData = await response.json();
                if (errorData.errors && errorData.errors.length > 0) {
                    addNotification('error', errorData.errors[0].msg || 'An error occurred while submitting the order.');
                } else {
                    addNotification('error', 'An error occurred while submitting the order.');
                }
            }
        } catch (err) {
            console.error('Order submission failed:', err);
            addNotification('error', 'A network error occurred. Please try again.');
        } finally {
            setIsSubmitting(false);
        }
    }, [note, orderData, userInfo, addNotification, router]);

    return (
        <>
            <header className="flex items-center mb-12">
                <button
                    onClick={() => router.back()}
                    className="p-2 relative z-20 cursor-pointer"
                    aria-label="Go back"
                >
                    <CircleArrowLeft size={52} strokeWidth={0.7} />
                </button>
                <h1 className="text-2xl ssm:text-3xl absolute right-0 left-0 z-10 text-center font-medium font-sans">
                    Checkout
                </h1>
            </header>
            <div className="font-serif overflow-x-hidden container mx-auto max-w-md">
                <section className="mb-6">
                    <h2 className="text-xl font-sans font-medium mb-2">Shipping Address</h2>
                    {renderShippingAddress()}
                </section>

                <section className="mb-6">
                    <h2 className="text-xl font-sans font-medium mb-2">Note</h2>
                    <p className="text-sm text-gray-600 mb-2">Write Any Additional Note</p>
                    <div className="relative">
                        <FileText className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                        <input
                            type="text"
                            value={note}
                            onChange={(e) => setNote(e.target.value)}
                            placeholder="I am not available on Sunday"
                            className="w-full border border-[rgba(105,92,92,0.3)] rounded-lg p-4 pl-12 text-sm"
                            aria-label="Additional note"
                        />
                    </div>
                </section>

                <section className="mb-6">
                    <h2 className="text-xl font-sans font-medium mb-2">Payment Method</h2>
                    <div className="flex items-center">
                        <div className="w-8 h-8 rounded-full border border-[#3B5345] flex items-center justify-center mr-3">
                            <div className="w-5 h-5 rounded-full bg-[#97C86C]"></div>
                        </div>
                        <span>Cash On Delivery</span>
                    </div>
                </section>

                <section className="-mx-8 mb-6 bg-[#F6F3F1]/30 rounded-lg p-8">
                    <h2 className="text-xl font-sans font-medium mb-4">Price Details</h2>
                    <div className="h-[1px] w-full mb-6 bg-[#695C5C]/30"></div>
                    <div className="space-y-3">
                        <div className="flex justify-between">
                            <span>Sub-total</span>
                            <span>{subTotal.toLocaleString()} IQD</span>
                        </div>
                        <div className="flex justify-between">
                            <span>Delivery</span>
                            <span>{delivery.toLocaleString()} IQD</span>
                        </div>
                        <div className="flex justify-between">
                            <span>Discount</span>
                            <span>{discount && discount > 0 ? "-" : ""}{discount?.toLocaleString()} IQD</span>
                        </div>
                        <div className="flex justify-between font-bold">
                            <span>Total Price</span>
                            <span>{totalPrice.toLocaleString()} IQD</span>
                        </div>
                    </div>
                </section>
                <button
                    onClick={handleSubmitOrder}
                    className="w-full inline-block bg-[#3B5345] text-white py-3 px-4 rounded-lg font-medium text-lg disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={isSubmitting}
                    aria-label="Submit Order"
                >
                    {isSubmitting ? 'Submitting...' : 'Submit Order'}
                </button>
                {error && <p className="text-red-500 text-center mt-4">{error}</p>}
            </div>
        </>
    );
};

export default React.memo(CartCheckout);

ChooseAddress:
'use client';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Link from "next/link";
import { CircleArrowLeft } from "lucide-react";

const ChooseAddress = () => {
    const router = useRouter();
    const [addresses, setAddresses] = useState([]);
    const [order, setOrder] = useState({});
    const [error, setError] = useState('');

    useEffect(() => {
        try {
            const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
            const storedOrder = JSON.parse(localStorage.getItem('orderData') || '{}');
            setAddresses(storedAddresses);
            setOrder(storedOrder);
        } catch (err) {
            console.error('Failed to load from localStorage:', err);
            setError('Failed to load addresses. Please try again.');
        }
    }, []);

    const handleAddressSelect = useCallback((address) => {
        try {
            const updatedOrder = { ...order, shippingAddress: address };
            setOrder(updatedOrder);
            localStorage.setItem('orderData', JSON.stringify(updatedOrder));
            router.push('/cart/order');
        } catch (err) {
            console.error('Failed to save order data:', err);
            setError('Failed to select address. Please try again.');
        }
    }, [order, router]);

    const renderedAddresses = useMemo(() => {
        if (addresses.length === 0) {
            return <p className="text-center text-gray-500">No addresses found. Please add a new address.</p>;
        }

        return addresses.map((address, index) => (
            <div
                key={index}
                className="mb-4 p-4 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50"
                onClick={() => handleAddressSelect(address)}
                role="button"
                tabIndex={0}
                onKeyPress={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        handleAddressSelect(address);
                    }
                }}
                aria-label={`Select ${address.type} address`}
            >
                <h2 className="text-xl font-semibold mb-2 capitalize">
                    {address.type === 'home' ? 'Home' : address.type === 'work' ? 'Work' : 'Other'}
                </h2>
                <p>{`${address.governorate}, ${address.city}`}</p>
                <p>{address.address}</p>
                <p>{address.phone_number}</p>
            </div>
        ));
    }, [addresses, handleAddressSelect]);

    return (
        <div className="container mx-auto max-w-md font-serif">
            <header className="flex items-center mb-12">
                <CircleArrowLeft
                    size={52}
                    strokeWidth={0.7}
                    onClick={() => router.back()}
                    className="p-2 relative z-20 cursor-pointer"
                    aria-label="Go back"
                />
                <h1 className="text-2xl ssm:text-3xl absolute right-0 left-0 z-10 text-center font-medium font-sans">
                    Choose Address
                </h1>
            </header>

            {error && <p className="text-red-500 text-center mb-4">{error}</p>}

            {renderedAddresses}

            <Link
                className="w-full bg-[#3B5345] text-white py-3 px-4 rounded-lg inline-block font-medium text-lg mt-4 text-center"
                href={{
                    pathname: "/profile/address/add",
                    query: { redirect: "/cart/choose-address" }
                }}
                aria-label="Add a new address"
            >
                Add a new address
            </Link>
        </div>
    );
};

export default React.memo(ChooseAddress);
AddAddress.jsx:
'use client';
import React, { useState, useCallback } from 'react';
import { HomeIcon, PlusCircleIcon, BriefcaseBusiness, CircleArrowLeft } from 'lucide-react';
import { useRouter, useSearchParams } from "next/navigation";
import { addAddress } from "@/lib/features/addressesSlice";
import { useAppDispatch } from "@/lib/hook";

export default function AddAddress() {
    const dispatch = useAppDispatch();
    const [addressType, setAddressType] = useState('');
    const [formData, setFormData] = useState({
        full_name: '',
        governorate: '',
        city: '',
        address: '',
        closest_point: '',
        phone_number: ''
    });
    const [errors, setErrors] = useState({});
    const [isLoading, setIsLoading] = useState(false);
    const router = useRouter();
    const searchParams = useSearchParams();

    // Validate phone number
    const validatePhoneNumber = (number) => {
        const regex = /^0?\d{10}$/;
        return regex.test(number);
    };

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

    const handleSubmit = useCallback(async (e) => {
        e.preventDefault();
        setIsLoading(true);
        setErrors({});

        // Validate phone number
        if (!validatePhoneNumber(formData.phone_number)) {
            setErrors(prev => ({
                ...prev,
                phone_number: 'Please enter a valid Iraqi phone number (11 digits, can start with 0).'
            }));
            setIsLoading(false);
            return;
        }

        if (!addressType) {
            setErrors(prev => ({
                ...prev,
                addressType: 'Please select an address type.'
            }));
            setIsLoading(false);
            return;
        }

        const newAddress = {...formData, type: addressType};

        try {
            // Save to local storage with error handling
            const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
            const updatedAddresses = [...storedAddresses, newAddress];
            localStorage.setItem('addresses', JSON.stringify(updatedAddresses));

            // Dispatch to Redux store
            dispatch(addAddress(newAddress));

            handleRedirect();
        } catch (error) {
            setErrors(prev => ({
                ...prev,
                general: 'Failed to save the address. Please try again.'
            }));
        } finally {
            setIsLoading(false);
        }
    }, [formData, addressType, dispatch]);

    const handleRedirect = () => {
        const redirectPath = searchParams.get('redirect');
        if (redirectPath) {
            router.push(redirectPath);
        } else {
            router.push('/profile/address');
        }
    };

    return (
        <div className="bg-white font-sans max-w-2xl mx-auto px-4">
            <header className="flex items-center justify-between mb-8">
                <CircleArrowLeft
                    size={52}
                    strokeWidth={0.7}
                    onClick={router.back}
                    className="p-2 cursor-pointer"
                    aria-label="Go back"
                />
                <h1 className="text-2xl font-bold">Add Address</h1>
                <div className="w-10"></div>
            </header>

            <div className="mb-6">
                <div className="font-medium flex space-x-2 mb-4">
                    {['home', 'work', 'other'].map((type) => (
                        <button
                            key={type}
                            className={`flex flex-1 items-center justify-center py-2 border rounded-md ${
                                addressType === type ? 'bg-[#3B5345] text-white' : 'bg-white text-black'
                            }`}
                            onClick={() => setAddressType(type)}
                            type="button"
                        >
                            {type === 'home' && <HomeIcon className="mr-2 h-4 w-4"/>}
                            {type === 'work' && <BriefcaseBusiness className="mr-2 h-4 w-4"/>}
                            {type === 'other' && <PlusCircleIcon className="mr-2 h-4 w-4"/>}
                            {type.charAt(0).toUpperCase() + type.slice(1)}
                        </button>
                    ))}
                </div>
                {errors.addressType && <p className="text-red-500 text-sm">{errors.addressType}</p>}

                <form onSubmit={handleSubmit} className="space-y-4">
                    <input
                        className="w-full p-3 border rounded-md"
                        placeholder="Full Name"
                        name="full_name"
                        value={formData.full_name}
                        onChange={handleInputChange}
                        required
                    />
                    <select
                        className="w-full p-3 border bg-white rounded-md appearance-none"
                        name="governorate"
                        value={formData.governorate}
                        onChange={handleInputChange}
                        required
                    >
                        <option value="" disabled hidden>Governorate</option>
                        <option value="al-anbar">Al-Anbar</option>
                        <option value="babil">Babil</option>
                        <option value="baghdad">Baghdad</option>
                        <option value="basra">Basra</option>
                        <option value="dhi_qar">Dhi Qar</option>
                        <option value="diyala">Diyala</option>
                        <option value="dohuk">Dohuk</option>
                        <option value="erbil">Erbil</option>
                        <option value="karbala">Karbala</option>
                        <option value="kirkuk">Kirkuk</option>
                        <option value="maysan">Maysan</option>
                        <option value="muthanna">Muthanna</option>
                        <option value="najaf">Najaf</option>
                        <option value="nineveh">Nineveh</option>
                        <option value="al-qadisiyyah">Al-Qadisiyyah</option>
                        <option value="saladin">Saladin</option>
                        <option value="sulaymaniyah">Sulaymaniyah</option>
                        <option value="wasit">Wasit</option>
                    </select>
                    <input
                        className="w-full p-3 border rounded-md"
                        placeholder="City"
                        name="city"
                        value={formData.city}
                        onChange={handleInputChange}
                        required
                    />
                    <input
                        className="w-full p-3 border rounded-md"
                        placeholder="Address"
                        name="address"
                        value={formData.address}
                        onChange={handleInputChange}
                        required
                    />
                    <input
                        className="w-full p-3 border rounded-md"
                        placeholder="The closest point of a function"
                        name="closest_point"
                        value={formData.closest_point}
                        onChange={handleInputChange}
                    />
                    <input
                        className={`w-full p-3 border rounded-md ${errors.phone_number ? 'border-red-500' : ''}`}
                        placeholder="Phone Number"
                        name="phone_number"
                        value={formData.phone_number}
                        onChange={handleInputChange}
                        required
                        maxLength={11}
                        pattern="^0?\d{10}$"
                        title="Please enter a valid Iraqi phone number (11 digits, can start with 0)."
                    />
                    {errors.phone_number && <p className="text-red-500 text-sm">{errors.phone_number}</p>}
                    {errors.general && <p className="text-red-500 text-sm">{errors.general}</p>}
                    <button
                        type="submit"
                        className="w-full p-3 bg-[#3B5345] text-white rounded-md disabled:bg-gray-400"
                        disabled={isLoading}
                        aria-label="Save Address"
                    >
                        {isLoading ? 'Saving...' : 'Save'}
                    </button>
                </form>
            </div>
        </div>)
}
CartCheckout.jsx:
'use client'
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import CartCheckout from "@/components/CartCheckout";
import { NotificationProvider } from "@/components/NotificationContext";
import Loading from "@/components/Loading";

export default function OrderNow() {
    const [orderData, setOrderData] = useState(null);
    const router = useRouter();

    useEffect(() => {
        const storedOrderData = localStorage.getItem('orderData');
        if (storedOrderData) {
            const parsedOrderData = JSON.parse(storedOrderData);
            setOrderData(parsedOrderData);
        } else {
            router.push('/cart');
        }
    }, [router]);

    if (!orderData) {
        return <Loading />;
    }

    const { subTotal, delivery, discount } = orderData.info;

    return (
        <NotificationProvider>
            <CartCheckout subTotal={subTotal} delivery={delivery} discount={discount} />
        </NotificationProvider>
    );
}