"use client";

import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { FormSheet } from "@/components/admin/FormSheet";
import { ImageDropZone } from "@/components/admin/ImageDropZone";
import { SectorIconPicker } from "@/components/admin/SectorIconPicker";
import { SECTOR_ICONS } from "@/lib/sectorIconMap";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Trash2, GripVertical, Loader2, CheckCircle2, Quote, Plus } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "sonner";
import { useImageUpload } from "@/hooks/use-image-upload";
import { uploadToCloudinary } from "@/lib/cloudinary";
import { useDragReorder } from "@/hooks/use-drag-reorder";
import { getClients, createClient, updateClient, deleteClient, reorderClients, type Client as ApiClient } from "@/services/clients";
import { getSectors, createSector, updateSector, deleteSector, reorderSectors, type Sector as ApiSector } from "@/services/sectors";
import { getTestimonials, createTestimonial, updateTestimonial, deleteTestimonial, reorderTestimonials, type Testimonial as ApiTestimonial } from "@/services/testimonials";
import { useAdminLocale } from "@/hooks/use-admin-locale";

// ─── Client helper type ───────────────────────────────────────────────────────

interface Client {
    id: number;
    name: string;
    type: string;
    logo: string;
    imagePublicId: string | null;
}

function toClient(c: ApiClient): Client {
    return { id: c.id, name: c.client_name, type: c.client_type, logo: c.client_image_url, imagePublicId: c.client_image_public_id ?? null };
}

// ─── Testimonials tab ─────────────────────────────────────────────────────────

function TestimonialsTabContent() {
    const [testimonials, setTestimonials] = useState<ApiTestimonial[]>([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState<ApiTestimonial | null>(null);
    const [isAdding, setIsAdding] = useState(false);
    const [contentValue, setContentValue] = useState("");
    const [nameValue, setNameValue] = useState("");
    const [positionValue, setPositionValue] = useState("");
    const [companyValue, setCompanyValue] = useState("");
    const [isSaving, setIsSaving] = useState(false);
    const [deletingId, setDeletingId] = useState<number | null>(null);

    const { preview, file, isDragging, setIsDragging, inputRef, handleFile, onDrop, reset: resetUpload } = useImageUpload();
    const [imageProgress, setImageProgress] = useState<number | null>(null);
    const [imageUploadDone, setImageUploadDone] = useState(false);
    const fetchedRef = useRef(false);

    const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
        testimonials,
        setTestimonials,
        (reordered) => {
            const positions = reordered.map((t, i) => ({ id: t.id, sort_order: i }));
            reorderTestimonials(positions).catch(() => {});
        },
    );

    useEffect(() => {
        if (fetchedRef.current) return;
        fetchedRef.current = true;
        getTestimonials()
            .then(setTestimonials)
            .finally(() => setLoading(false));
    }, []);

    const resetSheet = () => {
        setEditing(null);
        setIsAdding(false);
        setContentValue("");
        setNameValue("");
        setPositionValue("");
        setCompanyValue("");
        resetUpload();
        setImageProgress(null);
        setImageUploadDone(false);
    };

    const handleSave = async () => {
        if (!contentValue.trim()) { toast.error("Testimonial content is required."); return; }
        if (!nameValue.trim()) { toast.error("Name is required."); return; }
        if (!positionValue.trim()) { toast.error("Position/title is required."); return; }
        if (!companyValue.trim()) { toast.error("Company is required."); return; }
        setIsSaving(true);

        let imageResult: { secure_url: string; public_id: string } | undefined;
        if (file) {
            try {
                setImageProgress(0);
                imageResult = await uploadToCloudinary(file, "image", setImageProgress);
                setImageProgress(null);
                setImageUploadDone(true);
            } catch (err) {
                toast.error(err instanceof Error ? err.message : "Image upload failed.");
                setImageProgress(null);
                setIsSaving(false);
                return;
            }
        }

        try {
            if (isAdding) {
                const created = await createTestimonial({
                    testimonial_content: contentValue.trim(),
                    testimonial_name: nameValue.trim(),
                    testimonial_position: positionValue.trim(),
                    testimonial_company: companyValue.trim(),
                    ...(imageResult ? { testimonial_image_url: imageResult.secure_url, testimonial_image_public_id: imageResult.public_id } : {}),
                });
                setTestimonials((prev) => [...prev, created]);
                toast.success("Testimonial added.");
                resetSheet();
            } else {
                const updated = await updateTestimonial(editing!.id, {
                    testimonial_content: contentValue.trim(),
                    testimonial_name: nameValue.trim(),
                    testimonial_position: positionValue.trim(),
                    testimonial_company: companyValue.trim(),
                    ...(imageResult ? { testimonial_image_url: imageResult.secure_url, testimonial_image_public_id: imageResult.public_id } : {}),
                });
                setTestimonials((prev) => prev.map((t) => (t.id === updated.id ? updated : t)));
                toast.success("Testimonial updated.");
                resetSheet();
            }
        } catch {
            // interceptor shows toast
        } finally {
            setIsSaving(false);
        }
    };

    const handleDelete = async (e: React.MouseEvent, t: ApiTestimonial) => {
        e.stopPropagation();
        if (deletingId) return;
        setDeletingId(t.id);
        try {
            await deleteTestimonial(t.id);
            setTestimonials((prev) => prev.filter((x) => x.id !== t.id));
            toast.success("Testimonial removed.");
        } catch {
            // interceptor shows toast
        } finally {
            setDeletingId(null);
        }
    };

    const openEdit = (t: ApiTestimonial) => {
        setContentValue(t.testimonial_content);
        setNameValue(t.testimonial_name);
        setPositionValue(t.testimonial_position);
        setCompanyValue(t.testimonial_company);
        resetUpload();
        setImageProgress(null);
        setImageUploadDone(false);
        setEditing(t);
    };

    return (
        <div>
            <div className="flex items-center justify-between mb-6">
                <p className="text-sm text-muted-foreground">Manage client testimonials shown on the Clients page.</p>
                <Button
                    size="sm"
                    className="gap-2"
                    onClick={() => { resetSheet(); setIsAdding(true); }}
                >
                    <Plus className="h-4 w-4" /> Add Testimonial
                </Button>
            </div>

            <div className="space-y-3">
                {loading
                    ? Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-28 rounded-lg" />)
                    : testimonials.length === 0
                        ? (
                            <div className="text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                                No testimonials yet. Add your first one.
                            </div>
                        )
                        : testimonials.map((t, index) => (
                            <div
                                key={t.id}
                                draggable
                                onDragStart={() => onDragStart(index)}
                                onDragEnter={() => onDragEnter(index)}
                                onDragOver={(e) => e.preventDefault()}
                                onDragEnd={onDragEnd}
                                className="bg-card border rounded-lg p-5 flex gap-4 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                                onClick={() => openEdit(t)}
                            >
                                <div className="opacity-0 group-hover:opacity-100 transition-opacity self-center shrink-0">
                                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                                </div>
                                {t.testimonial_image_url ? (
                                    <Image src={t.testimonial_image_url} alt={t.testimonial_name} width={40} height={40} className="h-10 w-10 rounded-full object-cover shrink-0" />
                                ) : (
                                    <Quote className="h-5 w-5 text-accent shrink-0 mt-0.5" />
                                )}
                                <div className="flex-1 min-w-0">
                                    <p className="text-sm text-muted-foreground italic line-clamp-2">"{t.testimonial_content}"</p>
                                    <div className="flex items-center gap-2 mt-2">
                                        <span className="text-sm font-semibold">{t.testimonial_name}</span>
                                        <span className="text-xs text-muted-foreground">{t.testimonial_position},</span>
                                        <span className="text-xs text-accent font-medium">{t.testimonial_company}</span>
                                    </div>
                                </div>
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    className="absolute top-3 right-3 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                                    disabled={deletingId === t.id}
                                    onClick={(e) => handleDelete(e, t)}
                                >
                                    {deletingId === t.id
                                        ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                        : <Trash2 className="h-3.5 w-3.5" />}
                                </Button>
                            </div>
                        ))
                }
            </div>

            {!loading && testimonials.length > 0 && (
                <p className="text-xs text-muted-foreground mt-3">
                    {testimonials.length} testimonials · Click to edit, drag to reorder
                </p>
            )}

            <FormSheet
                open={!!editing || isAdding}
                onOpenChange={(open) => { if (!open) resetSheet(); }}
                title={editing ? "Edit Testimonial" : "New Testimonial"}
                onSave={handleSave}
                saveLabel={editing ? "Save Changes" : "Add Testimonial"}
                loading={isSaving}
            >
                <div className="space-y-2">
                    <Label>Testimonial Content</Label>
                    <Textarea
                        value={contentValue}
                        onChange={(e) => setContentValue(e.target.value)}
                        rows={4}
                        placeholder="What the client said..."
                    />
                </div>
                <div className="space-y-2">
                    <Label>Name</Label>
                    <Input
                        value={nameValue}
                        onChange={(e) => setNameValue(e.target.value)}
                        placeholder="e.g. Jane Doe"
                    />
                </div>
                <div className="space-y-2">
                    <Label>Position / Title</Label>
                    <Input
                        value={positionValue}
                        onChange={(e) => setPositionValue(e.target.value)}
                        placeholder="e.g. Operations Director"
                    />
                </div>
                <div className="space-y-2">
                    <Label>Company</Label>
                    <Input
                        value={companyValue}
                        onChange={(e) => setCompanyValue(e.target.value)}
                        placeholder="e.g. Acme Corp"
                    />
                </div>
                <div className="space-y-2">
                    <Label>Photo (optional)</Label>
                    <input
                        ref={inputRef}
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f); }}
                    />
                    <ImageDropZone
                        preview={preview}
                        fallback={editing?.testimonial_image_url ?? undefined}
                        isDragging={isDragging}
                        onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
                        onDragLeave={() => setIsDragging(false)}
                        onDrop={onDrop}
                        onClick={() => inputRef.current?.click()}
                    />
                    {imageProgress !== null && (
                        <div className="space-y-1">
                            <div className="flex justify-between text-xs text-muted-foreground">
                                <span>Uploading image…</span>
                                <span>{imageProgress}%</span>
                            </div>
                            <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                                <div className="h-full bg-primary rounded-full transition-all duration-150" style={{ width: `${imageProgress}%` }} />
                            </div>
                        </div>
                    )}
                    {imageUploadDone && imageProgress === null && (
                        <div className="flex items-center gap-1.5 text-xs text-emerald-600">
                            <CheckCircle2 className="h-3.5 w-3.5" />
                            <span>Image uploaded</span>
                        </div>
                    )}
                </div>
            </FormSheet>
        </div>
    );
}

// ─── Sectors tab ──────────────────────────────────────────────────────────────

function SectorsTabContent() {
    const locale = useAdminLocale();
    const [sectors, setSectors] = useState<ApiSector[]>([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState<ApiSector | null>(null);
    const [isAdding, setIsAdding] = useState(false);
    const [titleValue, setTitleValue] = useState("");
    const [descValue, setDescValue] = useState("");
    const [iconValue, setIconValue] = useState("Fuel");
    const [isSaving, setIsSaving] = useState(false);
    const [deletingId, setDeletingId] = useState<number | null>(null);
    const fetchedRef = useRef(false);

    const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
        sectors,
        setSectors,
        (reordered) => {
            const positions = reordered.map((s, i) => ({ id: s.id, sort_order: i }));
            reorderSectors(positions).catch(() => {});
        },
    );

    useEffect(() => {
        if (fetchedRef.current) return;
        fetchedRef.current = true;
        getSectors()
            .then(setSectors)
            .finally(() => setLoading(false));
    }, []);

    const resetSheet = () => {
        setEditing(null);
        setIsAdding(false);
        setTitleValue("");
        setDescValue("");
        setIconValue("Fuel");
    };

    const handleSave = async () => {
        if (!titleValue.trim()) { toast.error("Sector title is required."); return; }
        if (!descValue.trim()) { toast.error("Description is required."); return; }
        setIsSaving(true);
        try {
            if (isAdding) {
                const created = await createSector({
                    title: titleValue.trim(),
                    description: descValue.trim(),
                    icon: iconValue,
                });
                setSectors((prev) => [...prev, created]);
                toast.success("Sector added.");
                resetSheet();
            } else {
                const updated = await updateSector(editing!.id, {
                    title: { [locale]: titleValue.trim() },
                    description: { [locale]: descValue.trim() },
                    icon: iconValue,
                });
                setSectors((prev) => prev.map((s) => (s.id === updated.id ? updated : s)));
                toast.success("Sector updated.");
                resetSheet();
            }
        } catch {
            // interceptor shows toast
        } finally {
            setIsSaving(false);
        }
    };

    const handleDelete = async (e: React.MouseEvent, s: ApiSector) => {
        e.stopPropagation();
        if (deletingId) return;
        setDeletingId(s.id);
        try {
            await deleteSector(s.id);
            setSectors((prev) => prev.filter((x) => x.id !== s.id));
            toast.success("Sector removed.");
        } catch {
            // interceptor shows toast
        } finally {
            setDeletingId(null);
        }
    };

    const openEdit = (s: ApiSector) => {
        setTitleValue(s.title);
        setDescValue(s.description);
        setIconValue(s.icon);
        setEditing(s);
    };

    return (
        <div>
            <div className="flex items-center justify-between mb-6">
                <p className="text-sm text-muted-foreground">Manage industry sectors shown on the Clients page.</p>
                <Button
                    size="sm"
                    className="gap-2"
                    onClick={() => { resetSheet(); setIsAdding(true); }}
                >
                    <Plus className="h-4 w-4" /> Add Sector
                </Button>
            </div>

            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {loading
                    ? Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-28 rounded-lg" />)
                    : sectors.length === 0
                        ? (
                            <div className="col-span-full text-center text-sm text-muted-foreground py-16 bg-card border rounded-lg">
                                No sectors yet. Add your first one.
                            </div>
                        )
                        : sectors.map((s, index) => {
                            const IconComp = SECTOR_ICONS[s.icon]?.component;
                            return (
                                <div
                                    key={s.id}
                                    draggable
                                    onDragStart={() => onDragStart(index)}
                                    onDragEnter={() => onDragEnter(index)}
                                    onDragOver={(e) => e.preventDefault()}
                                    onDragEnd={onDragEnd}
                                    className="bg-card border rounded-lg p-5 cursor-pointer hover:bg-muted/30 transition-colors relative group"
                                    onClick={() => openEdit(s)}
                                >
                                    <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1">
                                        <GripVertical className="h-4 w-4 text-muted-foreground" />
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="h-6 w-6 text-destructive hover:text-destructive"
                                            disabled={deletingId === s.id}
                                            onClick={(e) => handleDelete(e, s)}
                                        >
                                            {deletingId === s.id
                                                ? <Loader2 className="h-3 w-3 animate-spin" />
                                                : <Trash2 className="h-3 w-3" />}
                                        </Button>
                                    </div>
                                    <div className="flex items-center gap-3 mb-2 pr-16">
                                        {IconComp && <IconComp className="h-5 w-5 text-primary shrink-0" />}
                                        <h3 className="font-semibold text-sm leading-tight">{s.title}</h3>
                                    </div>
                                    <p className="text-xs text-muted-foreground leading-relaxed line-clamp-2">
                                        {s.description}
                                    </p>
                                </div>
                            );
                        })
                }
            </div>

            {!loading && sectors.length > 0 && (
                <p className="text-xs text-muted-foreground mt-3">
                    {sectors.length} sectors · Click to edit, drag to reorder
                </p>
            )}

            <FormSheet
                open={!!editing || isAdding}
                onOpenChange={(open) => { if (!open) resetSheet(); }}
                title={editing ? `Edit: ${editing.title}` : "New Sector"}
                onSave={handleSave}
                saveLabel={editing ? "Save Changes" : "Add Sector"}
                loading={isSaving}
            >
                <div className="space-y-2">
                    <Label>Sector Title</Label>
                    <Input
                        value={titleValue}
                        onChange={(e) => setTitleValue(e.target.value)}
                        placeholder="e.g. Upstream Oil & Gas"
                    />
                </div>
                <div className="space-y-2">
                    <Label>Description</Label>
                    <Textarea
                        value={descValue}
                        onChange={(e) => setDescValue(e.target.value)}
                        rows={3}
                        placeholder="Short description of this industry sector..."
                    />
                </div>
                <div className="space-y-2">
                    <Label>Icon</Label>
                    <SectorIconPicker value={iconValue} onChange={setIconValue} />
                </div>
            </FormSheet>
        </div>
    );
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function ClientsAdmin() {
    const [clients, setClients] = useState<Client[]>([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState<Client | null>(null);
    const [isAdding, setIsAdding] = useState(false);
    const [nameValue, setNameValue] = useState("");
    const [typeValue, setTypeValue] = useState("");
    const [isSaving, setIsSaving] = useState(false);
    const [deletingId, setDeletingId] = useState<number | null>(null);

    const [testimonialsActivated, setTestimonialsActivated] = useState(false);
    const [sectorsActivated, setSectorsActivated] = useState(false);

    const { preview, file, isDragging, setIsDragging, inputRef, handleFile, onDrop, reset: resetUpload } = useImageUpload();
    const [imageProgress, setImageProgress] = useState<number | null>(null);
    const [imageUploadDone, setImageUploadDone] = useState(false);

    const { onDragStart, onDragEnter, onDragEnd } = useDragReorder(
        clients,
        setClients,
        (reordered) => {
            const positions = reordered.map((c, i) => ({ id: c.id, client_position: i + 1 }));
            reorderClients(positions)
                .then(() => toast.success("Order updated."))
                .catch((err) => toast.error(err.message));
        },
    );

    useEffect(() => {
        getClients()
            .then((data) => setClients(data.map(toClient)))
            .finally(() => setLoading(false));
    }, []);

    const handleTabChange = (value: string) => {
        if (value === "testimonials") setTestimonialsActivated(true);
        if (value === "sectors") setSectorsActivated(true);
    };

    const resetSheet = () => {
        setEditing(null);
        setIsAdding(false);
        setNameValue("");
        setTypeValue("");
        resetUpload();
        setImageProgress(null);
        setImageUploadDone(false);
    };

    const handleSave = async () => {
        if (!nameValue.trim()) {
            toast.error("Company name is required.");
            return;
        }
        if (nameValue.trim().length > 255) {
            toast.error("Company name must be 255 characters or fewer.");
            return;
        }
        if (isAdding && !file) {
            toast.error("Please upload a logo image.");
            return;
        }
        setIsSaving(true);

        let imageResult: { secure_url: string; public_id: string } | undefined;
        if (file) {
            try {
                setImageProgress(0);
                imageResult = await uploadToCloudinary(file, "image", setImageProgress);
                setImageProgress(null);
                setImageUploadDone(true);
            } catch (err) {
                toast.error(err instanceof Error ? err.message : "Image upload failed.");
                setImageProgress(null);
                setIsSaving(false);
                return;
            }
        }

        try {
            if (isAdding) {
                const created = await createClient(
                    nameValue.trim(),
                    typeValue.trim(),
                    imageResult!.secure_url,
                    imageResult!.public_id,
                );
                setClients((prev) => [...prev, toClient(created)]);
                toast.success("Client added.");
                resetSheet();
            } else {
                const updated = await updateClient(editing!.id, {
                    client_name: nameValue.trim(),
                    client_type: typeValue.trim() || undefined,
                    client_image_url: imageResult?.secure_url,
                    client_image_public_id: imageResult?.public_id,
                });
                setClients((prev) => prev.map((c) => (c.id === updated.id ? toClient(updated) : c)));
                toast.success("Client updated.");
                resetSheet();
            }
        } catch {
            // interceptor shows toast
        } finally {
            setIsSaving(false);
        }
    };

    const handleDelete = async (e: React.MouseEvent, client: Client) => {
        e.stopPropagation();
        if (deletingId) return;
        setDeletingId(client.id);
        try {
            await deleteClient(client.id, client.imagePublicId);
            setClients((prev) => prev.filter((c) => c.id !== client.id));
            toast.success("Client removed.");
        } catch {
            // interceptor shows toast
        } finally {
            setDeletingId(null);
        }
    };

    const openEdit = (client: Client) => {
        resetUpload();
        setImageProgress(null);
        setImageUploadDone(false);
        setNameValue(client.name);
        setTypeValue(client.type);
        setEditing(client);
    };

    return (
        <div className="p-6 lg:p-8 max-w-7xl mx-auto">
            <div className="mb-8">
                <h1 className="text-2xl font-bold tracking-tight text-foreground">Clients & Partners</h1>
                <p className="text-sm text-muted-foreground mt-1">
                    Manage client logos, testimonials, and industry sectors.
                </p>
            </div>

            <Tabs defaultValue="clients" onValueChange={handleTabChange}>
                <TabsList>
                    <TabsTrigger value="clients">Clients</TabsTrigger>
                    <TabsTrigger value="testimonials">Testimonials</TabsTrigger>
                    <TabsTrigger value="sectors">Sectors</TabsTrigger>
                </TabsList>

                {/* ── Clients tab ── */}
                <TabsContent value="clients" className="mt-6">
                    <div className="flex items-center justify-between mb-6">
                        <p className="text-sm text-muted-foreground">Manage client logos. Drag to reorder.</p>
                        <Button
                            size="sm"
                            className="gap-2"
                            onClick={() => { setNameValue(""); setTypeValue(""); setIsAdding(true); }}
                        >
                            <Plus className="h-4 w-4" /> Add Client
                        </Button>
                    </div>

                    <div className="bg-card rounded-lg border shadow-sm">
                        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-px bg-border">
                            {loading
                                ? Array.from({ length: 10 }).map((_, i) => (
                                    <div key={i} className="bg-card p-6 flex flex-col items-center gap-3">
                                        <Skeleton className="h-12 w-24" />
                                        <Skeleton className="h-3 w-16" />
                                    </div>
                                ))
                                : clients.map((client, index) => (
                                    <div
                                        key={client.id}
                                        draggable
                                        onDragStart={() => onDragStart(index)}
                                        onDragEnter={() => onDragEnter(index)}
                                        onDragOver={(e) => e.preventDefault()}
                                        onDragEnd={onDragEnd}
                                        className="bg-card p-6 flex flex-col items-center gap-3 group relative cursor-pointer hover:bg-muted/50 transition-colors"
                                        onClick={() => openEdit(client)}
                                    >
                                        <div className="absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <GripVertical className="h-4 w-4 text-muted-foreground" />
                                        </div>
                                        {client.logo
                                            ? <Image src={client.logo} alt={client.name} width={96} height={48} className="h-12 w-auto object-contain grayscale group-hover:grayscale-0 transition-all" />
                                            : <div className="h-12 w-24 rounded bg-muted" />
                                        }
                                        <span className="text-xs text-muted-foreground font-medium">{client.name}</span>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive"
                                            disabled={deletingId === client.id}
                                            onClick={(e) => handleDelete(e, client)}
                                        >
                                            {deletingId === client.id
                                                ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                                : <Trash2 className="h-3.5 w-3.5" />}
                                        </Button>
                                    </div>
                                ))
                            }
                        </div>
                    </div>
                    <p className="text-xs text-muted-foreground mt-3">
                        {clients.length} clients · Click to edit, drag to reorder
                    </p>
                </TabsContent>

                {/* ── Testimonials tab (lazy) ── */}
                <TabsContent value="testimonials" className="mt-6">
                    {testimonialsActivated && <TestimonialsTabContent />}
                </TabsContent>

                {/* ── Sectors tab (lazy) ── */}
                <TabsContent value="sectors" className="mt-6">
                    {sectorsActivated && <SectorsTabContent />}
                </TabsContent>
            </Tabs>

            {/* Client add/edit sheet */}
            <FormSheet
                open={!!editing || isAdding}
                onOpenChange={(open) => { if (!open) resetSheet(); }}
                title={editing ? `Edit: ${editing.name}` : "New Client"}
                onSave={handleSave}
                saveLabel={editing ? "Save Changes" : "Add Client"}
                loading={isSaving}
            >
                <div className="space-y-2">
                    <Label>Company Name</Label>
                    <Input value={nameValue} onChange={(e) => setNameValue(e.target.value)} />
                </div>
                <div className="space-y-2">
                    <Label>Client Type</Label>
                    <Input value={typeValue} onChange={(e) => setTypeValue(e.target.value)} placeholder="e.g. Oil & Gas, Marine, Aviation" />
                </div>
                <div className="space-y-2">
                    <Label>Logo</Label>
                    <input
                        ref={inputRef}
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f); }}
                    />
                    <ImageDropZone
                        preview={preview}
                        fallback={editing?.logo}
                        isDragging={isDragging}
                        onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
                        onDragLeave={() => setIsDragging(false)}
                        onDrop={onDrop}
                        onClick={() => inputRef.current?.click()}
                    />
                    {imageProgress !== null && (
                        <div className="space-y-1">
                            <div className="flex justify-between text-xs text-muted-foreground">
                                <span>Uploading image…</span>
                                <span>{imageProgress}%</span>
                            </div>
                            <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                                <div
                                    className="h-full bg-primary rounded-full transition-all duration-150"
                                    style={{ width: `${imageProgress}%` }}
                                />
                            </div>
                        </div>
                    )}
                    {imageUploadDone && imageProgress === null && (
                        <div className="flex items-center gap-1.5 text-xs text-emerald-600">
                            <CheckCircle2 className="h-3.5 w-3.5" />
                            <span>Image uploaded</span>
                        </div>
                    )}
                </div>
            </FormSheet>
        </div>
    );
}