Validate the phone number to be iraqi number (it can either starts with 0 or no) 11 digits...
Also choose address should automatically saves the address and then redirects to orders/page
'use client'
import React, { useState, useEffect } 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({});

    useEffect(() => {
        const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
        const storedOrder = JSON.parse(localStorage.getItem('orderData') || '{}');
        setAddresses(storedAddresses);
        setOrder(storedOrder);
    }, []);

    const handleAddressSelect = (address) => {
        const updatedOrder = { ...order, shippingAddress: address };
        setOrder(updatedOrder);
        localStorage.setItem('orderData', JSON.stringify(updatedOrder));
        router.push('/cart/order');
    };

    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" />
                <h1 className="text-2xl ssm:text-3xl absolute right-0 left-0 z-10 text-center font-medium font-sans">
                    Choose Address
                </h1>
            </header>

            {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)}
                >
                    <h2 className="text-xl font-semibold mb-2">
                        {address.type === 'home' ? 'Home' : 'Work'}
                    </h2>
                    <p>{address.governorate}, {address.city}</p>
                    <p>{address.address}</p>
                    <p>{address.phone_number}</p>
                </div>
            ))}

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

export default ChooseAddress;
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);

    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 (error) {
                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 (error) {
            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>
            </div>
        </>
    );
};

export default React.memo(CartCheckout);
AddAddress.jsx:
'use client'
import React, { useState, useEffect } 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 [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const router = useRouter();
    const searchParams = useSearchParams();

    useEffect(() => {
        const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
    }, []);

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

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        setError('');

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

        // Save to local storage
        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();
        return;

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

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'Failed to add address');
            }

            handleRedirect();
        } catch (err) {
            setError(err.message);
            const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
            const filteredAddresses = storedAddresses.filter(addr =>
                addr.full_name !== newAddress.full_name ||
                addr.phone_number !== newAddress.phone_number
            );
            localStorage.setItem('addresses', JSON.stringify(filteredAddresses));
        } finally {
            setIsLoading(false);
        }
    };

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

                <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="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="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"
                        placeholder="Phone Number"
                        name="phone_number"
                        value={formData.phone_number}
                        onChange={handleInputChange}
                        required
                    />
                    {error && <p className="text-red-500">{error}</p>}
                    <button
                        type="submit"
                        className="w-full p-3 bg-[#3B5345] text-white rounded-md disabled:bg-gray-400"
                        disabled={isLoading}
                    >
                        {isLoading ? 'Saving...' : 'Save'}
                    </button>
                </form>
            </div>
        </div>
    );
}
Also improve  stability especially for safari users... and improve performance...