import { jsxs, jsx } from "react/jsx-runtime";
import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { s as supabase } from "./client-CJCZGN4z.js";
import { A as AdminShell } from "./AdminShell-fo83oaxY.js";
import { D as DeleteButton } from "./DeleteButton-D7V3t-jE.js";
import { B as Button } from "./button-BXrfXN_b.js";
import { L as Label, I as Input } from "./label-BsuFFEVs.js";
import { T as Textarea } from "./textarea-BBisE2jS.js";
import { S as Switch } from "./switch-DDHih_sy.js";
import { S as Select, a as SelectTrigger, b as SelectValue, c as SelectContent, d as SelectItem } from "./select-Dn_c42EA.js";
import { C as Card, a as CardHeader, b as CardTitle, c as CardContent } from "./card-DU714E9E.js";
import { D as Dialog, a as DialogContent, b as DialogHeader, c as DialogTitle, d as DialogFooter } from "./alert-dialog-Cbc2KPWf.js";
import { Plus, Edit } from "lucide-react";
import { toast } from "sonner";
import "@supabase/supabase-js";
import "@tanstack/react-router";
import "./use-auth-DoD1gvcu.js";
import "@radix-ui/react-slot";
import "class-variance-authority";
import "clsx";
import "tailwind-merge";
import "@radix-ui/react-label";
import "@radix-ui/react-switch";
import "@radix-ui/react-select";
import "@radix-ui/react-dialog";
import "@radix-ui/react-alert-dialog";
const PLACEMENTS = ["homepage_hero", "homepage_sidebar", "article_top", "article_bottom", "category_top"];
function AdsPage() {
  const qc = useQueryClient();
  const [editing, setEditing] = useState(null);
  const list = useQuery({
    queryKey: ["admin", "ads"],
    queryFn: async () => {
      const {
        data,
        error
      } = await supabase.from("ad_slots").select("*").order("created_at", {
        ascending: false
      });
      if (error) throw error;
      return data;
    }
  });
  const save = useMutation({
    mutationFn: async () => {
      if (!editing?.name?.trim()) throw new Error("Name is required");
      const payload = {
        name: editing.name.trim(),
        placement: editing.placement,
        image_url: editing.image_url || null,
        target_url: editing.target_url || null,
        html: editing.html || null,
        active: !!editing.active,
        starts_at: editing.starts_at || null,
        ends_at: editing.ends_at || null
      };
      if (editing.id) {
        const {
          error
        } = await supabase.from("ad_slots").update(payload).eq("id", editing.id);
        if (error) throw error;
      } else {
        const {
          error
        } = await supabase.from("ad_slots").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      toast.success(editing?.id ? "Ad updated" : "Ad created");
      setEditing(null);
      qc.invalidateQueries({
        queryKey: ["admin", "ads"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const del = useMutation({
    mutationFn: async (id) => {
      const {
        error
      } = await supabase.from("ad_slots").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Ad deleted");
      qc.invalidateQueries({
        queryKey: ["admin", "ads"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  return /* @__PURE__ */ jsxs(AdminShell, { title: "Ad Slots", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center mb-4", children: [
      /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
        list.data?.length ?? 0,
        " ad slots"
      ] }),
      /* @__PURE__ */ jsxs(Button, { onClick: () => setEditing({
        name: "",
        placement: "homepage_sidebar",
        active: true
      }), children: [
        /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
        " New Ad"
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-3", children: [
      list.data?.map((a) => /* @__PURE__ */ jsxs(Card, { children: [
        /* @__PURE__ */ jsxs(CardHeader, { className: "flex flex-row items-center justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(CardTitle, { className: "text-base", children: a.name }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
              a.placement,
              " · ",
              a.impressions,
              " imp · ",
              a.clicks,
              " clicks"
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx("span", { className: `text-[10px] uppercase font-black px-2 py-0.5 rounded-sm ${a.active ? "bg-brand-accent/10 text-brand-accent" : "bg-muted"}`, children: a.active ? "ACTIVE" : "OFF" }),
            /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", onClick: () => setEditing(a), children: /* @__PURE__ */ jsx(Edit, { className: "w-4 h-4" }) }),
            /* @__PURE__ */ jsx(DeleteButton, { onDelete: () => del.mutate(a.id), title: "Delete ad slot?", description: `Remove "${a.name}" permanently.` })
          ] })
        ] }),
        a.image_url && /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx("img", { src: a.image_url, alt: "", className: "max-h-32 rounded-sm border border-border" }) })
      ] }, a.id)),
      !list.data?.length && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "No ad slots yet." })
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open: !!editing, onOpenChange: (o) => !o && setEditing(null), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: editing?.id ? "Edit ad" : "New ad" }) }),
      editing && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Name" }),
          /* @__PURE__ */ jsx(Input, { value: editing.name ?? "", onChange: (e) => setEditing({
            ...editing,
            name: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Placement" }),
          /* @__PURE__ */ jsxs(Select, { value: editing.placement, onValueChange: (v) => setEditing({
            ...editing,
            placement: v
          }), children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
            /* @__PURE__ */ jsx(SelectContent, { children: PLACEMENTS.map((p) => /* @__PURE__ */ jsx(SelectItem, { value: p, children: p }, p)) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Image URL" }),
          /* @__PURE__ */ jsx(Input, { value: editing.image_url ?? "", onChange: (e) => setEditing({
            ...editing,
            image_url: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Target URL" }),
          /* @__PURE__ */ jsx(Input, { value: editing.target_url ?? "", onChange: (e) => setEditing({
            ...editing,
            target_url: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "HTML embed (optional)" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 3, value: editing.html ?? "", onChange: (e) => setEditing({
            ...editing,
            html: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Starts at" }),
            /* @__PURE__ */ jsx(Input, { type: "datetime-local", value: editing.starts_at ? editing.starts_at.slice(0, 16) : "", onChange: (e) => setEditing({
              ...editing,
              starts_at: e.target.value ? new Date(e.target.value).toISOString() : null
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Ends at" }),
            /* @__PURE__ */ jsx(Input, { type: "datetime-local", value: editing.ends_at ? editing.ends_at.slice(0, 16) : "", onChange: (e) => setEditing({
              ...editing,
              ends_at: e.target.value ? new Date(e.target.value).toISOString() : null
            }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
          /* @__PURE__ */ jsx(Switch, { checked: !!editing.active, onCheckedChange: (c) => setEditing({
            ...editing,
            active: c
          }) }),
          " Active"
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setEditing(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { onClick: () => save.mutate(), disabled: save.isPending || !editing?.name?.trim(), children: "Save" })
      ] })
    ] }) })
  ] });
}
export {
  AdsPage as component
};
