import React from "react";
import { Link, router } from "@inertiajs/react";
import {
    ArrowLeft,
    ArrowRight,
    CalendarDays,
    CheckCircle2,
    Clock3,
    MoreVertical,
    Phone,
    Plus,
    Search,
    ShoppingCart,
    History,
    UserRound,
    Users,
    X,
    AlertTriangle,
    Ban,
    MapPin,
    Camera,
    TrendingUp,
    Package,
    LocateFixed,
    Loader2,
    Minus,
    Pencil,
    Bell,
    FileText,
    Image,
} from "lucide-react";
import {
    Badge,
    Button,
    Card,
    Input,
    PageHeader,
    Select,
} from "../../components/ui";
import * as recharts from "recharts";

// Label Indonesia untuk status Order (nilai di DB tetap Draft/Submitted/
// Approved/Delivered/Cancelled), dipakai di badge "Status Order" pada modal
// Edit Visit supaya konsisten dengan halaman Order.
const orderStatusLabel: Record<string, string> = {
    Draft: "Draf",
    Submitted: "Diajukan",
    Approved: "Disetujui",
    Delivered: "Terkirim",
    Cancelled: "Dibatalkan",
};

const statusMeta: Record<
    string,
    {
        label: string;
        tone: string;
        dot: string;
        soft: string;
        text: string;
        border: string;
        icon: React.ElementType;
    }
> = {
    Scheduled: {
        label: "Terjadwal",
        tone: "blue",
        dot: "bg-blue-500",
        soft: "bg-blue-50",
        text: "text-blue-600",
        border: "border-blue-500",
        icon: Clock3,
    },
    "On Process": {
        label: "Diproses",
        tone: "orange",
        dot: "bg-orange-500",
        soft: "bg-orange-50",
        text: "text-orange-600",
        border: "border-orange-500",
        icon: Clock3,
    },
    Visited: {
        label: "Selesai",
        tone: "green",
        dot: "bg-emerald-500",
        soft: "bg-emerald-50",
        text: "text-emerald-600",
        border: "border-emerald-500",
        icon: CheckCircle2,
    },
    Order: {
        label: "Order",
        tone: "purple",
        dot: "bg-violet-500",
        soft: "bg-violet-50",
        text: "text-violet-600",
        border: "border-violet-500",
        icon: ShoppingCart,
    },
    "Not Order": {
        label: "Tidak Order",
        tone: "slate",
        dot: "bg-slate-400",
        soft: "bg-slate-100",
        text: "text-slate-500",
        border: "border-slate-300",
        icon: Ban,
    },
    "Failed Visit": {
        label: "Gagal Visit",
        tone: "red",
        dot: "bg-rose-500",
        soft: "bg-rose-50",
        text: "text-rose-600",
        border: "border-rose-500",
        icon: AlertTriangle,
    },
};

function money(value: number) {
    return new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        maximumFractionDigits: 0,
    }).format(value || 0);
}

function dateLabel(value: string) {
    return new Intl.DateTimeFormat("id-ID", {
        day: "2-digit",
        month: "short",
        year: "numeric",
    }).format(new Date(`${value}T12:00:00`));
}

function shiftDate(value: string, days: number) {
    const [year, month, day] = value.split("-").map(Number);
    const d = new Date(Date.UTC(year, month - 1, day));
    d.setUTCDate(d.getUTCDate() + days);
    return d.toISOString().slice(0, 10);
}

function photoUrl(path?: string | null) {
    if (!path) return null;
    if (/^https?:\/\//i.test(path)) return path;
    return `/storage/${path}`;
}

function mapsUrl(lat?: number | null, lng?: number | null) {
    if (!lat || !lng) return null;
    return `https://www.google.com/maps?q=${lat},${lng}`;
}

export default function PerSales({
    date,
    sales = [],
    stats,
    teams = [],
    team = "",
    customerQuery = "",
    salesQuery = "",
    products = [],
    customers = [],
}: any) {
    const [selected, setSelected] = React.useState<any>(null);
    const [search, setSearch] = React.useState(customerQuery);
    const [teamFilter, setTeamFilter] = React.useState(team || "");
    const [addVisitFor, setAddVisitFor] = React.useState<any>(null);
    const [addVisitForm, setAddVisitForm] = React.useState<any>({
        customer_id: "",
        customer_name: "",
        sales_name: "",
        visited_at: "",
        status: "Scheduled",
        notes: "",
        latitude: "",
        longitude: "",
    });
    const [addVisitBusy, setAddVisitBusy] = React.useState(false);
    const [addVisitLocating, setAddVisitLocating] = React.useState(false);
    const [addVisitErrors, setAddVisitErrors] = React.useState<any>({});
    const [productSearch, setProductSearch] = React.useState("");
    const [orderItems, setOrderItems] = React.useState<any[]>([]);
    const [customerDropdownOpen, setCustomerDropdownOpen] =
        React.useState(false);
    const searchTimer = React.useRef<ReturnType<typeof setTimeout> | null>(
        null,
    );

    React.useEffect(() => setSearch(customerQuery), [customerQuery]);
    React.useEffect(() => setTeamFilter(team || ""), [team]);

    // ==== Deteksi aktivitas baru (visit/order masuk) tanpa reload manual ====
    // Poll data 'sales' (+ 'stats') secara berkala. "Baru" dihitung di backend
    // berdasarkan tabel pivot visit_reads (per user + per visit), sehingga
    // tetap akurat walau browser di-F5 dan granular per card/item.
    const [markingVisitsRead, setMarkingVisitsRead] = React.useState(false);
    React.useEffect(() => {
        const interval = setInterval(() => {
            router.reload({
                only: ["sales", "stats"],
            });
        }, 15000);
        return () => clearInterval(interval);
    }, []);

    const totalNewActivity = React.useMemo(
        () =>
            sales.reduce(
                (sum: number, s: any) => sum + Number(s.new_count ?? 0),
                0,
            ),
        [sales],
    );

    const markAllVisitsRead = () => {
        if (markingVisitsRead) return;
        setMarkingVisitsRead(true);
        router.post(
            "/visits/activity/mark-read",
            {},
            {
                only: ["sales", "stats", "notifications"],
                preserveScroll: true,
                preserveState: true,
                onFinish: () => setMarkingVisitsRead(false),
            },
        );
    };

    // Buka detail satu visit; kalau visit itu masih "baru", tandai dibaca
    // secara granular (hanya visit ini) supaya badge di card lain tidak
    // ikut hilang.
    const openVisitDetail = (v: any) => {
        setSelected(v);
        if (v?.is_new && v?.id) {
            router.post(
                "/visits/activity/mark-read",
                { visit_id: v.id },
                {
                    only: ["sales", "notifications"],
                    preserveScroll: true,
                    preserveState: true,
                },
            );
        }
    };

    const openAddVisit = (s: any) => {
        setAddVisitFor(s);
        setAddVisitErrors({});
        setProductSearch("");
        setOrderItems([]);
        setCustomerDropdownOpen(false);
        setAddVisitForm({
            customer_id: "",
            customer_name: "",
            sales_name: s?.name || "",
            visited_at: `${date}T09:00`,
            status: "Scheduled",
            notes: "",
            latitude: "",
            longitude: "",
        });
    };

    const closeAddVisit = () => {
        if (addVisitBusy) return;
        setAddVisitFor(null);
    };

    const updateAddVisitForm = (field: string, value: string) => {
        setAddVisitForm((prev: any) => ({ ...prev, [field]: value }));
    };

    const addProductToOrder = (product: any) => {
        setOrderItems((prev: any[]) => {
            const existing = prev.find((it) => it.product_id === product.id);
            if (existing) {
                return prev.map((it) =>
                    it.product_id === product.id
                        ? { ...it, qty: it.qty + 1 }
                        : it,
                );
            }
            return [
                ...prev,
                {
                    product_id: product.id,
                    name: product.name,
                    price: Number(product.price || 0),
                    qty: 1,
                },
            ];
        });
    };

    const changeOrderItemQty = (productId: number, delta: number) => {
        setOrderItems(
            (prev: any[]) =>
                prev
                    .map((it) =>
                        it.product_id === productId
                            ? { ...it, qty: it.qty + delta }
                            : it,
                    )
                    .filter((it) => it.qty > 0) as any[],
        );
    };

    const removeOrderItem = (productId: number) => {
        setOrderItems((prev: any[]) =>
            prev.filter((it) => it.product_id !== productId),
        );
    };

    const orderItemsTotal = orderItems.reduce(
        (sum, it) => sum + it.price * it.qty,
        0,
    );

    const filteredProducts = React.useMemo(() => {
        const q = productSearch.trim().toLowerCase();
        if (!q) return products;
        return products.filter((p: any) =>
            `${p.name} ${p.code || ""}`.toLowerCase().includes(q),
        );
    }, [products, productSearch]);

    const filteredCustomers = React.useMemo(() => {
        const q = addVisitForm.customer_name.trim().toLowerCase();
        const list = !q
            ? customers
            : customers.filter((c: any) =>
                  `${c.name} ${c.code || ""} ${c.phone || ""}`
                      .toLowerCase()
                      .includes(q),
              );
        return list.slice(0, 20);
    }, [customers, addVisitForm.customer_name]);

    const selectCustomer = (customer: any) => {
        setAddVisitForm((prev: any) => ({
            ...prev,
            customer_id: customer.id,
            customer_name: customer.name,
            latitude:
                prev.latitude ||
                (customer.latitude ? String(customer.latitude) : prev.latitude),
            longitude:
                prev.longitude ||
                (customer.longitude
                    ? String(customer.longitude)
                    : prev.longitude),
        }));
        setCustomerDropdownOpen(false);
    };

    const locateAddVisit = () => {
        if (!navigator.geolocation) {
            alert("Browser tidak mendukung GPS.");
            return;
        }
        setAddVisitLocating(true);
        navigator.geolocation.getCurrentPosition(
            (pos) => {
                setAddVisitForm((prev: any) => ({
                    ...prev,
                    latitude: String(pos.coords.latitude),
                    longitude: String(pos.coords.longitude),
                }));
                setAddVisitLocating(false);
            },
            () => {
                alert(
                    "Lokasi GPS tidak dapat diakses. Aktifkan permission lokasi.",
                );
                setAddVisitLocating(false);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
        );
    };

    const submitAddVisit = () => {
        if (!addVisitForm.customer_name.trim()) {
            setAddVisitErrors({ customer_name: "Nama customer wajib diisi." });
            return;
        }
        if (!addVisitForm.latitude || !addVisitForm.longitude) {
            setAddVisitErrors({
                latitude:
                    "Lokasi wajib diisi. Gunakan tombol Ambil Lokasi GPS.",
            });
            return;
        }
        setAddVisitBusy(true);
        router.post(
            "/visits",
            {
                customer_id: addVisitForm.customer_id || null,
                customer_name: addVisitForm.customer_name.trim(),
                sales_name: addVisitForm.sales_name.trim(),
                scheduled_at: addVisitForm.visited_at || null,
                visited_at: addVisitForm.visited_at || null,
                status: addVisitForm.status,
                notes: addVisitForm.notes || null,
                latitude: addVisitForm.latitude,
                longitude: addVisitForm.longitude,
                items: orderItems.map((it) => ({
                    product_id: it.product_id,
                    qty: it.qty,
                })),
            },
            {
                preserveScroll: true,
                onSuccess: () => {
                    setAddVisitBusy(false);
                    setAddVisitFor(null);
                },
                onError: (errors) => {
                    setAddVisitBusy(false);
                    setAddVisitErrors(errors);
                },
            },
        );
    };

    // ==== Edit Visit (ubah data & status visit yang sudah ada) ====
    const [editVisit, setEditVisit] = React.useState<any>(null);
    const [editVisitForm, setEditVisitForm] = React.useState<any>({
        customer_id: "",
        customer_name: "",
        visited_at: "",
        status: "Scheduled",
        notes: "",
        latitude: "",
        longitude: "",
    });
    const [editVisitBusy, setEditVisitBusy] = React.useState(false);
    const [editVisitLocating, setEditVisitLocating] = React.useState(false);
    const [editVisitErrors, setEditVisitErrors] = React.useState<any>({});
    const [editCustomerDropdownOpen, setEditCustomerDropdownOpen] =
        React.useState(false);

    const openEditVisit = (v: any) => {
        setEditVisit(v);
        setEditVisitErrors({});
        setEditCustomerDropdownOpen(false);
        setEditVisitForm({
            customer_id: v.customer_id || "",
            customer_name: v.customer_name || "",
            visited_at: v.visited_at || "",
            status: v.status || "Scheduled",
            notes: (v.notes || "").replace(/GPS distance:.*$/i, "").trim(),
            latitude:
                v.latitude != null && v.latitude !== 0
                    ? String(v.latitude)
                    : v.latitude === 0
                      ? "0"
                      : "",
            longitude:
                v.longitude != null && v.longitude !== 0
                    ? String(v.longitude)
                    : v.longitude === 0
                      ? "0"
                      : "",
        });
    };

    const closeEditVisit = () => {
        if (editVisitBusy) return;
        setEditVisit(null);
    };

    const updateEditVisitForm = (field: string, value: string) => {
        setEditVisitForm((prev: any) => ({ ...prev, [field]: value }));
    };

    const filteredEditCustomers = React.useMemo(() => {
        const q = editVisitForm.customer_name.trim().toLowerCase();
        const list = !q
            ? customers
            : customers.filter((c: any) =>
                  `${c.name} ${c.code || ""} ${c.phone || ""}`
                      .toLowerCase()
                      .includes(q),
              );
        return list.slice(0, 20);
    }, [customers, editVisitForm.customer_name]);

    const selectEditCustomer = (customer: any) => {
        setEditVisitForm((prev: any) => ({
            ...prev,
            customer_id: customer.id,
            customer_name: customer.name,
            latitude:
                prev.latitude ||
                (customer.latitude ? String(customer.latitude) : prev.latitude),
            longitude:
                prev.longitude ||
                (customer.longitude
                    ? String(customer.longitude)
                    : prev.longitude),
        }));
        setEditCustomerDropdownOpen(false);
    };

    const locateEditVisit = () => {
        if (!navigator.geolocation) {
            alert("Browser tidak mendukung GPS.");
            return;
        }
        setEditVisitLocating(true);
        navigator.geolocation.getCurrentPosition(
            (pos) => {
                setEditVisitForm((prev: any) => ({
                    ...prev,
                    latitude: String(pos.coords.latitude),
                    longitude: String(pos.coords.longitude),
                }));
                setEditVisitLocating(false);
            },
            () => {
                alert(
                    "Lokasi GPS tidak dapat diakses. Aktifkan permission lokasi.",
                );
                setEditVisitLocating(false);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
        );
    };

    const submitEditVisit = () => {
        if (!editVisitForm.customer_name.trim()) {
            setEditVisitErrors({
                customer_name: "Nama customer wajib diisi.",
            });
            return;
        }
        setEditVisitBusy(true);
        router.put(
            `/visits/${editVisit.id}`,
            {
                customer_id: editVisitForm.customer_id || null,
                customer_name: editVisitForm.customer_name.trim(),
                visited_at: editVisitForm.visited_at || null,
                status: editVisitForm.status,
                notes: editVisitForm.notes || null,
                latitude: editVisitForm.latitude || null,
                longitude: editVisitForm.longitude || null,
            },
            {
                preserveScroll: true,
                onSuccess: () => {
                    setEditVisitBusy(false);
                    // Tutup modal Edit Visit saja, lalu kembali ke modal detail
                    // (selected) dengan data yang sudah diperbarui, bukan
                    // menutup semuanya.
                    setSelected((prev: any) =>
                        prev && prev.id === editVisit.id
                            ? {
                                  ...prev,
                                  customer_id:
                                      editVisitForm.customer_id || null,
                                  customer_name:
                                      editVisitForm.customer_name.trim(),
                                  visited_at: editVisitForm.visited_at || null,
                                  status: editVisitForm.status,
                                  notes: editVisitForm.notes || null,
                                  latitude: editVisitForm.latitude
                                      ? Number(editVisitForm.latitude)
                                      : null,
                                  longitude: editVisitForm.longitude
                                      ? Number(editVisitForm.longitude)
                                      : null,
                              }
                            : prev,
                    );
                    setEditVisit(null);
                },
                onError: (errors) => {
                    setEditVisitBusy(false);
                    setEditVisitErrors(errors);
                },
            },
        );
    };

    const navigate = React.useCallback((params: Record<string, any>) => {
        router.get("/visits/per-sales", params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    }, []);

    const moveDate = (days: number) => {
        navigate({
            date: shiftDate(date, days),
            team: teamFilter || undefined,
            customer: search || undefined,
            sales: salesQuery || undefined,
        });
    };

    const changeDate = (nextDate: string) => {
        if (!nextDate) return;
        navigate({
            date: nextDate,
            team: teamFilter || undefined,
            customer: search || undefined,
            sales: salesQuery || undefined,
        });
    };

    const changeTeam = (nextTeam: string) => {
        setTeamFilter(nextTeam);
        navigate({
            date,
            team: nextTeam || undefined,
            customer: search || undefined,
            sales: salesQuery || undefined,
        });
    };

    const changeSearch = (value: string) => {
        setSearch(value);
        if (searchTimer.current) clearTimeout(searchTimer.current);
        searchTimer.current = setTimeout(() => {
            navigate({
                date,
                team: teamFilter || undefined,
                customer: value.trim() || undefined,
                sales: salesQuery || undefined,
            });
        }, 350);
    };

    const clearSalesFilter = () => {
        navigate({
            date,
            team: teamFilter || undefined,
            customer: search || undefined,
            sales: undefined,
        });
    };

    return (
        <div className="p-7">
            <PageHeader
                title="Visit Per Sales"
                description="Monitoring aktivitas kunjungan sales per hari, target, status customer, GPS, dan order."
                action={
                    <div className="flex items-center gap-2">
                        {salesQuery && (
                            <button
                                type="button"
                                onClick={clearSalesFilter}
                                className="inline-flex h-10 items-center gap-2 rounded-xl border border-[#18b89a]/40 bg-[#e9fbf7] px-4 text-sm font-semibold text-[#0b7668] hover:bg-[#d9f5ee]"
                            >
                                <UserRound size={16} />
                                Sales: {salesQuery}
                                <X size={14} />
                            </button>
                        )}
                        {totalNewActivity > 0 && (
                            <button
                                type="button"
                                disabled={markingVisitsRead}
                                onClick={markAllVisitsRead}
                                className="inline-flex h-10 items-center gap-2 rounded-xl border border-rose-200 bg-rose-50 px-4 text-sm font-semibold text-rose-600 hover:bg-rose-100 disabled:opacity-50"
                            >
                                <Bell size={16} />
                                {totalNewActivity} aktivitas baru
                                <span className="text-rose-400">
                                    · Tandai dilihat
                                </span>
                            </button>
                        )}
                    </div>
                }
            />

            <div className="mb-5 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                {[
                    [
                        "Sales Aktif",
                        stats?.sales ?? 0,
                        "Sales yang memiliki aktivitas",
                    ],
                    [
                        "Total Visit",
                        stats?.visits ?? 0,
                        "Kunjungan pada tanggal terpilih",
                    ],
                    [
                        "Visit Selesai",
                        stats?.completed ?? 0,
                        "Visited / Order / Not Order",
                    ],
                    [
                        "Total Order",
                        stats?.orders ?? 0,
                        "Order pada tanggal terpilih",
                    ],
                    ["Omzet", money(stats?.omzet ?? 0), "Nilai order hari ini"],
                ].map(([label, value, hint]) => (
                    <Card key={label as string} className="p-4">
                        <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
                            {label}
                        </div>
                        <div className="mt-1 text-xl font-black text-slate-900">
                            {value}
                        </div>
                        <div className="mt-1 text-[10px] text-slate-400">
                            {hint}
                        </div>
                    </Card>
                ))}
            </div>

            <Card className="mb-5 p-3">
                <div className="flex flex-wrap items-center gap-3">
                    <button
                        type="button"
                        aria-label="Tanggal sebelumnya"
                        onClick={() => moveDate(-1)}
                        className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 hover:bg-slate-200"
                    >
                        <ArrowLeft size={17} />
                    </button>
                    <div className="flex min-w-46.25 items-center gap-2 rounded-xl border border-slate-200 bg-white px-3">
                        <CalendarDays size={17} className="text-[#18b89a]" />
                        <input
                            aria-label="Pilih tanggal"
                            type="date"
                            value={date}
                            onChange={(e) => changeDate(e.target.value)}
                            className="h-10 w-full bg-transparent text-sm font-bold outline-none"
                        />
                    </div>
                    <button
                        type="button"
                        aria-label="Tanggal berikutnya"
                        onClick={() => moveDate(1)}
                        className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 hover:bg-slate-200"
                    >
                        <ArrowRight size={17} />
                    </button>
                    <div className="hidden h-8 w-px bg-slate-200 md:block" />
                    <div className="rounded-xl bg-[#e9fbf7] px-4 py-2 text-sm font-bold text-[#0d8e78]">
                        {dateLabel(date)}
                    </div>
                    <div className="ml-auto flex w-full flex-col gap-2 sm:flex-row md:w-auto">
                        <Select
                            value={teamFilter}
                            onChange={(e) => changeTeam(e.target.value)}
                            className="sm:min-w-42.5"
                        >
                            <option value="">Semua Team</option>
                            {teams.map((t: any) => (
                                <option key={t.id} value={t.id}>
                                    {t.name}
                                </option>
                            ))}
                        </Select>
                        <div className="relative min-w-55 sm:min-w-70">
                            <Search
                                size={16}
                                className="absolute left-3 top-3 text-slate-400"
                            />
                            <Input
                                value={search}
                                onChange={(e) => changeSearch(e.target.value)}
                                placeholder="Cari customer..."
                                className="pl-9"
                            />
                        </div>
                    </div>
                </div>
            </Card>

            <div className="mb-3 flex items-center justify-between">
                <div>
                    <div className="text-sm font-bold text-slate-700">
                        Monitoring Sales
                    </div>
                    <div className="text-xs text-slate-400">
                        Sales diurutkan berdasarkan aktivitas: order, gagal
                        visit, dan status visit lainnya.
                    </div>
                </div>
                <div className="hidden items-center gap-1 text-xs text-slate-400 md:flex">
                    <Users size={14} /> {sales.length} sales aktif
                </div>
            </div>

            {sales.length === 0 ? (
                <Card className="p-16 text-center">
                    <div className="mx-auto grid h-12 w-12 place-items-center rounded-2xl bg-slate-100 text-slate-400">
                        <CalendarDays />
                    </div>
                    <div className="mt-4 font-bold">
                        Belum ada aktivitas sales
                    </div>
                    <div className="mt-1 text-sm text-slate-400">
                        Tidak ada visit atau order untuk filter yang dipilih.
                    </div>
                </Card>
            ) : (
                <div className="grid grid-cols-1 gap-5 pb-4 md:grid-cols-2 xl:grid-cols-3">
                    {sales.map((s: any) => {
                        const target = Number(s.target_visit ?? 0);
                        const actual = Number(s.completed_count ?? 0);
                        const visitCount = Number(s.count ?? 0);
                        const orderCount = Number(s.order_count ?? 0);

                        // Order Rate = persentase visit yang menghasilkan
                        // minimal satu order, bukan jumlah order / jumlah visit.
                        // Satu visit dapat menghasilkan lebih dari satu order.
                        const orderVisitCount = Array.isArray(s.visits)
                            ? s.visits.filter(
                                  (visit: any) =>
                                      Number(visit.order_count ?? 0) > 0 ||
                                      Boolean(visit.order),
                              ).length
                            : 0;
                        const orderRate =
                            visitCount > 0
                                ? Math.round(
                                      (orderVisitCount / visitCount) * 100,
                                  )
                                : 0;

                        const progress =
                            target > 0
                                ? Math.min(
                                      100,
                                      Math.round((actual / target) * 100),
                                  )
                                : 0;
                        return (
                            <Card
                                key={s.id ?? s.name}
                                className="group relative min-w-0 overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-[0_8px_30px_rgba(15,23,42,0.06)] transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_14px_38px_rgba(15,23,42,0.10)]"
                            >
                                {/* Header Sales */}
                                <div className="relative overflow-hidden bg-linear-to-br from-[#087f70] via-[#0b8b79] to-[#066b60] px-4 pb-4 pt-4 text-white">
                                    <div className="pointer-events-none absolute -right-10 -top-12 h-32 w-32 rounded-full bg-white/10" />
                                    <div className="pointer-events-none absolute -bottom-16 right-16 h-24 w-24 rounded-full bg-white/5" />
                                    <div className="relative flex items-start justify-between gap-3">
                                        <div className="flex min-w-0 items-center gap-3">
                                            <div className="relative grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-white/15 text-base font-black ring-1 ring-white/15">
                                                {(s.name || "S")
                                                    .split(" ")
                                                    .slice(0, 2)
                                                    .map(
                                                        (part: string) =>
                                                            part[0],
                                                    )
                                                    .join("")
                                                    .toUpperCase()}
                                            </div>
                                            <div className="min-w-0">
                                                <div className="truncate text-[15px] font-extrabold tracking-tight">
                                                    {s.name}
                                                </div>
                                                <div className="mt-0.5 flex items-center gap-1.5 truncate text-[10px] font-medium text-white/65">
                                                    <span className="h-1.5 w-1.5 rounded-full bg-emerald-300" />
                                                    {s.team_name ||
                                                        "Sales Representative"}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="flex shrink-0 items-center gap-1.5">
                                            {Number(s.new_count ?? 0) > 0 && (
                                                <span className="inline-flex h-7 items-center gap-1 rounded-full bg-rose-500 px-2.5 text-[10px] font-extrabold text-white shadow-sm">
                                                    <Bell size={11} />
                                                    {s.new_count}
                                                </span>
                                            )}
                                            <div className="rounded-xl border border-white/10 bg-white/10 px-2.5 py-1.5 text-center backdrop-blur-sm">
                                                <div className="text-[8px] font-bold uppercase tracking-wider text-white/55">
                                                    Visit
                                                </div>
                                                <div className="text-sm font-black leading-4">
                                                    {visitCount}
                                                </div>
                                            </div>
                                            <button
                                                type="button"
                                                aria-label="Menu sales"
                                                className="rounded-lg p-1.5 text-white/70 transition hover:bg-white/10 hover:text-white"
                                            >
                                                <MoreVertical size={17} />
                                            </button>
                                        </div>
                                    </div>

                                    {/* KPI */}
                                    <div className="relative mt-4 grid grid-cols-3 gap-2">
                                        {[
                                            ["Target", target, "Target visit"],
                                            [
                                                "Selesai",
                                                actual,
                                                "Visit selesai",
                                            ],
                                            [
                                                "Order",
                                                orderCount,
                                                "Order masuk",
                                            ],
                                        ].map(([label, value, hint]) => (
                                            <div
                                                key={label as string}
                                                className="rounded-xl border border-white/10 bg-white/10 px-2.5 py-2.5 backdrop-blur-sm"
                                            >
                                                <div className="text-[9px] font-medium text-white/60">
                                                    {hint}
                                                </div>
                                                <div className="mt-1 text-lg font-black leading-5">
                                                    {value}
                                                </div>
                                                <div className="mt-0.5 text-[8px] font-bold uppercase tracking-wider text-white/45">
                                                    {label}
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    <div className="relative mt-3">
                                        <div className="mb-1.5 flex items-center justify-between text-[10px] font-bold">
                                            <span className="text-white/65">
                                                Progress target visit
                                            </span>
                                            <span>{progress}%</span>
                                        </div>
                                        <div className="h-1.5 overflow-hidden rounded-full bg-black/15">
                                            <div
                                                className="h-full rounded-full bg-white shadow-[0_0_10px_rgba(255,255,255,0.35)] transition-all duration-500"
                                                style={{
                                                    width: `${progress}%`,
                                                }}
                                            />
                                        </div>
                                    </div>
                                </div>

                                {/* Omzet + conversion */}
                                <div className="grid grid-cols-[1fr_auto] items-center border-b border-slate-100 bg-white px-4 py-3">
                                    <div>
                                        <div className="flex items-center gap-1.5 text-[9px] font-bold uppercase tracking-wider text-slate-400">
                                            <TrendingUp
                                                size={12}
                                                className="text-[#0b8b79]"
                                            />{" "}
                                            Omzet
                                        </div>
                                        <div className="mt-0.5 text-[17px] font-black tracking-tight text-slate-900">
                                            {money(s.order_total)}
                                        </div>
                                    </div>
                                    <div className="rounded-xl bg-violet-50 px-3 py-2 text-right">
                                        <div className="text-[9px] font-bold uppercase tracking-wider text-violet-400">
                                            Order rate
                                        </div>
                                        <div className="mt-0.5 text-base font-black text-violet-600">
                                            {orderRate}%
                                        </div>
                                    </div>
                                </div>

                                {/* Status summary */}
                                <div className="grid grid-cols-4 gap-1.5 border-b border-slate-100 bg-slate-50/80 px-3 py-2.5">
                                    {[
                                        [
                                            "Order",
                                            orderCount,
                                            "bg-violet-50",
                                            "text-violet-600",
                                        ],
                                        [
                                            "Selesai",
                                            s.completed_count,
                                            "bg-emerald-50",
                                            "text-emerald-600",
                                        ],
                                        [
                                            "Gagal",
                                            s.failed_count,
                                            "bg-rose-50",
                                            "text-rose-600",
                                        ],
                                        [
                                            "No Order",
                                            s.not_order_count,
                                            "bg-slate-100",
                                            "text-slate-500",
                                        ],
                                    ].map(([label, value, bg, tone]) => (
                                        <div
                                            key={label as string}
                                            className={`rounded-lg ${bg} px-1.5 py-2 text-center`}
                                        >
                                            <div className="text-[8px] font-bold uppercase tracking-tight text-slate-400">
                                                {label}
                                            </div>
                                            <div
                                                className={`mt-0.5 text-sm font-black ${tone}`}
                                            >
                                                {value}
                                            </div>
                                        </div>
                                    ))}
                                </div>

                                {/* Activity list */}
                                <div className="bg-white">
                                    <div className="flex items-center justify-between px-4 pb-2 pt-3">
                                        <div className="text-[10px] font-extrabold uppercase tracking-wider text-slate-400">
                                            Aktivitas customer
                                        </div>
                                        <div className="text-[10px] font-semibold text-slate-400">
                                            {visitCount} kunjungan
                                        </div>
                                    </div>
                                    <div className="max-h-57.5 min-h-37.5 overflow-y-auto px-3 pb-2">
                                        {s.visits.length === 0 ? (
                                            <div className="grid min-h-32.5 place-items-center rounded-xl border border-dashed border-slate-200 bg-slate-50/60 text-center">
                                                <div>
                                                    <CalendarDays
                                                        size={20}
                                                        className="mx-auto text-slate-300"
                                                    />
                                                    <div className="mt-1 text-xs font-semibold text-slate-400">
                                                        Belum ada aktivitas
                                                    </div>
                                                </div>
                                            </div>
                                        ) : (
                                            s.visits.map((v: any) => {
                                                const meta =
                                                    statusMeta[v.status] ||
                                                    statusMeta.Visited;
                                                const Icon = meta.icon;
                                                return (
                                                    <button
                                                        key={v.id}
                                                        type="button"
                                                        onClick={() =>
                                                            openVisitDetail(v)
                                                        }
                                                        className="group flex w-full items-center gap-3 border-b border-slate-100 px-1 py-2.5 text-left last:border-0 hover:bg-slate-50"
                                                    >
                                                        <div
                                                            className={`grid h-9 w-9 shrink-0 place-items-center rounded-xl ${meta.soft} ${meta.text}`}
                                                        >
                                                            <Icon size={15} />
                                                        </div>
                                                        <div className="min-w-0 flex-1">
                                                            <div className="flex items-center gap-2">
                                                                <span className="text-[10px] font-bold text-slate-400">
                                                                    {v.time ||
                                                                        "--:--"}
                                                                </span>
                                                                {v.is_new && (
                                                                    <span className="rounded-full bg-rose-500 px-1.5 py-0.5 text-[8px] font-black text-white">
                                                                        Baru
                                                                    </span>
                                                                )}
                                                            </div>
                                                            <div className="truncate text-[12px] font-bold text-slate-800">
                                                                {
                                                                    v.customer_name
                                                                }
                                                            </div>
                                                            <div className="mt-0.5 flex items-center gap-1.5">
                                                                <span
                                                                    className={`text-[9px] font-bold ${meta.text}`}
                                                                >
                                                                    {meta.label}
                                                                </span>
                                                                {v.order && (
                                                                    <span className="truncate text-[9px] font-semibold text-slate-400">
                                                                        •{" "}
                                                                        {money(
                                                                            v
                                                                                .order
                                                                                .total,
                                                                        )}
                                                                    </span>
                                                                )}
                                                            </div>
                                                        </div>
                                                        <MoreVertical
                                                            size={14}
                                                            className="shrink-0 text-slate-300 group-hover:text-slate-500"
                                                        />
                                                    </button>
                                                );
                                            })
                                        )}
                                    </div>
                                </div>

                                {/* Footer */}
                                <div className="border-t border-slate-100 bg-slate-50/70 p-3">
                                    <Button
                                        className="w-full gap-2 rounded-xl shadow-sm"
                                        onClick={() => openAddVisit(s)}
                                    >
                                        <Plus size={16} /> Tambah Visit
                                    </Button>
                                </div>
                            </Card>
                        );
                    })}
                </div>
            )}

            {selected && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/55 p-4"
                    onMouseDown={(e) =>
                        e.target === e.currentTarget && setSelected(null)
                    }
                >
                    <div className="flex max-h-[92vh] w-full max-w-384 flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
                        <div className="flex items-start justify-between border-b px-5 py-4">
                            <div className="flex gap-4">
                                <div className="grid h-14 w-14 place-items-center rounded-2xl bg-[#e9fbf7] text-[#0b7668]">
                                    <UserRound />
                                </div>
                                <div>
                                    <div className="text-lg font-black text-slate-900">
                                        {selected.customer_name}
                                    </div>
                                    <div className="mt-1 flex flex-wrap items-center gap-2">
                                        <Badge
                                            tone={
                                                (
                                                    statusMeta[
                                                        selected.status
                                                    ] || statusMeta.Visited
                                                ).tone
                                            }
                                        >
                                            {
                                                (
                                                    statusMeta[
                                                        selected.status
                                                    ] || statusMeta.Visited
                                                ).label
                                            }
                                        </Badge>
                                        <span className="text-xs text-slate-400">
                                            {selected.time} • {dateLabel(date)}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <button
                                    onClick={() => openEditVisit(selected)}
                                    className="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 px-3 py-2 text-xs font-bold text-slate-600 hover:bg-slate-50"
                                >
                                    <Pencil size={14} />
                                    Edit
                                </button>
                                <button
                                    onClick={() => setSelected(null)}
                                    className="rounded-xl p-2 text-slate-400 hover:bg-slate-100"
                                >
                                    <X />
                                </button>
                            </div>
                        </div>
                        <div className="min-h-0 flex-1 overflow-y-auto">
                            <div className="grid lg:grid-cols-[.62fr_1.38fr]">
                                <div className="border-r border-slate-100 p-5">
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        <div className="rounded-xl bg-slate-50 p-3">
                                            <div className="text-[10px] font-bold uppercase text-slate-400">
                                                PIC / Sales
                                            </div>
                                            <div className="mt-1 text-sm font-bold">
                                                {sales.find((x: any) =>
                                                    x.visits.some(
                                                        (y: any) =>
                                                            y.id ===
                                                            selected.id,
                                                    ),
                                                )?.name || "-"}
                                            </div>
                                        </div>
                                        <div className="rounded-xl bg-slate-50 p-3">
                                            <div className="text-[10px] font-bold uppercase text-slate-400">
                                                Customer
                                            </div>
                                            <div className="mt-1 text-sm font-bold">
                                                {selected.customer?.code || "-"}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="mt-4 rounded-xl border border-slate-200 p-4">
                                        <div className="mb-3 flex items-center justify-between">
                                            <div className="font-bold">
                                                Informasi Customer
                                            </div>
                                            {selected.customer?.phone && (
                                                <a
                                                    href={`tel:${selected.customer.phone}`}
                                                    className="inline-flex items-center gap-1 text-xs font-bold text-[#0b7668]"
                                                >
                                                    <Phone size={14} />{" "}
                                                    {selected.customer.phone}
                                                </a>
                                            )}
                                        </div>
                                        <div className="text-sm font-semibold">
                                            {selected.customer?.name ||
                                                selected.customer_name}
                                        </div>
                                        <div className="mt-1 text-xs leading-5 text-slate-500">
                                            {selected.customer?.address ||
                                                "Alamat customer belum tersedia."}
                                        </div>
                                    </div>
                                    <div className="mt-4 rounded-xl bg-slate-50 p-4">
                                        <div className="flex items-center gap-2 text-xs font-bold">
                                            <Clock3 size={15} /> Keterangan /
                                            Next Action
                                        </div>
                                        <div className="mt-2 text-sm leading-6 text-slate-600">
                                            {selected.notes
                                                ?.replace(
                                                    /GPS distance:.*$/i,
                                                    "",
                                                )
                                                .trim() ||
                                                "Tidak ada catatan visit."}
                                        </div>
                                    </div>
                                </div>
                                <div className="p-5">
                                    <div className="flex items-center justify-between">
                                        <div>
                                            <div className="font-bold">
                                                Detail Order
                                            </div>
                                            <div className="text-[10px] text-slate-400">
                                                Produk dan kontribusi omzet
                                                order
                                                {Number(
                                                    selected.order_count ?? 0,
                                                ) > 1
                                                    ? ` • ${Number(selected.order_count)} order terkait`
                                                    : ""}
                                            </div>
                                        </div>
                                        {selected.order && (
                                            <div className="flex items-center gap-2">
                                                <Badge tone="orange">
                                                    {selected.order.order_no}
                                                </Badge>
                                                {Number(
                                                    selected.order_count ?? 0,
                                                ) > 1 && (
                                                    <Badge tone="purple">
                                                        {Number(
                                                            selected.order_count,
                                                        )}{" "}
                                                        Order
                                                    </Badge>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                    {selected.order && (
                                        <>
                                            <div className="mt-3 overflow-hidden rounded-xl border border-slate-200">
                                                <div className="grid grid-cols-[1fr_55px_100px] gap-2 bg-slate-50 px-3 py-2 text-[10px] font-bold uppercase text-slate-400">
                                                    <span>Produk</span>
                                                    <span>Qty</span>
                                                    <span className="text-right">
                                                        Subtotal
                                                    </span>
                                                </div>
                                                {selected.order.items.map(
                                                    (item: any, i: number) => (
                                                        <div
                                                            key={i}
                                                            className="grid grid-cols-[1fr_55px_100px] gap-2 border-t px-3 py-3 text-xs"
                                                        >
                                                            <span className="font-semibold">
                                                                {
                                                                    item.product_name
                                                                }
                                                                <span className="block text-[10px] font-normal text-slate-400">
                                                                    {money(
                                                                        item.price,
                                                                    )}{" "}
                                                                    / unit
                                                                </span>
                                                            </span>
                                                            <span>
                                                                {item.qty}
                                                            </span>
                                                            <span className="text-right font-bold">
                                                                {money(
                                                                    item.subtotal,
                                                                )}
                                                            </span>
                                                        </div>
                                                    ),
                                                )}
                                            </div>
                                            <div className="mt-3 flex items-center justify-between rounded-xl bg-[#e9fbf7] p-4">
                                                <div>
                                                    <span className="text-xs font-bold text-slate-500">
                                                        Total Omzet Order
                                                    </span>
                                                    <span className="mt-0.5 block text-[10px] text-slate-400">
                                                        {
                                                            selected.order.items
                                                                .length
                                                        }{" "}
                                                        produk
                                                    </span>
                                                </div>
                                                <span className="text-lg font-black text-[#0b7668]">
                                                    {money(
                                                        selected.order.total,
                                                    )}
                                                </span>
                                            </div>
                                        </>
                                    )}
                                </div>
                            </div>
                            <div className="px-5 pb-5">
                                <div className="mt-5 grid gap-4 lg:grid-cols-3">
                                    <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                                        <div className="mb-3 flex items-center justify-between gap-3">
                                            <div>
                                                <div className="flex items-center gap-1.5 text-xs font-black text-slate-900">
                                                    <TrendingUp
                                                        size={14}
                                                        className="text-[#0b7668]"
                                                    />
                                                    Chart Omzet 3 Bulan Terakhir
                                                </div>
                                                <div className="mt-0.5 text-[10px] text-slate-400">
                                                    Total omzet customer per
                                                    bulan (
                                                    {selected.monthly_omzet
                                                        ?.map(
                                                            (m: any) => m.label,
                                                        )
                                                        .join(" - ") || "-"}
                                                    )
                                                </div>
                                            </div>
                                            <span className="rounded-full bg-slate-100 px-2 py-1 text-[9px] font-bold text-slate-500">
                                                IDR
                                            </span>
                                        </div>
                                        {selected.monthly_omzet?.some(
                                            (m: any) => Number(m.omzet) > 0,
                                        ) ? (
                                            <div className="h-56">
                                                <recharts.ResponsiveContainer
                                                    width="100%"
                                                    height="100%"
                                                >
                                                    <recharts.BarChart
                                                        data={selected.monthly_omzet.map(
                                                            (m: any) => ({
                                                                name: m.label,
                                                                omzet: Number(
                                                                    m.omzet ||
                                                                        0,
                                                                ),
                                                            }),
                                                        )}
                                                        margin={{
                                                            top: 8,
                                                            right: 8,
                                                            left: 0,
                                                            bottom: 8,
                                                        }}
                                                    >
                                                        <recharts.CartesianGrid
                                                            strokeDasharray="3 3"
                                                            vertical={false}
                                                        />
                                                        <recharts.XAxis
                                                            dataKey="name"
                                                            tick={{
                                                                fontSize: 10,
                                                            }}
                                                            tickLine={false}
                                                        />
                                                        <recharts.YAxis
                                                            tick={{
                                                                fontSize: 9,
                                                            }}
                                                            tickLine={false}
                                                            axisLine={false}
                                                            tickFormatter={(
                                                                v,
                                                            ) =>
                                                                new Intl.NumberFormat(
                                                                    "id-ID",
                                                                    {
                                                                        notation:
                                                                            "compact",
                                                                        maximumFractionDigits: 1,
                                                                    },
                                                                ).format(v)
                                                            }
                                                        />
                                                        <recharts.Tooltip
                                                            cursor={{
                                                                fill: "rgba(15, 23, 42, 0.04)",
                                                            }}
                                                            formatter={(
                                                                value: any,
                                                            ) => [
                                                                money(
                                                                    Number(
                                                                        value,
                                                                    ),
                                                                ),
                                                                "Omzet",
                                                            ]}
                                                            labelStyle={{
                                                                fontWeight: 700,
                                                            }}
                                                        />
                                                        <recharts.Bar
                                                            dataKey="omzet"
                                                            radius={[
                                                                7, 7, 2, 2,
                                                            ]}
                                                        >
                                                            {selected.monthly_omzet.map(
                                                                (
                                                                    _: any,
                                                                    index: number,
                                                                ) => (
                                                                    <recharts.Cell
                                                                        key={`bar-${index}`}
                                                                        fill={
                                                                            [
                                                                                "#0b7668",
                                                                                "#18b89a",
                                                                                "#3b82f6",
                                                                            ][
                                                                                index %
                                                                                    3
                                                                            ]
                                                                        }
                                                                    />
                                                                ),
                                                            )}
                                                        </recharts.Bar>
                                                    </recharts.BarChart>
                                                </recharts.ResponsiveContainer>
                                            </div>
                                        ) : (
                                            <div className="flex h-56 items-center justify-center rounded-xl bg-slate-50 text-center">
                                                <div>
                                                    <ShoppingCart
                                                        className="mx-auto text-slate-300"
                                                        size={22}
                                                    />
                                                    <div className="mt-2 text-xs font-bold text-slate-500">
                                                        Belum ada data chart
                                                    </div>
                                                    <div className="mt-1 text-[10px] text-slate-400">
                                                        Belum ada order dalam 3
                                                        bulan terakhir.
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                                        <div className="mb-3 flex items-center justify-between gap-3">
                                            <div>
                                                <div className="flex items-center gap-1.5 text-xs font-black text-slate-900">
                                                    <Package
                                                        size={14}
                                                        className="text-[#0b7668]"
                                                    />
                                                    Produk Pernah Diorder
                                                </div>
                                                <div className="mt-0.5 text-[10px] text-slate-400">
                                                    Seluruh produk yang pernah
                                                    dibeli customer ini
                                                </div>
                                            </div>
                                            <Badge tone="slate">
                                                {selected.ordered_products
                                                    ?.length ?? 0}{" "}
                                                produk
                                            </Badge>
                                        </div>
                                        {selected.ordered_products?.length ? (
                                            <div className="max-h-56 space-y-2 overflow-y-auto pr-1">
                                                {selected.ordered_products.map(
                                                    (
                                                        product: any,
                                                        index: number,
                                                    ) => (
                                                        <div
                                                            key={index}
                                                            className="flex items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2.5"
                                                        >
                                                            <div className="min-w-0">
                                                                <div className="truncate text-xs font-bold text-slate-800">
                                                                    {
                                                                        product.product_name
                                                                    }
                                                                </div>
                                                                <div className="mt-0.5 text-[10px] text-slate-400">
                                                                    {
                                                                        product.qty
                                                                    }{" "}
                                                                    unit •{" "}
                                                                    {
                                                                        product.orders
                                                                    }{" "}
                                                                    order
                                                                </div>
                                                            </div>
                                                            <span className="shrink-0 text-xs font-bold text-[#0b7668]">
                                                                {money(
                                                                    product.omzet,
                                                                )}
                                                            </span>
                                                        </div>
                                                    ),
                                                )}
                                            </div>
                                        ) : (
                                            <div className="flex h-56 items-center justify-center rounded-xl bg-slate-50 text-center">
                                                <div>
                                                    <Package
                                                        className="mx-auto text-slate-300"
                                                        size={22}
                                                    />
                                                    <div className="mt-2 text-xs font-bold text-slate-500">
                                                        Belum ada produk
                                                    </div>
                                                    <div className="mt-1 text-[10px] text-slate-400">
                                                        Customer belum pernah
                                                        order produk apa pun.
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
                                        <div className="flex items-center justify-between gap-3">
                                            <div>
                                                <div className="flex items-center gap-2 text-xs font-black text-slate-900">
                                                    <History
                                                        size={16}
                                                        className="text-[#0b7668]"
                                                    />
                                                    Riwayat Order Customer
                                                </div>
                                                <div className="mt-0.5 text-[10px] text-slate-400">
                                                    Maksimal 10 transaksi
                                                    terakhir customer
                                                </div>
                                            </div>
                                            <Badge tone="slate">
                                                {selected.order_history
                                                    ?.length ?? 0}{" "}
                                                order
                                            </Badge>
                                        </div>
                                        {selected.order_history?.length ? (
                                            <div className="mt-3 overflow-hidden rounded-xl border border-slate-200">
                                                <div className="grid grid-cols-[1fr_78px_92px] gap-2 bg-slate-50 px-3 py-2 text-[9px] font-bold uppercase tracking-wide text-slate-400">
                                                    <span>Order</span>
                                                    <span>Tanggal</span>
                                                    <span className="text-right">
                                                        Total
                                                    </span>
                                                </div>
                                                <div className="max-h-56 overflow-y-auto">
                                                    {selected.order_history.map(
                                                        (history: any) => {
                                                            const isCurrent =
                                                                Number(
                                                                    history.id,
                                                                ) ===
                                                                Number(
                                                                    selected
                                                                        .order
                                                                        ?.id,
                                                                );
                                                            return (
                                                                <div
                                                                    key={
                                                                        history.id
                                                                    }
                                                                    className={`grid grid-cols-[1fr_78px_92px] gap-2 border-t px-3 py-2.5 text-[10px] ${isCurrent ? "bg-[#e9fbf7]" : "bg-white"}`}
                                                                >
                                                                    <div className="min-w-0">
                                                                        <div className="flex items-center gap-1.5">
                                                                            <span className="truncate font-bold text-slate-800">
                                                                                {
                                                                                    history.order_no
                                                                                }
                                                                            </span>
                                                                            {isCurrent && (
                                                                                <Badge tone="green">
                                                                                    Saat
                                                                                    ini
                                                                                </Badge>
                                                                            )}
                                                                        </div>
                                                                        <div className="mt-0.5 text-[9px] text-slate-400">
                                                                            {history.items_count ??
                                                                                0}{" "}
                                                                            produk
                                                                            •{" "}
                                                                            {
                                                                                history.status
                                                                            }
                                                                        </div>
                                                                    </div>
                                                                    <span className="text-slate-500">
                                                                        {dateLabel(
                                                                            history.order_date,
                                                                        )}
                                                                    </span>
                                                                    <span className="text-right font-bold text-slate-800">
                                                                        {money(
                                                                            Number(
                                                                                history.total ||
                                                                                    0,
                                                                            ),
                                                                        )}
                                                                    </span>
                                                                </div>
                                                            );
                                                        },
                                                    )}
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="mt-3 flex h-56 items-center justify-center rounded-xl bg-slate-50 text-center">
                                                <div>
                                                    <History
                                                        className="mx-auto text-slate-300"
                                                        size={22}
                                                    />
                                                    <div className="mt-2 text-xs font-bold text-slate-500">
                                                        Belum ada riwayat order
                                                    </div>
                                                    <div className="mt-1 text-[10px] text-slate-400">
                                                        Customer belum memiliki
                                                        transaksi.
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="flex flex-wrap items-center justify-end gap-2 border-t bg-slate-50 px-5 py-3">
                            {mapsUrl(selected.latitude, selected.longitude) && (
                                <Button
                                    variant="outline"
                                    className="gap-2"
                                    onClick={() =>
                                        window.open(
                                            mapsUrl(
                                                selected.latitude,
                                                selected.longitude,
                                            )!,
                                            "_blank",
                                            "noopener,noreferrer",
                                        )
                                    }
                                >
                                    <MapPin size={15} /> Lokasi Visit
                                </Button>
                            )}
                            {photoUrl(selected.photo_path) && (
                                <Button
                                    variant="outline"
                                    className="gap-2"
                                    onClick={() =>
                                        window.open(
                                            photoUrl(selected.photo_path)!,
                                            "_blank",
                                            "noopener,noreferrer",
                                        )
                                    }
                                >
                                    <Camera size={15} /> Lihat Foto
                                </Button>
                            )}
                            {/* TODO: belum ada fungsinya, tunggu route/isi PDF ditentukan */}
                            <Button variant="outline" className="gap-2">
                                <FileText size={15} /> Lihat PDF
                            </Button>
                            {/* TODO: belum ada fungsinya */}
                            <Button variant="outline" className="gap-2">
                                <Image size={15} /> Lihat Gambar
                            </Button>
                            <Button
                                variant="outline"
                                onClick={() => setSelected(null)}
                            >
                                Tutup
                            </Button>
                        </div>
                    </div>
                </div>
            )}

            {addVisitFor && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/55 p-4"
                    onMouseDown={(e) =>
                        e.target === e.currentTarget && closeAddVisit()
                    }
                >
                    <div className="flex max-h-[92vh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
                        <div className="flex items-start justify-between border-b px-5 py-4">
                            <div>
                                <div className="text-lg font-black text-slate-900">
                                    Tambah Visit
                                </div>
                                <div className="mt-0.5 text-xs text-slate-400">
                                    Sales: {addVisitFor.name}
                                </div>
                            </div>
                            <button
                                onClick={closeAddVisit}
                                className="rounded-xl p-2 text-slate-400 hover:bg-slate-100"
                            >
                                <X />
                            </button>
                        </div>
                        <div className="min-h-0 flex-1 overflow-y-auto p-5">
                            <div className="grid gap-5 md:grid-cols-2">
                                {/* Kolom kiri: data visit & customer */}
                                <div className="space-y-4">
                                    <div className="relative">
                                        <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                            Customer
                                        </label>
                                        <div className="relative">
                                            <Search
                                                size={14}
                                                className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
                                            />
                                            <Input
                                                value={
                                                    addVisitForm.customer_name
                                                }
                                                onChange={(e: any) => {
                                                    updateAddVisitForm(
                                                        "customer_id",
                                                        "",
                                                    );
                                                    updateAddVisitForm(
                                                        "customer_name",
                                                        e.target.value,
                                                    );
                                                    setCustomerDropdownOpen(
                                                        true,
                                                    );
                                                }}
                                                onFocus={() =>
                                                    setCustomerDropdownOpen(
                                                        true,
                                                    )
                                                }
                                                onBlur={() =>
                                                    setTimeout(
                                                        () =>
                                                            setCustomerDropdownOpen(
                                                                false,
                                                            ),
                                                        150,
                                                    )
                                                }
                                                placeholder="Cari atau ketik nama customer..."
                                                className="pl-9"
                                                autoComplete="off"
                                            />
                                        </div>
                                        {customerDropdownOpen && (
                                            <div className="absolute z-10 mt-1 max-h-48 w-full overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-lg">
                                                {filteredCustomers.length ? (
                                                    filteredCustomers.map(
                                                        (c: any) => (
                                                            <button
                                                                type="button"
                                                                key={c.id}
                                                                onMouseDown={(
                                                                    e,
                                                                ) =>
                                                                    e.preventDefault()
                                                                }
                                                                onClick={() =>
                                                                    selectCustomer(
                                                                        c,
                                                                    )
                                                                }
                                                                className="flex w-full flex-col border-b border-slate-100 px-3 py-2 text-left text-xs last:border-b-0 hover:bg-slate-50"
                                                            >
                                                                <span className="font-semibold text-slate-700">
                                                                    {c.name}
                                                                </span>
                                                                <span className="text-[10px] text-slate-400">
                                                                    {[
                                                                        c.code,
                                                                        c.phone,
                                                                    ]
                                                                        .filter(
                                                                            Boolean,
                                                                        )
                                                                        .join(
                                                                            " · ",
                                                                        )}
                                                                </span>
                                                            </button>
                                                        ),
                                                    )
                                                ) : (
                                                    <div className="px-3 py-3 text-center text-xs text-slate-400">
                                                        Customer tidak
                                                        ditemukan. Nama akan
                                                        disimpan sebagai
                                                        customer baru.
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                        {addVisitErrors.customer_name && (
                                            <div className="mt-1 text-[11px] font-semibold text-rose-500">
                                                {addVisitErrors.customer_name}
                                            </div>
                                        )}
                                    </div>
                                    <div className="grid grid-cols-2 gap-3">
                                        <div>
                                            <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                                Jadwal Kunjungan
                                            </label>
                                            <Input
                                                type="datetime-local"
                                                value={addVisitForm.visited_at}
                                                onChange={(e: any) =>
                                                    updateAddVisitForm(
                                                        "visited_at",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        <div>
                                            <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                                Status
                                            </label>
                                            <Select
                                                value={
                                                    orderItems.length
                                                        ? "Order"
                                                        : addVisitForm.status
                                                }
                                                disabled={orderItems.length > 0}
                                                onChange={(e: any) =>
                                                    updateAddVisitForm(
                                                        "status",
                                                        e.target.value,
                                                    )
                                                }
                                            >
                                                {Object.keys(statusMeta).map(
                                                    (key) => (
                                                        <option
                                                            key={key}
                                                            value={key}
                                                        >
                                                            {
                                                                statusMeta[key]
                                                                    .label
                                                            }
                                                        </option>
                                                    ),
                                                )}
                                            </Select>
                                            {orderItems.length > 0 && (
                                                <div className="mt-1 text-[10px] text-slate-400">
                                                    Otomatis "Order" karena ada
                                                    produk dipilih.
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                    <div>
                                        <div className="mb-1.5 flex items-center justify-between">
                                            <label className="text-xs font-bold text-slate-600">
                                                Lokasi GPS
                                            </label>
                                            <button
                                                type="button"
                                                onClick={locateAddVisit}
                                                disabled={addVisitLocating}
                                                className="inline-flex items-center gap-1.5 text-xs font-bold text-[#0b7668] disabled:opacity-50"
                                            >
                                                {addVisitLocating ? (
                                                    <Loader2
                                                        size={13}
                                                        className="animate-spin"
                                                    />
                                                ) : (
                                                    <LocateFixed size={13} />
                                                )}
                                                Ambil Lokasi Saat Ini
                                            </button>
                                        </div>
                                        <div className="grid grid-cols-2 gap-3">
                                            <Input
                                                type="number"
                                                placeholder="Latitude"
                                                value={addVisitForm.latitude}
                                                onChange={(e: any) =>
                                                    updateAddVisitForm(
                                                        "latitude",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                            <Input
                                                type="number"
                                                placeholder="Longitude"
                                                value={addVisitForm.longitude}
                                                onChange={(e: any) =>
                                                    updateAddVisitForm(
                                                        "longitude",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {addVisitErrors.latitude && (
                                            <div className="mt-1 text-[11px] font-semibold text-rose-500">
                                                {addVisitErrors.latitude}
                                            </div>
                                        )}
                                    </div>
                                    <div>
                                        <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                            Catatan / Next Action
                                        </label>
                                        <textarea
                                            value={addVisitForm.notes}
                                            onChange={(e) =>
                                                updateAddVisitForm(
                                                    "notes",
                                                    e.target.value,
                                                )
                                            }
                                            rows={3}
                                            placeholder="Opsional"
                                            className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none transition placeholder:text-slate-400 focus:border-[#18b89a] focus:ring-2 focus:ring-[#18b89a]/10"
                                        />
                                    </div>
                                </div>

                                {/* Kolom kanan: produk order */}
                                <div>
                                    <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                        Produk Order (opsional)
                                    </label>
                                    <div className="relative">
                                        <Search
                                            size={14}
                                            className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
                                        />
                                        <Input
                                            value={productSearch}
                                            onChange={(e: any) =>
                                                setProductSearch(e.target.value)
                                            }
                                            placeholder="Cari produk..."
                                            className="pl-9"
                                        />
                                    </div>
                                    <div className="mt-2 max-h-36 overflow-y-auto rounded-xl border border-slate-200">
                                        {filteredProducts.length ? (
                                            filteredProducts.map((p: any) => (
                                                <button
                                                    type="button"
                                                    key={p.id}
                                                    onClick={() =>
                                                        addProductToOrder(p)
                                                    }
                                                    className="flex w-full items-center justify-between gap-2 border-b border-slate-100 px-3 py-2 text-left text-xs last:border-b-0 hover:bg-slate-50"
                                                >
                                                    <div className="min-w-0">
                                                        <div className="truncate font-semibold text-slate-700">
                                                            {p.name}
                                                        </div>
                                                        <div className="text-[10px] text-slate-400">
                                                            {money(
                                                                Number(
                                                                    p.price ||
                                                                        0,
                                                                ),
                                                            )}
                                                        </div>
                                                    </div>
                                                    <Plus
                                                        size={14}
                                                        className="shrink-0 text-[#0b7668]"
                                                    />
                                                </button>
                                            ))
                                        ) : (
                                            <div className="px-3 py-4 text-center text-xs text-slate-400">
                                                Produk tidak ditemukan.
                                            </div>
                                        )}
                                    </div>

                                    {orderItems.length > 0 && (
                                        <div className="mt-3 space-y-2 rounded-xl bg-slate-50 p-3">
                                            {orderItems.map((it) => (
                                                <div
                                                    key={it.product_id}
                                                    className="flex items-center gap-2"
                                                >
                                                    <div className="min-w-0 flex-1">
                                                        <div className="truncate text-xs font-bold text-slate-800">
                                                            {it.name}
                                                        </div>
                                                        <div className="text-[10px] text-slate-400">
                                                            {money(it.price)} /
                                                            unit
                                                        </div>
                                                    </div>
                                                    <div className="flex shrink-0 items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-1.5 py-1">
                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                changeOrderItemQty(
                                                                    it.product_id,
                                                                    -1,
                                                                )
                                                            }
                                                            className="grid h-6 w-6 place-items-center rounded-md text-slate-500 hover:bg-slate-100"
                                                        >
                                                            <Minus size={13} />
                                                        </button>
                                                        <span className="w-6 text-center text-xs font-bold text-slate-800">
                                                            {it.qty}
                                                        </span>
                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                changeOrderItemQty(
                                                                    it.product_id,
                                                                    1,
                                                                )
                                                            }
                                                            className="grid h-6 w-6 place-items-center rounded-md text-slate-500 hover:bg-slate-100"
                                                        >
                                                            <Plus size={13} />
                                                        </button>
                                                    </div>
                                                    <span className="w-20 shrink-0 text-right text-xs font-bold text-slate-800">
                                                        {money(
                                                            it.price * it.qty,
                                                        )}
                                                    </span>
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            removeOrderItem(
                                                                it.product_id,
                                                            )
                                                        }
                                                        className="shrink-0 text-slate-300 hover:text-rose-500"
                                                    >
                                                        <X size={14} />
                                                    </button>
                                                </div>
                                            ))}
                                            <div className="flex items-center justify-between border-t border-slate-200 pt-2">
                                                <span className="text-xs font-bold text-slate-500">
                                                    Total Order
                                                </span>
                                                <span className="text-sm font-black text-[#0b7668]">
                                                    {money(orderItemsTotal)}
                                                </span>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                        <div className="flex justify-end gap-2 border-t bg-slate-50 px-5 py-3">
                            <Button
                                variant="outline"
                                onClick={closeAddVisit}
                                disabled={addVisitBusy}
                            >
                                Batal
                            </Button>
                            <Button
                                className="gap-2"
                                onClick={submitAddVisit}
                                disabled={addVisitBusy}
                            >
                                {addVisitBusy ? (
                                    <Loader2
                                        size={15}
                                        className="animate-spin"
                                    />
                                ) : (
                                    <Plus size={15} />
                                )}
                                Simpan Visit
                            </Button>
                        </div>
                    </div>
                </div>
            )}
            {editVisit && (
                <div
                    className="fixed inset-0 z-60 flex items-center justify-center bg-slate-950/55 p-4"
                    onMouseDown={(e) =>
                        e.target === e.currentTarget && closeEditVisit()
                    }
                >
                    <div className="flex max-h-[92vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
                        <div className="flex items-center justify-between border-b p-5">
                            <div>
                                <h2 className="font-black">Edit Visit</h2>
                                <p className="text-xs text-slate-400">
                                    Perbarui data kunjungan &amp; status, lalu
                                    simpan.
                                </p>
                            </div>
                            <button
                                onClick={closeEditVisit}
                                disabled={editVisitBusy}
                                className="rounded-xl p-2 text-slate-400 hover:bg-slate-100 disabled:opacity-50"
                            >
                                <X />
                            </button>
                        </div>
                        <div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-5">
                            <div className="relative">
                                <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                    Customer
                                </label>
                                <div className="relative">
                                    <Search
                                        size={14}
                                        className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
                                    />
                                    <Input
                                        value={editVisitForm.customer_name}
                                        onChange={(e: any) => {
                                            updateEditVisitForm(
                                                "customer_id",
                                                "",
                                            );
                                            updateEditVisitForm(
                                                "customer_name",
                                                e.target.value,
                                            );
                                            setEditCustomerDropdownOpen(true);
                                        }}
                                        onFocus={() =>
                                            setEditCustomerDropdownOpen(true)
                                        }
                                        onBlur={() =>
                                            setTimeout(
                                                () =>
                                                    setEditCustomerDropdownOpen(
                                                        false,
                                                    ),
                                                150,
                                            )
                                        }
                                        placeholder="Cari atau ketik nama customer..."
                                        className="pl-9"
                                        autoComplete="off"
                                    />
                                </div>
                                {editCustomerDropdownOpen && (
                                    <div className="absolute z-10 mt-1 max-h-48 w-full overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-lg">
                                        {filteredEditCustomers.length ? (
                                            filteredEditCustomers.map(
                                                (c: any) => (
                                                    <button
                                                        type="button"
                                                        key={c.id}
                                                        onMouseDown={(e) =>
                                                            e.preventDefault()
                                                        }
                                                        onClick={() =>
                                                            selectEditCustomer(
                                                                c,
                                                            )
                                                        }
                                                        className="flex w-full flex-col border-b border-slate-100 px-3 py-2 text-left text-xs last:border-b-0 hover:bg-slate-50"
                                                    >
                                                        <span className="font-semibold text-slate-700">
                                                            {c.name}
                                                        </span>
                                                        <span className="text-[10px] text-slate-400">
                                                            {[c.code, c.phone]
                                                                .filter(Boolean)
                                                                .join(" · ")}
                                                        </span>
                                                    </button>
                                                ),
                                            )
                                        ) : (
                                            <div className="px-3 py-3 text-center text-xs text-slate-400">
                                                Customer tidak ditemukan.
                                            </div>
                                        )}
                                    </div>
                                )}
                                {editVisitErrors.customer_name && (
                                    <div className="mt-1 text-[11px] font-semibold text-rose-500">
                                        {editVisitErrors.customer_name}
                                    </div>
                                )}
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                        Jadwal Kunjungan
                                    </label>
                                    <Input
                                        type="datetime-local"
                                        value={editVisitForm.visited_at}
                                        onChange={(e: any) =>
                                            updateEditVisitForm(
                                                "visited_at",
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>
                                <div>
                                    <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                        Status Kunjungan
                                    </label>
                                    <Select
                                        value={editVisitForm.status}
                                        onChange={(e: any) =>
                                            updateEditVisitForm(
                                                "status",
                                                e.target.value,
                                            )
                                        }
                                    >
                                        {Object.keys(statusMeta).map((key) => (
                                            <option key={key} value={key}>
                                                {statusMeta[key].label}
                                            </option>
                                        ))}
                                    </Select>
                                    {editVisitErrors.status && (
                                        <div className="mt-1 text-[11px] font-semibold text-rose-500">
                                            {editVisitErrors.status}
                                        </div>
                                    )}
                                    <div className="mt-1 text-[10px] text-slate-400">
                                        Status hasil kunjungan sales, bukan
                                        status order.
                                    </div>
                                </div>
                            </div>
                            {editVisit?.order && (
                                <div className="flex items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
                                    <div>
                                        <div className="text-[10px] font-bold uppercase tracking-wider text-slate-400">
                                            Order Terkait
                                        </div>
                                        <div className="text-xs font-semibold text-slate-700">
                                            {editVisit.order.order_no}
                                        </div>
                                    </div>
                                    <span className="rounded-full bg-white px-2.5 py-1 text-[10px] font-bold text-slate-600 shadow-sm">
                                        Status Order:{" "}
                                        {orderStatusLabel[
                                            editVisit.order.status
                                        ] || editVisit.order.status}
                                    </span>
                                </div>
                            )}
                            <div>
                                <div className="mb-1.5 flex items-center justify-between">
                                    <label className="text-xs font-bold text-slate-600">
                                        Lokasi GPS (opsional)
                                    </label>
                                    <button
                                        type="button"
                                        onClick={locateEditVisit}
                                        disabled={editVisitLocating}
                                        className="inline-flex items-center gap-1.5 text-xs font-bold text-[#0b7668] disabled:opacity-50"
                                    >
                                        {editVisitLocating ? (
                                            <Loader2
                                                size={13}
                                                className="animate-spin"
                                            />
                                        ) : (
                                            <LocateFixed size={13} />
                                        )}
                                        Ambil Lokasi Saat Ini
                                    </button>
                                </div>
                                <div className="grid grid-cols-2 gap-3">
                                    <Input
                                        type="number"
                                        placeholder="Latitude"
                                        value={editVisitForm.latitude}
                                        onChange={(e: any) =>
                                            updateEditVisitForm(
                                                "latitude",
                                                e.target.value,
                                            )
                                        }
                                    />
                                    <Input
                                        type="number"
                                        placeholder="Longitude"
                                        value={editVisitForm.longitude}
                                        onChange={(e: any) =>
                                            updateEditVisitForm(
                                                "longitude",
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>
                                {editVisitErrors.latitude && (
                                    <div className="mt-1 text-[11px] font-semibold text-rose-500">
                                        {editVisitErrors.latitude}
                                    </div>
                                )}
                            </div>
                            <div>
                                <label className="mb-1.5 block text-xs font-bold text-slate-600">
                                    Catatan / Next Action
                                </label>
                                <textarea
                                    value={editVisitForm.notes}
                                    onChange={(e) =>
                                        updateEditVisitForm(
                                            "notes",
                                            e.target.value,
                                        )
                                    }
                                    rows={3}
                                    placeholder="Opsional"
                                    className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none transition placeholder:text-slate-400 focus:border-[#18b89a] focus:ring-2 focus:ring-[#18b89a]/10"
                                />
                            </div>
                        </div>
                        <div className="flex justify-end gap-2 border-t bg-slate-50 px-5 py-3">
                            <Button
                                variant="outline"
                                onClick={closeEditVisit}
                                disabled={editVisitBusy}
                            >
                                Batal
                            </Button>
                            <Button
                                className="gap-2"
                                onClick={submitEditVisit}
                                disabled={editVisitBusy}
                            >
                                {editVisitBusy ? (
                                    <Loader2
                                        size={15}
                                        className="animate-spin"
                                    />
                                ) : (
                                    <Pencil size={15} />
                                )}
                                Simpan Perubahan
                            </Button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
