import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { Link } from "@tanstack/react-router";
import * as React from "react";
import { useQueryClient, useQuery } from "@tanstack/react-query";
import { s as supabase, m as cn, B as Button, D as Dialog, b as DialogContent, e as DialogHeader, f as DialogTitle, c as DialogDescription, d as DialogFooter, u as useAuth } from "./router-D4ixsMHb.js";
import { createLovableAuth } from "@lovable.dev/cloud-auth-js";
import { I as Input } from "./input-Cu7YTZO_.js";
import { L as Label, T as Textarea } from "./label-GLGnKkqd.js";
import { cva } from "class-variance-authority";
import { toast } from "sonner";
import { X, Image, Loader2, Upload, Search, Plus, Newspaper, Star, EyeOff, Eye, Pencil, Trash2, ShieldCheck, LayoutDashboard, Package, FolderTree, Tag, Inbox, Home, MessageSquareQuote, Settings, ExternalLink, LogOut, Download, Mail, Phone } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import "@radix-ui/react-slot";
import "clsx";
import "tailwind-merge";
import "cmdk";
import "@radix-ui/react-dialog";
import "@supabase/supabase-js";
import "@radix-ui/react-label";
const lovableAuth = createLovableAuth();
const lovable = {
  auth: {
    signInWithOAuth: async (provider, opts) => {
      const result = await lovableAuth.signInWithOAuth(provider, {
        redirect_uri: opts?.redirect_uri,
        extraParams: {
          ...opts?.extraParams
        }
      });
      if (result.redirected) {
        return result;
      }
      if (result.error) {
        return result;
      }
      try {
        await supabase.auth.setSession(result.tokens);
      } catch (e) {
        return { error: e instanceof Error ? e : new Error(String(e)) };
      }
      return result;
    }
  }
};
const Table = React.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { className: "relative w-full overflow-auto", children: /* @__PURE__ */ jsx("table", { ref, className: cn("w-full caption-bottom text-sm", className), ...props }) })
);
Table.displayName = "Table";
const TableHeader = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("thead", { ref, className: cn("[&_tr]:border-b", className), ...props }));
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("tbody", { ref, className: cn("[&_tr:last-child]:border-0", className), ...props }));
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
  "tfoot",
  {
    ref,
    className: cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className),
    ...props
  }
));
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ jsx(
    "tr",
    {
      ref,
      className: cn(
        "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
        className
      ),
      ...props
    }
  )
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
  "th",
  {
    ref,
    className: cn(
      "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    ),
    ...props
  }
));
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
  "td",
  {
    ref,
    className: cn(
      "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    ),
    ...props
  }
));
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("caption", { ref, className: cn("mt-4 text-sm text-muted-foreground", className), ...props }));
TableCaption.displayName = "TableCaption";
const badgeVariants = cva(
  "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
  {
    variants: {
      variant: {
        default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
        secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
        destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
        outline: "text-foreground"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
);
function Badge({ className, variant, ...props }) {
  return /* @__PURE__ */ jsx("div", { className: cn(badgeVariants({ variant }), className), ...props });
}
function ImageUploader({ value, onChange, folder = "uploads", label = "Image", aspect = "square" }) {
  const [busy, setBusy] = React.useState(false);
  const inputRef = React.useRef(null);
  async function handleFile(file) {
    if (!file.type.startsWith("image/")) {
      toast.error("Please choose an image file");
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error("Image must be under 5MB");
      return;
    }
    setBusy(true);
    try {
      const ext = file.name.split(".").pop()?.toLowerCase() || "jpg";
      const safe = file.name.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "image";
      const path = `${folder}/${Date.now()}-${safe}.${ext}`;
      const { error } = await supabase.storage.from("media").upload(path, file, {
        cacheControl: "31536000",
        upsert: false,
        contentType: file.type
      });
      if (error) throw error;
      const { data } = supabase.storage.from("media").getPublicUrl(path);
      onChange(data.publicUrl);
      toast.success("Image uploaded");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Upload failed");
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }
  const aspectClass = aspect === "wide" ? "aspect-[16/9]" : aspect === "tall" ? "aspect-[3/4]" : "aspect-square";
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    label && /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: label }),
    /* @__PURE__ */ jsxs("div", { className: "flex gap-3", children: [
      /* @__PURE__ */ jsx(
        "div",
        {
          className: `relative w-28 ${aspectClass} flex-none overflow-hidden rounded-md border border-border bg-muted`,
          children: value ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("img", { src: value, alt: "", className: "absolute inset-0 h-full w-full object-cover" }),
            /* @__PURE__ */ jsx(
              "button",
              {
                type: "button",
                onClick: () => onChange(""),
                className: "absolute right-1 top-1 rounded-full bg-background/90 p-1 text-foreground shadow hover:bg-background",
                "aria-label": "Remove image",
                children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
              }
            )
          ] }) : /* @__PURE__ */ jsx("div", { className: "absolute inset-0 flex items-center justify-center text-muted-foreground", children: /* @__PURE__ */ jsx(Image, { className: "h-6 w-6" }) })
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col gap-2", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            ref: inputRef,
            type: "file",
            accept: "image/*",
            className: "hidden",
            onChange: (e) => {
              const f = e.target.files?.[0];
              if (f) handleFile(f);
            }
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            disabled: busy,
            onClick: () => inputRef.current?.click(),
            className: "w-fit",
            children: [
              busy ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Upload, { className: "mr-2 h-4 w-4" }),
              busy ? "Uploading…" : "Upload image"
            ]
          }
        ),
        /* @__PURE__ */ jsx(
          Input,
          {
            value,
            onChange: (e) => onChange(e.target.value),
            placeholder: "Or paste URL (e.g. /assets/img/foo.jpg)",
            className: "text-xs"
          }
        )
      ] })
    ] })
  ] });
}
function SectionToolbar({
  search,
  setSearch,
  onAdd,
  count,
  addLabel = "Add"
}) {
  return /* @__PURE__ */ jsxs("div", { className: "mb-4 flex flex-wrap items-center justify-between gap-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "relative max-w-sm flex-1", children: [
      /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: search,
          onChange: (e) => setSearch(e.target.value),
          placeholder: "Search…",
          className: "pl-9"
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
        count,
        " item",
        count === 1 ? "" : "s"
      ] }),
      /* @__PURE__ */ jsxs(Button, { onClick: onAdd, className: "bg-primary text-primary-foreground hover:bg-primary/90", children: [
        /* @__PURE__ */ jsx(Plus, { className: "mr-1 h-4 w-4" }),
        " ",
        addLabel
      ] })
    ] })
  ] });
}
function StatusBadge({ status }) {
  const map = {
    new: "bg-blue-500/15 text-blue-700 dark:text-blue-300",
    contacted: "bg-amber-500/15 text-amber-700 dark:text-amber-300",
    closed: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"
  };
  return /* @__PURE__ */ jsx("span", { className: cn("rounded-full px-2 py-0.5 text-xs font-medium", map[status] ?? "bg-muted text-muted-foreground"), children: status });
}
function slugify(s) {
  return s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
}
function BlogAdmin() {
  const qc = useQueryClient();
  const { data = [] } = useQuery({
    queryKey: ["admin_blog_posts"],
    queryFn: async () => {
      const { data: data2, error } = await supabase.from("blog_posts").select("*").order("published_at", { ascending: false, nullsFirst: false }).order("created_at", { ascending: false });
      if (error) throw error;
      return data2 ?? [];
    }
  });
  const [editing, setEditing] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const emptyForm = {
    title: "",
    slug: "",
    excerpt: "",
    body: "",
    cover_url: "",
    read_min: 5,
    published: false,
    featured: false,
    published_at: "",
    sort_order: 0
  };
  const [form, setForm] = React.useState(emptyForm);
  const [preview, setPreview] = React.useState(true);
  const [inlineBusy, setInlineBusy] = React.useState(false);
  const bodyRef = React.useRef(null);
  React.useEffect(() => {
    if (editing) {
      setForm({
        title: editing.title ?? "",
        slug: editing.slug ?? "",
        excerpt: editing.excerpt ?? "",
        body: editing.body ?? "",
        cover_url: editing.cover_url ?? "",
        read_min: editing.read_min ?? 5,
        published: !!editing.published,
        featured: !!editing.featured,
        published_at: editing.published_at ? editing.published_at.slice(0, 10) : "",
        sort_order: editing.sort_order ?? 0
      });
    } else {
      setForm(emptyForm);
    }
  }, [editing]);
  const filtered = data.filter(
    (p) => [p.title, p.slug].some((v) => (v ?? "").toLowerCase().includes(search.toLowerCase()))
  );
  function openAdd() {
    setEditing(null);
    setOpen(true);
  }
  function openEdit(p) {
    setEditing(p);
    setOpen(true);
  }
  async function togglePublish(p) {
    const next = !p.published;
    const { error } = await supabase.from("blog_posts").update({
      published: next,
      published_at: next ? p.published_at ?? (/* @__PURE__ */ new Date()).toISOString() : p.published_at
    }).eq("id", p.id);
    if (error) toast.error(error.message);
    else {
      toast.success(next ? "Published" : "Unpublished");
      qc.invalidateQueries({ queryKey: ["admin_blog_posts"] });
      qc.invalidateQueries({ queryKey: ["blog_posts_public"] });
    }
  }
  async function toggleFeatured(p) {
    const { error } = await supabase.from("blog_posts").update({ featured: !p.featured }).eq("id", p.id);
    if (error) toast.error(error.message);
    else {
      toast.success(!p.featured ? "Marked as featured" : "Removed from featured");
      qc.invalidateQueries({ queryKey: ["admin_blog_posts"] });
      qc.invalidateQueries({ queryKey: ["blog_posts_public"] });
    }
  }
  function insertAtCursor(snippet) {
    const ta = bodyRef.current;
    if (!ta) {
      setForm((f) => ({ ...f, body: f.body + snippet }));
      return;
    }
    const start = ta.selectionStart ?? ta.value.length;
    const end = ta.selectionEnd ?? ta.value.length;
    const next = ta.value.slice(0, start) + snippet + ta.value.slice(end);
    setForm((f) => ({ ...f, body: next }));
    requestAnimationFrame(() => {
      ta.focus();
      const pos = start + snippet.length;
      ta.setSelectionRange(pos, pos);
    });
  }
  async function uploadInlineImage(file) {
    if (!file.type.startsWith("image/")) return toast.error("Choose an image file");
    if (file.size > 5 * 1024 * 1024) return toast.error("Image must be under 5MB");
    setInlineBusy(true);
    try {
      const ext = file.name.split(".").pop()?.toLowerCase() || "jpg";
      const safe = file.name.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40) || "image";
      const path = `blog/inline/${Date.now()}-${safe}.${ext}`;
      const { error } = await supabase.storage.from("media").upload(path, file, { cacheControl: "31536000", contentType: file.type });
      if (error) throw error;
      const { data: data2 } = supabase.storage.from("media").getPublicUrl(path);
      insertAtCursor(`

![${safe}](${data2.publicUrl})

`);
      toast.success("Image inserted");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setInlineBusy(false);
    }
  }
  const inlineFileRef = React.useRef(null);
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(
      SectionToolbar,
      {
        search,
        setSearch,
        onAdd: openAdd,
        count: filtered.length,
        addLabel: "New post"
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-hidden", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Article" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Published" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 4, className: "py-10 text-center text-sm text-muted-foreground", children: 'No articles yet. Click "New post" to write your first one.' }) }),
        filtered.map((p) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            p.cover_url ? /* @__PURE__ */ jsx("img", { src: p.cover_url, alt: "", className: "h-10 w-14 rounded-md object-cover bg-muted" }) : /* @__PURE__ */ jsx("div", { className: "flex h-10 w-14 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx(Newspaper, { className: "h-4 w-4 text-muted-foreground" }) }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsxs("div", { className: "truncate flex items-center gap-2", children: [
                p.title,
                p.featured && /* @__PURE__ */ jsx(Star, { className: "h-3.5 w-3.5 fill-amber-400 text-amber-500" })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground truncate", children: [
                "/blog/",
                p.slug
              ] })
            ] })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { children: p.published ? /* @__PURE__ */ jsx(Badge, { className: "bg-emerald-500/15 text-emerald-700 border-emerald-500/20", children: "Published" }) : /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "Draft" }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-muted-foreground text-sm", children: p.published_at ? new Date(p.published_at).toLocaleDateString() : "—" }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right", children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => toggleFeatured(p), title: p.featured ? "Unfeature" : "Feature", children: /* @__PURE__ */ jsx(Star, { className: cn("h-4 w-4", p.featured && "fill-amber-400 text-amber-500") }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => togglePublish(p), title: p.published ? "Unpublish" : "Publish", children: p.published ? /* @__PURE__ */ jsx(EyeOff, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => openEdit(p), children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                size: "sm",
                variant: "ghost",
                onClick: async () => {
                  if (!confirm(`Delete "${p.title}"?`)) return;
                  const { error } = await supabase.from("blog_posts").delete().eq("id", p.id);
                  if (error) toast.error(error.message);
                  else {
                    toast.success("Deleted");
                    qc.invalidateQueries({ queryKey: ["admin_blog_posts"] });
                    qc.invalidateQueries({ queryKey: ["blog_posts_public"] });
                  }
                },
                children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" })
              }
            )
          ] })
        ] }, p.id))
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-5xl max-h-[92vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editing ? "Edit article" : "New article" }),
        /* @__PURE__ */ jsx(DialogDescription, { children: "Body supports markdown — use `## Heading`, `**bold**`, lists, and links. Separate paragraphs with a blank line." })
      ] }),
      /* @__PURE__ */ jsxs(
        "form",
        {
          className: "space-y-3",
          onSubmit: async (e) => {
            e.preventDefault();
            const payload = {
              title: form.title,
              slug: form.slug || slugify(form.title),
              excerpt: form.excerpt,
              body: form.body,
              cover_url: form.cover_url || null,
              read_min: Number(form.read_min) || 5,
              published: form.published,
              featured: form.featured,
              published_at: form.published ? form.published_at ? new Date(form.published_at).toISOString() : (/* @__PURE__ */ new Date()).toISOString() : form.published_at ? new Date(form.published_at).toISOString() : null,
              sort_order: Number(form.sort_order) || 0
            };
            const { error } = editing ? await supabase.from("blog_posts").update(payload).eq("id", editing.id) : await supabase.from("blog_posts").insert(payload);
            if (error) toast.error(error.message);
            else {
              toast.success("Saved");
              setOpen(false);
              setEditing(null);
              qc.invalidateQueries({ queryKey: ["admin_blog_posts"] });
              qc.invalidateQueries({ queryKey: ["blog_posts_public"] });
            }
          },
          children: [
            /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
                /* @__PURE__ */ jsx(Label, { children: "Title" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: form.title,
                    onChange: (e) => {
                      const title = e.target.value;
                      setForm((f) => ({
                        ...f,
                        title,
                        slug: !editing && (!f.slug || f.slug === slugify(f.title)) ? slugify(title) : f.slug
                      }));
                    },
                    required: true
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Slug" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: form.slug,
                    onChange: (e) => setForm({ ...form, slug: e.target.value }),
                    placeholder: "auto-from-title"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Read time (min)" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "number",
                    min: 1,
                    value: form.read_min,
                    onChange: (e) => setForm({ ...form, read_min: Number(e.target.value) })
                  }
                )
              ] }),
              /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(
                ImageUploader,
                {
                  value: form.cover_url ?? "",
                  onChange: (url) => setForm({ ...form, cover_url: url }),
                  folder: "blog",
                  label: "Cover image",
                  aspect: "wide"
                }
              ) }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
                /* @__PURE__ */ jsx(Label, { children: "Excerpt" }),
                /* @__PURE__ */ jsx(
                  Textarea,
                  {
                    rows: 2,
                    value: form.excerpt,
                    onChange: (e) => setForm({ ...form, excerpt: e.target.value }),
                    placeholder: "Short summary shown in lists and social previews."
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
                /* @__PURE__ */ jsxs("div", { className: "mb-2 flex flex-wrap items-center justify-between gap-2", children: [
                  /* @__PURE__ */ jsx(Label, { className: "m-0", children: "Body (markdown)" }),
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1", children: [
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("## Heading\n\n"), children: "H2" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("**bold**"), children: "B" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("_italic_"), children: /* @__PURE__ */ jsx("span", { className: "italic", children: "I" }) }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("\n- item\n- item\n"), children: "List" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("[text](https://)"), children: "Link" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("\n\n> Quote\n\n"), children: "Quote" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => insertAtCursor("\n```\ncode\n```\n"), children: "Code" }),
                    /* @__PURE__ */ jsx(
                      "input",
                      {
                        ref: inlineFileRef,
                        type: "file",
                        accept: "image/*",
                        className: "hidden",
                        onChange: (e) => {
                          const f = e.target.files?.[0];
                          if (f) uploadInlineImage(f);
                          if (inlineFileRef.current) inlineFileRef.current.value = "";
                        }
                      }
                    ),
                    /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", variant: "outline", disabled: inlineBusy, onClick: () => inlineFileRef.current?.click(), children: [
                      /* @__PURE__ */ jsx(Image, { className: "mr-1 h-3.5 w-3.5" }),
                      " ",
                      inlineBusy ? "Uploading…" : "Image"
                    ] }),
                    /* @__PURE__ */ jsx("span", { className: "mx-1 h-4 w-px bg-border" }),
                    /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: preview ? "default" : "outline", onClick: () => setPreview((v) => !v), children: preview ? "Hide preview" : "Show preview" })
                  ] })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: cn("grid gap-3", preview ? "md:grid-cols-2" : "grid-cols-1"), children: [
                  /* @__PURE__ */ jsx(
                    Textarea,
                    {
                      ref: bodyRef,
                      rows: 20,
                      value: form.body,
                      onChange: (e) => setForm({ ...form, body: e.target.value }),
                      className: "font-mono text-sm",
                      onDrop: (e) => {
                        const f = e.dataTransfer.files?.[0];
                        if (f && f.type.startsWith("image/")) {
                          e.preventDefault();
                          uploadInlineImage(f);
                        }
                      },
                      placeholder: "## Introduction\n\nFirst paragraph…\n\nDrop an image here, or click the Image button to upload."
                    }
                  ),
                  preview && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-border bg-background p-4 overflow-auto max-h-[520px]", children: form.body.trim() ? /* @__PURE__ */ jsx("article", { className: "prose prose-sm max-w-none dark:prose-invert prose-img:rounded-sm", children: /* @__PURE__ */ jsx(ReactMarkdown, { remarkPlugins: [remarkGfm], children: form.body }) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Live preview appears here as you type." }) })
                ] })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2 grid gap-2 sm:grid-cols-2", children: [
                /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 rounded-sm border border-border bg-muted/30 px-3 py-2 cursor-pointer", children: [
                  /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "checkbox",
                      checked: form.published,
                      onChange: (e) => setForm({ ...form, published: e.target.checked }),
                      className: "h-4 w-4 accent-primary"
                    }
                  ),
                  /* @__PURE__ */ jsx("span", { className: "font-medium text-sm", children: "Published (visible on /blog)" })
                ] }),
                /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 rounded-sm border border-border bg-muted/30 px-3 py-2 cursor-pointer", children: [
                  /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "checkbox",
                      checked: form.featured,
                      onChange: (e) => setForm({ ...form, featured: e.target.checked }),
                      className: "h-4 w-4 accent-primary"
                    }
                  ),
                  /* @__PURE__ */ jsxs("span", { className: "font-medium text-sm flex items-center gap-1", children: [
                    /* @__PURE__ */ jsx(Star, { className: "h-3.5 w-3.5 text-amber-500" }),
                    " Featured article"
                  ] })
                ] })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
                /* @__PURE__ */ jsx(Label, { children: "Publish date" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "date",
                    value: form.published_at,
                    onChange: (e) => setForm({ ...form, published_at: e.target.value })
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Leave blank to use today when publishing." })
              ] })
            ] }),
            /* @__PURE__ */ jsxs(DialogFooter, { className: "pt-2", children: [
              /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => {
                setOpen(false);
                setEditing(null);
              }, children: "Cancel" }),
              /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90", children: editing ? "Save changes" : "Create article" })
            ] })
          ]
        }
      )
    ] }) })
  ] });
}
function TestimonialsAdmin() {
  const qc = useQueryClient();
  const { data = [] } = useQuery({
    queryKey: ["admin_testimonials"],
    queryFn: async () => {
      const { data: data2, error } = await supabase.from("testimonials").select("*").order("sort_order", { ascending: true }).order("created_at", { ascending: false });
      if (error) throw error;
      return data2 ?? [];
    }
  });
  const emptyForm = {
    name: "",
    role: "",
    clinic: "",
    location: "",
    quote: "",
    rating: 5,
    avatar_url: "",
    sort_order: 0,
    published: true
  };
  const [form, setForm] = React.useState(emptyForm);
  const [editing, setEditing] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  React.useEffect(() => {
    if (editing) {
      setForm({
        name: editing.name ?? "",
        role: editing.role ?? "",
        clinic: editing.clinic ?? "",
        location: editing.location ?? "",
        quote: editing.quote ?? "",
        rating: editing.rating ?? 5,
        avatar_url: editing.avatar_url ?? "",
        sort_order: editing.sort_order ?? 0,
        published: !!editing.published
      });
    } else {
      setForm(emptyForm);
    }
  }, [editing]);
  const filtered = data.filter(
    (t) => [t.name, t.clinic, t.location, t.quote].some(
      (v) => (v ?? "").toLowerCase().includes(search.toLowerCase())
    )
  );
  async function togglePublish(t) {
    const { error } = await supabase.from("testimonials").update({ published: !t.published }).eq("id", t.id);
    if (error) toast.error(error.message);
    else {
      toast.success(!t.published ? "Published" : "Unpublished");
      qc.invalidateQueries({ queryKey: ["admin_testimonials"] });
      qc.invalidateQueries({ queryKey: ["pub_testimonials"] });
    }
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(
      SectionToolbar,
      {
        search,
        setSearch,
        onAdd: () => {
          setEditing(null);
          setOpen(true);
        },
        count: filtered.length,
        addLabel: "New testimonial"
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-hidden", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Author" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Quote" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Order" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 5, className: "py-10 text-center text-sm text-muted-foreground", children: 'No testimonials yet. Click "New testimonial" to add one.' }) }),
        filtered.map((t) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsx("div", { className: "truncate", children: t.name }),
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: [t.clinic, t.location].filter(Boolean).join(" · ") })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "max-w-[360px]", children: /* @__PURE__ */ jsx("div", { className: "line-clamp-2 text-sm text-muted-foreground", children: t.quote }) }),
          /* @__PURE__ */ jsx(TableCell, { children: t.published ? /* @__PURE__ */ jsx(Badge, { className: "bg-emerald-500/15 text-emerald-700 border-emerald-500/20", children: "Published" }) : /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "Hidden" }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-sm text-muted-foreground", children: t.sort_order }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right", children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => togglePublish(t), title: t.published ? "Hide" : "Show", children: t.published ? /* @__PURE__ */ jsx(EyeOff, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => {
              setEditing(t);
              setOpen(true);
            }, children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                size: "sm",
                variant: "ghost",
                onClick: async () => {
                  if (!confirm(`Delete testimonial from "${t.name}"?`)) return;
                  const { error } = await supabase.from("testimonials").delete().eq("id", t.id);
                  if (error) toast.error(error.message);
                  else {
                    toast.success("Deleted");
                    qc.invalidateQueries({ queryKey: ["admin_testimonials"] });
                    qc.invalidateQueries({ queryKey: ["pub_testimonials"] });
                  }
                },
                children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" })
              }
            )
          ] })
        ] }, t.id))
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editing ? "Edit testimonial" : "New testimonial" }),
        /* @__PURE__ */ jsx(DialogDescription, { children: 'Shown on the homepage. Lower "sort order" numbers appear first.' })
      ] }),
      /* @__PURE__ */ jsxs(
        "form",
        {
          className: "space-y-3",
          onSubmit: async (e) => {
            e.preventDefault();
            if (!form.quote.trim() || !form.name.trim()) {
              toast.error("Name and quote are required");
              return;
            }
            const payload = {
              name: form.name.trim(),
              role: form.role.trim(),
              clinic: form.clinic.trim(),
              location: form.location.trim(),
              quote: form.quote.trim(),
              rating: Math.min(5, Math.max(1, Number(form.rating) || 5)),
              avatar_url: form.avatar_url || null,
              sort_order: Number(form.sort_order) || 0,
              published: !!form.published
            };
            const { error } = editing ? await supabase.from("testimonials").update(payload).eq("id", editing.id) : await supabase.from("testimonials").insert(payload);
            if (error) toast.error(error.message);
            else {
              toast.success("Saved");
              setOpen(false);
              setEditing(null);
              qc.invalidateQueries({ queryKey: ["admin_testimonials"] });
              qc.invalidateQueries({ queryKey: ["pub_testimonials"] });
            }
          },
          children: [
            /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Name" }),
                /* @__PURE__ */ jsx(Input, { value: form.name, onChange: (e) => setForm({ ...form, name: e.target.value }), required: true })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Role / Title" }),
                /* @__PURE__ */ jsx(Input, { value: form.role, onChange: (e) => setForm({ ...form, role: e.target.value }), placeholder: "Principal Dentist" })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Clinic / Hospital" }),
                /* @__PURE__ */ jsx(Input, { value: form.clinic, onChange: (e) => setForm({ ...form, clinic: e.target.value }) })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Location" }),
                /* @__PURE__ */ jsx(Input, { value: form.location, onChange: (e) => setForm({ ...form, location: e.target.value }), placeholder: "Nairobi" })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
                /* @__PURE__ */ jsx(Label, { children: "Quote" }),
                /* @__PURE__ */ jsx(
                  Textarea,
                  {
                    rows: 4,
                    value: form.quote,
                    onChange: (e) => setForm({ ...form, quote: e.target.value }),
                    required: true,
                    placeholder: "What did they say about working with you?"
                  }
                )
              ] }),
              /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(
                ImageUploader,
                {
                  value: form.avatar_url ?? "",
                  onChange: (url) => setForm({ ...form, avatar_url: url }),
                  folder: "testimonials",
                  label: "Avatar (optional)",
                  aspect: "square"
                }
              ) }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Rating (1–5)" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "number",
                    min: 1,
                    max: 5,
                    value: form.rating,
                    onChange: (e) => setForm({ ...form, rating: Number(e.target.value) })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Label, { children: "Sort order" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "number",
                    value: form.sort_order,
                    onChange: (e) => setForm({ ...form, sort_order: Number(e.target.value) })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "col-span-2 flex items-center gap-2 rounded-sm border border-border bg-muted/30 px-3 py-2", children: [
                /* @__PURE__ */ jsx(
                  "input",
                  {
                    id: "testimonial-published",
                    type: "checkbox",
                    checked: form.published,
                    onChange: (e) => setForm({ ...form, published: e.target.checked }),
                    className: "h-4 w-4 accent-primary"
                  }
                ),
                /* @__PURE__ */ jsx(Label, { htmlFor: "testimonial-published", className: "cursor-pointer font-medium", children: "Published (visible on homepage)" })
              ] })
            ] }),
            /* @__PURE__ */ jsxs(DialogFooter, { className: "pt-2", children: [
              /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => {
                setOpen(false);
                setEditing(null);
              }, children: "Cancel" }),
              /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90", children: editing ? "Save changes" : "Create testimonial" })
            ] })
          ]
        }
      )
    ] }) })
  ] });
}
function AdminLogin() {
  const [mode, setMode] = React.useState("signin");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [fullName, setFullName] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  async function submit(e) {
    e.preventDefault();
    setBusy(true);
    try {
      if (mode === "signin") {
        const {
          error
        } = await supabase.auth.signInWithPassword({
          email,
          password
        });
        if (error) throw error;
        toast.success("Welcome back");
      } else {
        const {
          error
        } = await supabase.auth.signUp({
          email,
          password,
          options: {
            emailRedirectTo: window.location.origin + "/admin",
            data: {
              full_name: fullName
            }
          }
        });
        if (error) throw error;
        toast.success("Account created. Check your email to confirm.");
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Authentication failed");
    } finally {
      setBusy(false);
    }
  }
  async function google() {
    const result = await lovable.auth.signInWithOAuth("google", {
      redirect_uri: window.location.origin + "/admin"
    });
    if (result.error) toast.error("Google sign-in failed");
  }
  return /* @__PURE__ */ jsx("div", { className: "container mx-auto max-w-md px-4 py-16", children: /* @__PURE__ */ jsxs("div", { className: "rounded border border-border bg-card p-8 shadow-[var(--shadow-card)]", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-brand", children: [
      /* @__PURE__ */ jsx(ShieldCheck, { className: "h-5 w-5" }),
      /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold uppercase tracking-wider", children: "Staff only" })
    ] }),
    /* @__PURE__ */ jsx("h1", { className: "mt-2 text-2xl font-bold", children: mode === "signin" ? "Admin sign in" : "Create admin account" }),
    /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: "Authorized personnel only." }),
    /* @__PURE__ */ jsx(Button, { onClick: google, variant: "outline", className: "mt-6 w-full", children: "Continue with Google" }),
    /* @__PURE__ */ jsx("div", { className: "my-4 text-center text-xs text-muted-foreground", children: "or with email" }),
    /* @__PURE__ */ jsxs("form", { onSubmit: submit, className: "space-y-4", children: [
      mode === "signup" && /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "name", children: "Full name" }),
        /* @__PURE__ */ jsx(Input, { id: "name", value: fullName, onChange: (e) => setFullName(e.target.value), required: true })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "email", children: "Email" }),
        /* @__PURE__ */ jsx(Input, { id: "email", type: "email", value: email, onChange: (e) => setEmail(e.target.value), required: true })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "password", children: "Password" }),
        /* @__PURE__ */ jsx(Input, { id: "password", type: "password", value: password, onChange: (e) => setPassword(e.target.value), required: true, minLength: 6 })
      ] }),
      /* @__PURE__ */ jsx(Button, { type: "submit", disabled: busy, className: "w-full bg-brand text-brand-foreground hover:bg-brand/90", children: busy ? "Please wait…" : mode === "signin" ? "Sign in" : "Create account" })
    ] }),
    /* @__PURE__ */ jsx("button", { type: "button", className: "mt-4 text-sm text-brand-bright hover:underline", onClick: () => setMode(mode === "signin" ? "signup" : "signin"), children: mode === "signin" ? "Need an account? Sign up" : "Have an account? Sign in" }),
    /* @__PURE__ */ jsx("div", { className: "mt-6 text-xs text-muted-foreground", children: /* @__PURE__ */ jsx(Link, { to: "/", className: "hover:underline", children: "← Back to site" }) })
  ] }) });
}
function AdminPage() {
  const {
    user,
    isAdmin,
    loading,
    signOut,
    refreshRole
  } = useAuth();
  const [section, setSection] = React.useState("overview");
  if (loading) {
    return /* @__PURE__ */ jsx("div", { className: "container mx-auto px-4 py-16 text-sm text-muted-foreground", children: "Loading…" });
  }
  if (!user) {
    return /* @__PURE__ */ jsx(AdminLogin, {});
  }
  if (!isAdmin) {
    return /* @__PURE__ */ jsx("div", { className: "container mx-auto max-w-lg px-4 py-16", children: /* @__PURE__ */ jsxs("div", { className: "rounded border border-border bg-card p-8 text-center", children: [
      /* @__PURE__ */ jsx(ShieldCheck, { className: "mx-auto h-10 w-10 text-brand" }),
      /* @__PURE__ */ jsx("h1", { className: "mt-3 text-xl font-bold", children: "You're signed in, but not an admin yet" }),
      /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: "If this is the first admin for this site, click below to claim admin access. After the first admin is set, new admins must be added by an existing admin from the database." }),
      /* @__PURE__ */ jsx(Button, { className: "mt-5 bg-brand text-brand-foreground hover:bg-brand/90", onClick: async () => {
        const {
          data,
          error
        } = await supabase.rpc("claim_first_admin");
        if (error) return toast.error(error.message);
        if (data) {
          toast.success("You are now admin");
          await refreshRole();
        } else {
          toast.error("An admin already exists. Ask them to grant you access.");
        }
      }, children: "Claim first-admin access" }),
      /* @__PURE__ */ jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: signOut, children: "Sign out" }) })
    ] }) });
  }
  const nav = [{
    id: "overview",
    label: "Overview",
    icon: LayoutDashboard
  }, {
    id: "products",
    label: "Products",
    icon: Package
  }, {
    id: "categories",
    label: "Categories",
    icon: FolderTree
  }, {
    id: "brands",
    label: "Brands",
    icon: Tag
  }, {
    id: "quotes",
    label: "Quote requests",
    icon: Inbox
  }, {
    id: "homepage",
    label: "Homepage",
    icon: Home
  }, {
    id: "blog",
    label: "Blog",
    icon: Newspaper
  }, {
    id: "testimonials",
    label: "Testimonials",
    icon: MessageSquareQuote
  }, {
    id: "settings",
    label: "Site settings",
    icon: Settings
  }];
  const titles = {
    overview: {
      title: "Overview",
      sub: "What's happening across your store."
    },
    products: {
      title: "Products",
      sub: "Add, edit and publish your catalog."
    },
    categories: {
      title: "Categories",
      sub: "Organize your storefront."
    },
    brands: {
      title: "Brands",
      sub: "Manage the brands you carry."
    },
    quotes: {
      title: "Quote requests",
      sub: "Inbox from customers asking for a quote."
    },
    homepage: {
      title: "Homepage",
      sub: "Hero banner, promo strip and featured products."
    },
    blog: {
      title: "Blog",
      sub: "Write, edit and publish articles."
    },
    testimonials: {
      title: "Testimonials",
      sub: "Customer quotes shown on the homepage."
    },
    settings: {
      title: "Site settings",
      sub: "Contact details and social links."
    }
  };
  return /* @__PURE__ */ jsx("div", { className: "min-h-screen bg-muted/30", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto grid min-h-screen w-full max-w-[1440px] grid-cols-1 md:grid-cols-[240px_1fr] md:gap-6", children: [
    /* @__PURE__ */ jsxs("aside", { className: "hidden border-r border-border bg-card md:flex md:flex-col", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-b border-border px-5 py-4", children: [
        /* @__PURE__ */ jsx("div", { className: "flex h-8 w-8 items-center justify-center rounded-sm bg-primary text-primary-foreground", children: /* @__PURE__ */ jsx(ShieldCheck, { className: "h-4 w-4" }) }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold", children: "Admin" }),
          /* @__PURE__ */ jsx("div", { className: "text-[11px] text-muted-foreground", children: "Aquadent Supplies" })
        ] })
      ] }),
      /* @__PURE__ */ jsx("nav", { className: "flex-1 space-y-1 p-3", children: nav.map((n) => {
        const active = section === n.id;
        const Icon = n.icon;
        return /* @__PURE__ */ jsxs("button", { onClick: () => setSection(n.id), className: cn("flex w-full items-center gap-3 rounded-sm px-3 py-2 text-sm font-medium transition-colors", active ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground"), children: [
          /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }),
          n.label
        ] }, n.id);
      }) }),
      /* @__PURE__ */ jsxs("div", { className: "border-t border-border p-3 space-y-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "rounded-sm bg-muted/50 px-3 py-2 text-xs", children: [
          /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground truncate", children: user.email }),
          /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: "Administrator" })
        ] }),
        /* @__PURE__ */ jsxs(Link, { to: "/", className: "flex items-center gap-2 rounded-sm px-3 py-2 text-xs text-muted-foreground hover:bg-muted hover:text-foreground", children: [
          /* @__PURE__ */ jsx(ExternalLink, { className: "h-3.5 w-3.5" }),
          " View public site"
        ] }),
        /* @__PURE__ */ jsxs("button", { onClick: signOut, className: "flex w-full items-center gap-2 rounded-sm px-3 py-2 text-xs text-muted-foreground hover:bg-muted hover:text-foreground", children: [
          /* @__PURE__ */ jsx(LogOut, { className: "h-3.5 w-3.5" }),
          " Sign out"
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("main", { className: "flex flex-col md:pr-6 md:py-6", children: [
      /* @__PURE__ */ jsxs("header", { className: "relative overflow-hidden rounded border border-border bg-card px-6 py-5 shadow-[var(--shadow-card)] md:px-8 md:py-6", children: [
        /* @__PURE__ */ jsx("div", { className: "absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-primary via-primary/60 to-transparent" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx(LayoutDashboard, { className: "h-3.5 w-3.5" }),
              /* @__PURE__ */ jsx("span", { className: "font-medium uppercase tracking-wider", children: "Admin" }),
              /* @__PURE__ */ jsx("span", { className: "text-border", children: "/" }),
              /* @__PURE__ */ jsx("span", { className: "text-foreground font-semibold", children: titles[section].title })
            ] }),
            /* @__PURE__ */ jsx("h1", { className: "mt-2 text-xl font-bold md:text-2xl", children: titles[section].title }),
            /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm text-muted-foreground", children: titles[section].sub })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 shrink-0", children: [
            /* @__PURE__ */ jsxs(Link, { to: "/", className: "hidden items-center gap-1.5 rounded-sm border border-border bg-background px-3 py-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors md:inline-flex", children: [
              /* @__PURE__ */ jsx(ExternalLink, { className: "h-3.5 w-3.5" }),
              "View site"
            ] }),
            /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: signOut, className: "md:hidden", children: /* @__PURE__ */ jsx(LogOut, { className: "h-4 w-4" }) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex gap-2 overflow-x-auto border-b border-border bg-background px-4 py-2 md:hidden", children: nav.map((n) => /* @__PURE__ */ jsx("button", { onClick: () => setSection(n.id), className: cn("whitespace-nowrap rounded-full px-3 py-1.5 text-xs font-medium", section === n.id ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"), children: n.label }, n.id)) }),
      /* @__PURE__ */ jsxs("div", { className: "flex-1 p-4 md:p-0 md:pt-6", children: [
        section === "overview" && /* @__PURE__ */ jsx(Overview, { onJump: setSection }),
        section === "products" && /* @__PURE__ */ jsx(ProductsAdmin, {}),
        section === "categories" && /* @__PURE__ */ jsx(CategoriesAdmin, {}),
        section === "brands" && /* @__PURE__ */ jsx(BrandsAdmin, {}),
        section === "quotes" && /* @__PURE__ */ jsx(QuotesAdmin, {}),
        section === "homepage" && /* @__PURE__ */ jsx(HomepageAdmin, {}),
        section === "blog" && /* @__PURE__ */ jsx(BlogAdmin, {}),
        section === "testimonials" && /* @__PURE__ */ jsx(TestimonialsAdmin, {}),
        section === "settings" && /* @__PURE__ */ jsx(SettingsAdmin, {})
      ] })
    ] })
  ] }) });
}
function Stat({
  label,
  value,
  icon: Icon,
  hint
}) {
  return /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-5", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsx("span", { className: "text-xs font-medium uppercase tracking-wider text-muted-foreground", children: label }),
      /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4 text-muted-foreground" })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "mt-3 text-3xl font-bold tracking-tight", children: value }),
    hint && /* @__PURE__ */ jsx("div", { className: "mt-1 text-xs text-muted-foreground", children: hint })
  ] });
}
function Overview({
  onJump
}) {
  const {
    data: stats
  } = useQuery({
    queryKey: ["admin_stats"],
    queryFn: async () => {
      const [p, pInactive, c, b, qNew, qTotal, recent] = await Promise.all([supabase.from("products").select("id", {
        count: "exact",
        head: true
      }), supabase.from("products").select("id", {
        count: "exact",
        head: true
      }).eq("is_active", false), supabase.from("categories").select("id", {
        count: "exact",
        head: true
      }), supabase.from("brands").select("id", {
        count: "exact",
        head: true
      }), supabase.from("quote_requests").select("id", {
        count: "exact",
        head: true
      }).eq("status", "new"), supabase.from("quote_requests").select("id", {
        count: "exact",
        head: true
      }), supabase.from("quote_requests").select("*").order("created_at", {
        ascending: false
      }).limit(5)]);
      return {
        products: p.count ?? 0,
        hidden: pInactive.count ?? 0,
        categories: c.count ?? 0,
        brands: b.count ?? 0,
        newQuotes: qNew.count ?? 0,
        totalQuotes: qTotal.count ?? 0,
        recent: recent.data ?? []
      };
    }
  });
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-4", children: [
      /* @__PURE__ */ jsx(Stat, { label: "Products", value: stats?.products ?? "—", icon: Package, hint: `${stats?.hidden ?? 0} hidden` }),
      /* @__PURE__ */ jsx(Stat, { label: "Categories", value: stats?.categories ?? "—", icon: FolderTree }),
      /* @__PURE__ */ jsx(Stat, { label: "Brands", value: stats?.brands ?? "—", icon: Tag }),
      /* @__PURE__ */ jsx(Stat, { label: "New quotes", value: stats?.newQuotes ?? "—", icon: Inbox, hint: `${stats?.totalQuotes ?? 0} total` })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 lg:grid-cols-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-5 lg:col-span-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: "Recent quote requests" }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Latest 5 from your inbox" })
          ] }),
          /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => onJump("quotes"), children: "View all" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-4 divide-y divide-border", children: [
          (stats?.recent ?? []).length === 0 && /* @__PURE__ */ jsx("div", { className: "py-8 text-center text-sm text-muted-foreground", children: "No requests yet." }),
          stats?.recent.map((q) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 py-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-medium", children: q.name }),
              /* @__PURE__ */ jsx("div", { className: "truncate text-xs text-muted-foreground", children: q.email || q.phone || "—" })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
              /* @__PURE__ */ jsx(StatusBadge, { status: q.status }),
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: new Date(q.created_at).toLocaleDateString() })
            ] })
          ] }, q.id))
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-5", children: [
        /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: "Quick actions" }),
        /* @__PURE__ */ jsxs("div", { className: "mt-4 space-y-2", children: [
          /* @__PURE__ */ jsxs(Button, { className: "w-full justify-start", variant: "outline", onClick: () => onJump("products"), children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
            " Add product"
          ] }),
          /* @__PURE__ */ jsxs(Button, { className: "w-full justify-start", variant: "outline", onClick: () => onJump("categories"), children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
            " Add category"
          ] }),
          /* @__PURE__ */ jsxs(Button, { className: "w-full justify-start", variant: "outline", onClick: () => onJump("brands"), children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
            " Add brand"
          ] }),
          /* @__PURE__ */ jsxs(Button, { className: "w-full justify-start", variant: "outline", onClick: () => onJump("settings"), children: [
            /* @__PURE__ */ jsx(Settings, { className: "mr-2 h-4 w-4" }),
            " Edit site settings"
          ] })
        ] })
      ] })
    ] })
  ] });
}
function CategoriesAdmin() {
  const qc = useQueryClient();
  const {
    data = []
  } = useQuery({
    queryKey: ["admin_categories"],
    queryFn: async () => {
      const {
        data: data2,
        error
      } = await supabase.from("categories").select("*").order("sort_order").order("name");
      if (error) throw error;
      return data2;
    }
  });
  const [editing, setEditing] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const filtered = data.filter((c) => [c.name, c.slug].some((v) => (v ?? "").toLowerCase().includes(search.toLowerCase())));
  function openAdd() {
    setEditing(null);
    setOpen(true);
  }
  function openEdit(c) {
    setEditing(c);
    setOpen(true);
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(SectionToolbar, { search, setSearch, onAdd: openAdd, count: filtered.length, addLabel: "Add category" }),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-hidden", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Name" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Slug" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Order" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 4, className: "py-10 text-center text-sm text-muted-foreground", children: "No categories yet." }) }),
        filtered.map((c) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            c.image_url ? /* @__PURE__ */ jsx("img", { src: c.image_url, alt: "", className: "h-9 w-9 rounded-md object-cover" }) : /* @__PURE__ */ jsx("div", { className: "flex h-9 w-9 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx(FolderTree, { className: "h-4 w-4 text-muted-foreground" }) }),
            c.name
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-muted-foreground", children: c.slug }),
          /* @__PURE__ */ jsx(TableCell, { children: c.sort_order }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right", children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => openEdit(c), children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: async () => {
              if (!confirm(`Delete "${c.name}"?`)) return;
              const {
                error
              } = await supabase.from("categories").delete().eq("id", c.id);
              if (error) toast.error(error.message);
              else {
                toast.success("Deleted");
                qc.invalidateQueries({
                  queryKey: ["admin_categories"]
                });
              }
            }, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" }) })
          ] })
        ] }, c.id))
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editing ? "Edit category" : "New category" }),
        /* @__PURE__ */ jsx(DialogDescription, { children: "Categories group products on your storefront." })
      ] }),
      /* @__PURE__ */ jsx(CategoryForm, { editing, onDone: () => {
        setOpen(false);
        setEditing(null);
        qc.invalidateQueries({
          queryKey: ["admin_categories"]
        });
      } })
    ] }) })
  ] });
}
function CategoryForm({
  editing,
  onDone
}) {
  const [form, setForm] = React.useState({
    name: "",
    slug: "",
    description: "",
    sort_order: 0,
    image_url: ""
  });
  React.useEffect(() => {
    setForm(editing ? {
      ...editing
    } : {
      name: "",
      slug: "",
      description: "",
      sort_order: 0,
      image_url: ""
    });
  }, [editing]);
  return /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: async (e) => {
    e.preventDefault();
    const payload = {
      name: form.name,
      slug: form.slug,
      description: form.description,
      sort_order: Number(form.sort_order) || 0,
      image_url: form.image_url || null
    };
    const {
      error
    } = editing ? await supabase.from("categories").update(payload).eq("id", editing.id) : await supabase.from("categories").insert(payload);
    if (error) toast.error(error.message);
    else {
      toast.success("Saved");
      onDone();
    }
  }, children: [
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
        /* @__PURE__ */ jsx(Label, { children: "Name" }),
        /* @__PURE__ */ jsx(Input, { value: form.name, onChange: (e) => setForm({
          ...form,
          name: e.target.value
        }), required: true })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { children: "Slug" }),
        /* @__PURE__ */ jsx(Input, { value: form.slug, onChange: (e) => setForm({
          ...form,
          slug: e.target.value
        }), required: true })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { children: "Sort order" }),
        /* @__PURE__ */ jsx(Input, { type: "number", value: form.sort_order, onChange: (e) => setForm({
          ...form,
          sort_order: Number(e.target.value)
        }) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(ImageUploader, { value: form.image_url ?? "", onChange: (url) => setForm({
        ...form,
        image_url: url
      }), folder: "categories", label: "Image", aspect: "wide" }) }),
      /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
        /* @__PURE__ */ jsx(Label, { children: "Description" }),
        /* @__PURE__ */ jsx(Textarea, { value: form.description ?? "", onChange: (e) => setForm({
          ...form,
          description: e.target.value
        }) })
      ] })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { className: "pt-2", children: [
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: onDone, children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90", children: editing ? "Save changes" : "Create category" })
    ] })
  ] });
}
function BrandsAdmin() {
  const qc = useQueryClient();
  const {
    data = []
  } = useQuery({
    queryKey: ["admin_brands"],
    queryFn: async () => {
      const {
        data: data2,
        error
      } = await supabase.from("brands").select("*").order("sort_order").order("name");
      if (error) throw error;
      return data2;
    }
  });
  const [editing, setEditing] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [form, setForm] = React.useState({
    name: "",
    slug: "",
    description: "",
    logo_url: "",
    sort_order: 0
  });
  React.useEffect(() => {
    setForm(editing ? {
      ...editing
    } : {
      name: "",
      slug: "",
      description: "",
      logo_url: "",
      sort_order: 0
    });
  }, [editing]);
  const filtered = data.filter((b) => [b.name, b.slug].some((v) => (v ?? "").toLowerCase().includes(search.toLowerCase())));
  function openAdd() {
    setEditing(null);
    setOpen(true);
  }
  function openEdit(b) {
    setEditing(b);
    setOpen(true);
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(SectionToolbar, { search, setSearch, onAdd: openAdd, count: filtered.length, addLabel: "Add brand" }),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-hidden", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Brand" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Slug" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Order" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 4, className: "py-10 text-center text-sm text-muted-foreground", children: "No brands yet." }) }),
        filtered.map((b) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            b.logo_url ? /* @__PURE__ */ jsx("img", { src: b.logo_url, alt: "", className: "h-9 w-9 rounded-md object-contain bg-muted p-1" }) : /* @__PURE__ */ jsx("div", { className: "flex h-9 w-9 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx(Tag, { className: "h-4 w-4 text-muted-foreground" }) }),
            b.name
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-muted-foreground", children: b.slug }),
          /* @__PURE__ */ jsx(TableCell, { children: b.sort_order }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right", children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => openEdit(b), children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: async () => {
              if (!confirm(`Delete "${b.name}"?`)) return;
              const {
                error
              } = await supabase.from("brands").delete().eq("id", b.id);
              if (error) toast.error(error.message);
              else {
                toast.success("Deleted");
                qc.invalidateQueries({
                  queryKey: ["admin_brands"]
                });
              }
            }, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" }) })
          ] })
        ] }, b.id))
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editing ? "Edit brand" : "New brand" }),
        /* @__PURE__ */ jsx(DialogDescription, { children: "Brands you carry. Shown on the brands page." })
      ] }),
      /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: async (e) => {
        e.preventDefault();
        const payload = {
          name: form.name,
          slug: form.slug,
          description: form.description,
          logo_url: form.logo_url || null,
          sort_order: Number(form.sort_order) || 0
        };
        const {
          error
        } = editing ? await supabase.from("brands").update(payload).eq("id", editing.id) : await supabase.from("brands").insert(payload);
        if (error) toast.error(error.message);
        else {
          toast.success("Saved");
          setOpen(false);
          setEditing(null);
          qc.invalidateQueries({
            queryKey: ["admin_brands"]
          });
        }
      }, children: [
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Name" }),
            /* @__PURE__ */ jsx(Input, { value: form.name, onChange: (e) => setForm({
              ...form,
              name: e.target.value
            }), required: true })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Slug" }),
            /* @__PURE__ */ jsx(Input, { value: form.slug, onChange: (e) => setForm({
              ...form,
              slug: e.target.value
            }), required: true })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Sort order" }),
            /* @__PURE__ */ jsx(Input, { type: "number", value: form.sort_order, onChange: (e) => setForm({
              ...form,
              sort_order: Number(e.target.value)
            }) })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(ImageUploader, { value: form.logo_url ?? "", onChange: (url) => setForm({
            ...form,
            logo_url: url
          }), folder: "brands", label: "Logo", aspect: "square" }) }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Description" }),
            /* @__PURE__ */ jsx(Textarea, { value: form.description ?? "", onChange: (e) => setForm({
              ...form,
              description: e.target.value
            }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs(DialogFooter, { className: "pt-2", children: [
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => {
            setOpen(false);
            setEditing(null);
          }, children: "Cancel" }),
          /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90", children: editing ? "Save changes" : "Create brand" })
        ] })
      ] })
    ] }) })
  ] });
}
function ProductsAdmin() {
  const qc = useQueryClient();
  const {
    data: products = []
  } = useQuery({
    queryKey: ["admin_products"],
    queryFn: async () => {
      const {
        data,
        error
      } = await supabase.from("products").select("*, categories(name), brands(name)").order("created_at", {
        ascending: false
      });
      if (error) throw error;
      return data;
    }
  });
  const {
    data: cats = []
  } = useQuery({
    queryKey: ["cats_list"],
    queryFn: async () => (await supabase.from("categories").select("id,name").order("name")).data ?? []
  });
  const {
    data: brs = []
  } = useQuery({
    queryKey: ["brands_list"],
    queryFn: async () => (await supabase.from("brands").select("id,name").order("name")).data ?? []
  });
  const empty = {
    name: "",
    slug: "",
    sku: "",
    lot: "",
    price_ksh: 0,
    category_id: "",
    brand_id: "",
    image_url: "",
    badge: "",
    short: "",
    description: "",
    features: "",
    is_active: true,
    is_featured: false,
    featured_order: 0
  };
  const [editing, setEditing] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [form, setForm] = React.useState(empty);
  React.useEffect(() => {
    setForm(editing ? {
      ...editing,
      category_id: editing.category_id ?? "",
      brand_id: editing.brand_id ?? "",
      features: (editing.features ?? []).join(", "),
      badge: editing.badge ?? "",
      sku: editing.sku ?? "",
      lot: editing.lot ?? "",
      image_url: editing.image_url ?? "",
      is_featured: !!editing.is_featured,
      featured_order: editing.featured_order ?? 0
    } : empty);
  }, [editing]);
  const filtered = products.filter((p) => [p.name, p.slug, p.sku, p.categories?.name, p.brands?.name].some((v) => (v ?? "").toLowerCase().includes(search.toLowerCase())));
  function openAdd() {
    setEditing(null);
    setOpen(true);
  }
  function openEdit(p) {
    setEditing(p);
    setOpen(true);
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx(SectionToolbar, { search, setSearch, onAdd: openAdd, count: filtered.length, addLabel: "Add product" }),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-x-auto", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Product" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Category" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Brand" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Price" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 6, className: "py-10 text-center text-sm text-muted-foreground", children: "No products match." }) }),
        filtered.map((p) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-medium", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            p.image_url ? /* @__PURE__ */ jsx("img", { src: p.image_url, alt: "", className: "h-10 w-10 rounded-md object-cover" }) : /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx(Package, { className: "h-4 w-4 text-muted-foreground" }) }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("div", { className: "truncate", children: p.name }),
              p.sku && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
                "SKU ",
                p.sku
              ] })
            ] })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-muted-foreground", children: p.categories?.name ?? "—" }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-muted-foreground", children: p.brands?.name ?? "—" }),
          /* @__PURE__ */ jsxs(TableCell, { className: "font-medium", children: [
            "Ksh ",
            Number(p.price_ksh).toLocaleString()
          ] }),
          /* @__PURE__ */ jsxs(TableCell, { children: [
            p.is_active ? /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "border-emerald-500/40 text-emerald-700 dark:text-emerald-300", children: [
              /* @__PURE__ */ jsx(Eye, { className: "mr-1 h-3 w-3" }),
              "Live"
            ] }) : /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "text-muted-foreground", children: [
              /* @__PURE__ */ jsx(EyeOff, { className: "mr-1 h-3 w-3" }),
              "Hidden"
            ] }),
            p.is_featured && /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "ml-1 border-amber-500/40 text-amber-700 dark:text-amber-300", children: [
              /* @__PURE__ */ jsx(Star, { className: "mr-1 h-3 w-3" }),
              "Featured"
            ] })
          ] }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right", children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => openEdit(p), children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: async () => {
              if (!confirm(`Delete "${p.name}"?`)) return;
              const {
                error
              } = await supabase.from("products").delete().eq("id", p.id);
              if (error) toast.error(error.message);
              else {
                toast.success("Deleted");
                qc.invalidateQueries({
                  queryKey: ["admin_products"]
                });
              }
            }, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" }) })
          ] })
        ] }, p.id))
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editing ? "Edit product" : "New product" }),
        /* @__PURE__ */ jsx(DialogDescription, { children: "Fill in product details. Hidden products won't appear publicly." })
      ] }),
      /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: async (e) => {
        e.preventDefault();
        const payload = {
          name: form.name,
          slug: form.slug,
          sku: form.sku || null,
          lot: form.lot || null,
          price_ksh: Number(form.price_ksh) || 0,
          category_id: form.category_id || null,
          brand_id: form.brand_id || null,
          image_url: form.image_url || null,
          badge: form.badge || null,
          short: form.short,
          description: form.description,
          features: String(form.features || "").split(",").map((s) => s.trim()).filter(Boolean),
          is_active: !!form.is_active,
          is_featured: !!form.is_featured,
          featured_order: Number(form.featured_order) || 0
        };
        const {
          error
        } = editing ? await supabase.from("products").update(payload).eq("id", editing.id) : await supabase.from("products").insert(payload);
        if (error) toast.error(error.message);
        else {
          toast.success("Saved");
          setOpen(false);
          setEditing(null);
          qc.invalidateQueries({
            queryKey: ["admin_products"]
          });
        }
      }, children: [
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Name" }),
            /* @__PURE__ */ jsx(Input, { value: form.name, onChange: (e) => setForm({
              ...form,
              name: e.target.value
            }), required: true })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Slug" }),
            /* @__PURE__ */ jsx(Input, { value: form.slug, onChange: (e) => setForm({
              ...form,
              slug: e.target.value
            }), required: true })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Price (Ksh)" }),
            /* @__PURE__ */ jsx(Input, { type: "number", value: form.price_ksh, onChange: (e) => setForm({
              ...form,
              price_ksh: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "SKU" }),
            /* @__PURE__ */ jsx(Input, { value: form.sku, onChange: (e) => setForm({
              ...form,
              sku: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Lot" }),
            /* @__PURE__ */ jsx(Input, { value: form.lot, onChange: (e) => setForm({
              ...form,
              lot: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Badge" }),
            /* @__PURE__ */ jsxs("select", { className: "h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm", value: form.badge, onChange: (e) => setForm({
              ...form,
              badge: e.target.value
            }), children: [
              /* @__PURE__ */ jsx("option", { value: "", children: "None" }),
              /* @__PURE__ */ jsx("option", { children: "New" }),
              /* @__PURE__ */ jsx("option", { children: "Hot" }),
              /* @__PURE__ */ jsx("option", { children: "Sale" })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Category" }),
            /* @__PURE__ */ jsxs("select", { className: "h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm", value: form.category_id, onChange: (e) => setForm({
              ...form,
              category_id: e.target.value
            }), children: [
              /* @__PURE__ */ jsx("option", { value: "", children: "—" }),
              cats.map((c) => /* @__PURE__ */ jsx("option", { value: c.id, children: c.name }, c.id))
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Brand" }),
            /* @__PURE__ */ jsxs("select", { className: "h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm", value: form.brand_id, onChange: (e) => setForm({
              ...form,
              brand_id: e.target.value
            }), children: [
              /* @__PURE__ */ jsx("option", { value: "", children: "—" }),
              brs.map((b) => /* @__PURE__ */ jsx("option", { value: b.id, children: b.name }, b.id))
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsx(ImageUploader, { value: form.image_url, onChange: (url) => setForm({
            ...form,
            image_url: url
          }), folder: "products", label: "Product image", aspect: "square" }) }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Short description" }),
            /* @__PURE__ */ jsx(Input, { value: form.short, onChange: (e) => setForm({
              ...form,
              short: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Full description" }),
            /* @__PURE__ */ jsx(Textarea, { rows: 3, value: form.description, onChange: (e) => setForm({
              ...form,
              description: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Features (comma-separated)" }),
            /* @__PURE__ */ jsx(Input, { value: form.features, onChange: (e) => setForm({
              ...form,
              features: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2 flex items-center gap-2 rounded-sm bg-muted/40 p-3", children: [
            /* @__PURE__ */ jsx("input", { id: "active", type: "checkbox", checked: form.is_active, onChange: (e) => setForm({
              ...form,
              is_active: e.target.checked
            }), className: "h-4 w-4" }),
            /* @__PURE__ */ jsx(Label, { htmlFor: "active", className: "!mt-0 cursor-pointer", children: "Active (visible on site)" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "col-span-2 grid grid-cols-[1fr_auto] items-center gap-3 rounded-sm border border-amber-500/30 bg-amber-500/5 p-3", children: [
            /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
              /* @__PURE__ */ jsx("input", { id: "featured", type: "checkbox", checked: !!form.is_featured, onChange: (e) => setForm({
                ...form,
                is_featured: e.target.checked
              }), className: "h-4 w-4" }),
              /* @__PURE__ */ jsx(Star, { className: "h-4 w-4 text-amber-500" }),
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Show on homepage (Featured)" })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "forder", className: "!mt-0 text-xs whitespace-nowrap", children: "Order" }),
              /* @__PURE__ */ jsx(Input, { id: "forder", type: "number", className: "h-8 w-20", value: form.featured_order ?? 0, onChange: (e) => setForm({
                ...form,
                featured_order: Number(e.target.value)
              }) })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs(DialogFooter, { className: "pt-2", children: [
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => {
            setOpen(false);
            setEditing(null);
          }, children: "Cancel" }),
          /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90", children: editing ? "Save changes" : "Create product" })
        ] })
      ] })
    ] }) })
  ] });
}
function SettingsAdmin() {
  const qc = useQueryClient();
  const {
    data,
    isLoading
  } = useQuery({
    queryKey: ["admin_settings"],
    queryFn: async () => (await supabase.from("site_settings").select("*").eq("id", true).maybeSingle()).data
  });
  const [form, setForm] = React.useState(null);
  React.useEffect(() => {
    if (data) setForm(data);
  }, [data]);
  if (isLoading || !form) return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: "Loading…" });
  const groups = [{
    title: "Business",
    desc: "Used across the site and in metadata.",
    fields: [["name", "Business name"], ["tagline", "Tagline"]]
  }, {
    title: "Contact",
    desc: "How customers reach you.",
    fields: [["phone", "Phone (E.164, e.g. +254...)"], ["phone_display", "Phone (display)"], ["whatsapp", "WhatsApp number (digits only)"], ["email", "Email"], ["address", "Address"]]
  }, {
    title: "Social links",
    desc: "Leave blank to hide an icon on the site.",
    fields: [["instagram", "Instagram URL"], ["facebook", "Facebook URL"], ["linkedin", "LinkedIn URL"], ["tiktok", "TikTok URL"]]
  }];
  return /* @__PURE__ */ jsxs("form", { className: "max-w-3xl space-y-6", onSubmit: async (e) => {
    e.preventDefault();
    const {
      id: _id,
      updated_at: _u,
      ...rest
    } = form;
    const {
      error
    } = await supabase.from("site_settings").update(rest).eq("id", true);
    if (error) toast.error(error.message);
    else {
      toast.success("Settings saved");
      qc.invalidateQueries({
        queryKey: ["site_settings"]
      });
      qc.invalidateQueries({
        queryKey: ["admin_settings"]
      });
    }
  }, children: [
    groups.map((g) => /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-6", children: [
      /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: g.title }),
      /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: g.desc }),
      /* @__PURE__ */ jsx("div", { className: "mt-4 grid gap-3 sm:grid-cols-2", children: g.fields.map(([k, label]) => /* @__PURE__ */ jsxs("div", { className: k === "address" || k === "tagline" ? "sm:col-span-2" : "", children: [
        /* @__PURE__ */ jsx(Label, { children: label }),
        /* @__PURE__ */ jsx(Input, { value: form[k] ?? "", onChange: (e) => setForm({
          ...form,
          [k]: e.target.value
        }) })
      ] }, k)) })
    ] }, g.title)),
    /* @__PURE__ */ jsx("div", { className: "sticky bottom-4 flex justify-end", children: /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground shadow-lg hover:bg-primary/90", children: "Save settings" }) })
  ] });
}
function QuotesAdmin() {
  const qc = useQueryClient();
  const {
    data = []
  } = useQuery({
    queryKey: ["admin_quotes"],
    queryFn: async () => (await supabase.from("quote_requests").select("*").order("created_at", {
      ascending: false
    })).data ?? []
  });
  const [search, setSearch] = React.useState("");
  const [filter, setFilter] = React.useState("all");
  const [viewing, setViewing] = React.useState(null);
  const filtered = data.filter((q) => filter === "all" || q.status === filter).filter((q) => [q.name, q.email, q.phone, q.clinic].some((v) => (v ?? "").toLowerCase().includes(search.toLowerCase())));
  function exportCsv() {
    const rows = filtered.length ? filtered : data;
    if (!rows.length) {
      toast.info("Nothing to export");
      return;
    }
    const esc = (v) => {
      const s = v == null ? "" : String(v);
      return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };
    const header = ["Date", "Name", "Clinic", "Email", "Phone", "Status", "Items", "Message"];
    const lines = [header.join(",")];
    for (const q of rows) {
      const items = Array.isArray(q.items) ? q.items.map((i) => `${i.name ?? i.id} x${i.qty ?? 1}`).join(" | ") : "";
      lines.push([new Date(q.created_at).toISOString(), q.name, q.clinic ?? "", q.email ?? "", q.phone ?? "", q.status, items, q.message ?? ""].map(esc).join(","));
    }
    const blob = new Blob([lines.join("\n")], {
      type: "text/csv;charset=utf-8;"
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `quote-requests-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    toast.success(`Exported ${rows.length} request${rows.length === 1 ? "" : "s"}`);
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-4 flex flex-wrap items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "relative max-w-sm flex-1", children: [
        /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }),
        /* @__PURE__ */ jsx(Input, { value: search, onChange: (e) => setSearch(e.target.value), placeholder: "Search requests…", className: "pl-9" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1 rounded-sm bg-muted p-1", children: ["all", "new", "contacted", "closed"].map((f) => {
          const count = f === "all" ? data.length : data.filter((q) => q.status === f).length;
          return /* @__PURE__ */ jsxs("button", { onClick: () => setFilter(f), className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium capitalize transition-colors", filter === f ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"), children: [
            f,
            /* @__PURE__ */ jsx("span", { className: "rounded-full bg-muted-foreground/15 px-1.5 py-0.5 text-[10px] tabular-nums", children: count })
          ] }, f);
        }) }),
        /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: exportCsv, className: "gap-1.5", children: [
          /* @__PURE__ */ jsx(Download, { className: "h-3.5 w-3.5" }),
          " Export CSV"
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "rounded-sm border border-border bg-card overflow-x-auto", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "When" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Customer" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Contact" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Items" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        filtered.length === 0 && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 6, className: "py-10 text-center text-sm text-muted-foreground", children: "No requests match." }) }),
        filtered.map((q) => {
          const itemCount = Array.isArray(q.items) ? q.items.reduce((s, i) => s + (Number(i.qty) || 1), 0) : 0;
          return /* @__PURE__ */ jsxs(TableRow, { className: "cursor-pointer", onClick: () => setViewing(q), children: [
            /* @__PURE__ */ jsxs(TableCell, { className: "text-xs whitespace-nowrap", children: [
              new Date(q.created_at).toLocaleDateString(),
              /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: new Date(q.created_at).toLocaleTimeString([], {
                hour: "2-digit",
                minute: "2-digit"
              }) })
            ] }),
            /* @__PURE__ */ jsxs(TableCell, { className: "font-medium", children: [
              q.name,
              q.clinic && /* @__PURE__ */ jsx("div", { className: "text-xs font-normal text-muted-foreground", children: q.clinic })
            ] }),
            /* @__PURE__ */ jsxs(TableCell, { className: "text-xs text-muted-foreground", children: [
              q.email && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsx(Mail, { className: "h-3 w-3" }),
                q.email
              ] }),
              q.phone && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsx(Phone, { className: "h-3 w-3" }),
                q.phone
              ] })
            ] }),
            /* @__PURE__ */ jsx(TableCell, { className: "text-xs", children: itemCount > 0 ? `${itemCount} item${itemCount === 1 ? "" : "s"}` : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "Message only" }) }),
            /* @__PURE__ */ jsx(TableCell, { onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxs("select", { className: "h-8 rounded-md border border-input bg-transparent px-2 text-xs", value: q.status, onChange: async (e) => {
              const {
                error
              } = await supabase.from("quote_requests").update({
                status: e.target.value
              }).eq("id", q.id);
              if (error) toast.error(error.message);
              else qc.invalidateQueries({
                queryKey: ["admin_quotes"]
              });
            }, children: [
              /* @__PURE__ */ jsx("option", { value: "new", children: "new" }),
              /* @__PURE__ */ jsx("option", { value: "contacted", children: "contacted" }),
              /* @__PURE__ */ jsx("option", { value: "closed", children: "closed" })
            ] }) }),
            /* @__PURE__ */ jsx(TableCell, { className: "text-right", onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: async () => {
              if (!confirm("Delete this request?")) return;
              const {
                error
              } = await supabase.from("quote_requests").delete().eq("id", q.id);
              if (error) toast.error(error.message);
              else {
                toast.success("Deleted");
                qc.invalidateQueries({
                  queryKey: ["admin_quotes"]
                });
              }
            }, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-destructive" }) }) })
          ] }, q.id);
        })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!viewing, onOpenChange: (o) => !o && setViewing(null), children: /* @__PURE__ */ jsx(DialogContent, { className: "max-w-lg", children: viewing && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: viewing.name }),
        /* @__PURE__ */ jsxs(DialogDescription, { children: [
          "Received ",
          new Date(viewing.created_at).toLocaleString(),
          " · ",
          /* @__PURE__ */ jsx(StatusBadge, { status: viewing.status })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
        viewing.clinic && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "text-xs uppercase tracking-wider text-muted-foreground", children: "Clinic" }),
          /* @__PURE__ */ jsx("div", { children: viewing.clinic })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          viewing.email && /* @__PURE__ */ jsxs("a", { href: `mailto:${viewing.email}`, className: "rounded-sm border border-border p-3 hover:bg-muted/50", children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs uppercase tracking-wider text-muted-foreground", children: "Email" }),
            /* @__PURE__ */ jsx("div", { className: "truncate text-brand-bright", children: viewing.email })
          ] }),
          viewing.phone && /* @__PURE__ */ jsxs("a", { href: `tel:${viewing.phone}`, className: "rounded-sm border border-border p-3 hover:bg-muted/50", children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs uppercase tracking-wider text-muted-foreground", children: "Phone" }),
            /* @__PURE__ */ jsx("div", { className: "truncate text-brand-bright", children: viewing.phone })
          ] })
        ] }),
        Array.isArray(viewing.items) && viewing.items.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "text-xs uppercase tracking-wider text-muted-foreground", children: "Items requested" }),
          /* @__PURE__ */ jsx("ul", { className: "mt-2 divide-y divide-border rounded-sm border border-border", children: viewing.items.map((i, idx) => /* @__PURE__ */ jsxs("li", { className: "flex items-center justify-between px-3 py-2 text-sm", children: [
            /* @__PURE__ */ jsx("span", { children: i.name ?? i.id }),
            /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
              "× ",
              i.qty ?? 1
            ] })
          ] }, idx)) })
        ] }),
        viewing.message && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "text-xs uppercase tracking-wider text-muted-foreground", children: "Message" }),
          /* @__PURE__ */ jsx("div", { className: "mt-1 whitespace-pre-wrap rounded-sm bg-muted/40 p-3 text-sm", children: viewing.message })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setViewing(null), children: "Close" }),
        viewing.email && /* @__PURE__ */ jsx(Button, { asChild: true, className: "bg-primary text-primary-foreground hover:bg-primary/90", children: /* @__PURE__ */ jsx("a", { href: `mailto:${viewing.email}?subject=Re: Your quote request`, children: "Reply by email" }) })
      ] })
    ] }) }) })
  ] });
}
function HomepageAdmin() {
  const qc = useQueryClient();
  const {
    data,
    isLoading
  } = useQuery({
    queryKey: ["admin_settings"],
    queryFn: async () => (await supabase.from("site_settings").select("*").eq("id", true).maybeSingle()).data
  });
  const {
    data: featured = []
  } = useQuery({
    queryKey: ["admin_featured_products"],
    queryFn: async () => (await supabase.from("products").select("id,name,slug,image_url,is_featured,featured_order,is_active").eq("is_featured", true).order("featured_order", {
      ascending: true
    })).data ?? []
  });
  const [form, setForm] = React.useState(null);
  React.useEffect(() => {
    if (data) setForm(data);
  }, [data]);
  if (isLoading || !form) return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: "Loading…" });
  async function save(e) {
    e.preventDefault();
    const payload = {
      hero_eyebrow: form.hero_eyebrow ?? "",
      hero_title: form.hero_title ?? "",
      hero_subtitle: form.hero_subtitle ?? "",
      hero_image_url: form.hero_image_url ?? "",
      hero_cta_primary_label: form.hero_cta_primary_label ?? "",
      hero_cta_primary_href: form.hero_cta_primary_href ?? "",
      hero_cta_secondary_label: form.hero_cta_secondary_label ?? "",
      hero_cta_secondary_href: form.hero_cta_secondary_href ?? "",
      promo_enabled: !!form.promo_enabled,
      promo_text: form.promo_text ?? "",
      promo_label: form.promo_label ?? "",
      promo_href: form.promo_href ?? ""
    };
    const {
      error
    } = await supabase.from("site_settings").update(payload).eq("id", true);
    if (error) toast.error(error.message);
    else {
      toast.success("Homepage saved");
      qc.invalidateQueries({
        queryKey: ["site_settings"]
      });
      qc.invalidateQueries({
        queryKey: ["admin_settings"]
      });
    }
  }
  async function updateFeaturedOrder(id, order) {
    const {
      error
    } = await supabase.from("products").update({
      featured_order: order
    }).eq("id", id);
    if (error) toast.error(error.message);
    else {
      qc.invalidateQueries({
        queryKey: ["admin_featured_products"]
      });
      qc.invalidateQueries({
        queryKey: ["pub_products"]
      });
    }
  }
  async function unfeature(id) {
    const {
      error
    } = await supabase.from("products").update({
      is_featured: false
    }).eq("id", id);
    if (error) toast.error(error.message);
    else {
      toast.success("Removed from homepage");
      qc.invalidateQueries({
        queryKey: ["admin_featured_products"]
      });
      qc.invalidateQueries({
        queryKey: ["admin_products"]
      });
      qc.invalidateQueries({
        queryKey: ["pub_products"]
      });
    }
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("form", { onSubmit: save, className: "space-y-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-6", children: [
        /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: "Hero banner" }),
        /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Top of the homepage. Leave any field blank to fall back to defaults." }),
        /* @__PURE__ */ jsxs("div", { className: "mt-4 grid gap-4 md:grid-cols-2", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Eyebrow (small label above title)" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_eyebrow ?? "", onChange: (e) => setForm({
              ...form,
              hero_eyebrow: e.target.value
            }), placeholder: "Kenya's trusted dental supplier" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Headline" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_title ?? "", onChange: (e) => setForm({
              ...form,
              hero_title: e.target.value
            }), placeholder: "Premium dental supplies, delivered nationwide." })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "md:col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Subheadline" }),
            /* @__PURE__ */ jsx(Textarea, { rows: 2, value: form.hero_subtitle ?? "", onChange: (e) => setForm({
              ...form,
              hero_subtitle: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "md:col-span-2", children: /* @__PURE__ */ jsx(ImageUploader, { value: form.hero_image_url ?? "", onChange: (url) => setForm({
            ...form,
            hero_image_url: url
          }), folder: "hero", label: "Background image", aspect: "wide" }) }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Primary button label" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_cta_primary_label ?? "", onChange: (e) => setForm({
              ...form,
              hero_cta_primary_label: e.target.value
            }), placeholder: "Browse catalog" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Primary button link" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_cta_primary_href ?? "", onChange: (e) => setForm({
              ...form,
              hero_cta_primary_href: e.target.value
            }), placeholder: "/products" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Secondary button label" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_cta_secondary_label ?? "", onChange: (e) => setForm({
              ...form,
              hero_cta_secondary_label: e.target.value
            }), placeholder: "Request a quote" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Secondary button link" }),
            /* @__PURE__ */ jsx(Input, { value: form.hero_cta_secondary_href ?? "", onChange: (e) => setForm({
              ...form,
              hero_cta_secondary_href: e.target.value
            }), placeholder: "/quote" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-6", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: "Promo strip" }),
            /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Thin bar above the hero. Use for announcements, sales or new arrivals." })
          ] }),
          /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
            /* @__PURE__ */ jsx("input", { type: "checkbox", checked: !!form.promo_enabled, onChange: (e) => setForm({
              ...form,
              promo_enabled: e.target.checked
            }), className: "h-4 w-4" }),
            "Enabled"
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-4 grid gap-4 md:grid-cols-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "md:col-span-2", children: [
            /* @__PURE__ */ jsx(Label, { children: "Message" }),
            /* @__PURE__ */ jsx(Input, { value: form.promo_text ?? "", onChange: (e) => setForm({
              ...form,
              promo_text: e.target.value
            }), placeholder: "🚚 Free delivery in Eldoret on orders above Ksh 10,000" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Button label (optional)" }),
            /* @__PURE__ */ jsx(Input, { value: form.promo_label ?? "", onChange: (e) => setForm({
              ...form,
              promo_label: e.target.value
            }), placeholder: "Shop now" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Button link (optional)" }),
            /* @__PURE__ */ jsx(Input, { value: form.promo_href ?? "", onChange: (e) => setForm({
              ...form,
              promo_href: e.target.value
            }), placeholder: "/products" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "sticky bottom-4 flex justify-end", children: /* @__PURE__ */ jsx(Button, { type: "submit", className: "bg-primary text-primary-foreground shadow-lg hover:bg-primary/90", children: "Save homepage" }) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "rounded-sm border border-border bg-card p-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: "Featured products" }),
          /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: 'These appear in the "Featured Products" section on the homepage. Lower order numbers show first. If none are flagged, the 8 newest products are shown automatically.' })
        ] }),
        /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "border-amber-500/40 text-amber-700 dark:text-amber-300", children: [
          /* @__PURE__ */ jsx(Star, { className: "mr-1 h-3 w-3" }),
          featured.length,
          " selected"
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-4 divide-y divide-border", children: [
        featured.length === 0 && /* @__PURE__ */ jsx("div", { className: "py-8 text-center text-sm text-muted-foreground", children: 'No featured products yet. Open any product and turn on "Show on homepage".' }),
        featured.map((p) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 py-3", children: [
          p.image_url ? /* @__PURE__ */ jsx("img", { src: p.image_url, alt: "", className: "h-10 w-10 rounded-md object-cover" }) : /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx(Package, { className: "h-4 w-4 text-muted-foreground" }) }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
            /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-medium", children: p.name }),
            !p.is_active && /* @__PURE__ */ jsx("div", { className: "text-xs text-amber-600 dark:text-amber-400", children: "Hidden — won't show even though featured" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Label, { className: "!mt-0 text-xs", children: "Order" }),
            /* @__PURE__ */ jsx(Input, { type: "number", className: "h-8 w-20", defaultValue: p.featured_order ?? 0, onBlur: (e) => {
              const v = Number(e.target.value) || 0;
              if (v !== p.featured_order) updateFeaturedOrder(p.id, v);
            } }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => unfeature(p.id), title: "Remove from homepage", children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4 text-destructive" }) })
          ] })
        ] }, p.id))
      ] })
    ] })
  ] });
}
export {
  AdminPage as component
};
