import { jsx, jsxs } from "react/jsx-runtime";
import { Link } from "@tanstack/react-router";
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 { c as cn, 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 { cva } from "class-variance-authority";
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 { S as Select, a as SelectTrigger, b as SelectValue, c as SelectContent, d as SelectItem } from "./select-Dn_c42EA.js";
import { T as Tabs, a as TabsList, b as TabsTrigger } from "./tabs-c5KQ8wMi.js";
import { Edit, ExternalLink, Check, X } from "lucide-react";
import { toast } from "sonner";
import { u as useAuth } from "./use-auth-DoD1gvcu.js";
import { s as slugify } from "./slug-ROJCnNRp.js";
import { C as CATEGORIES } from "./router-CEaBCHfX.js";
import "@supabase/supabase-js";
import "@radix-ui/react-slot";
import "clsx";
import "tailwind-merge";
import "@radix-ui/react-label";
import "@radix-ui/react-dialog";
import "@radix-ui/react-alert-dialog";
import "@radix-ui/react-select";
import "@radix-ui/react-tabs";
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 SubmissionsPage() {
  const qc = useQueryClient();
  const {
    user,
    hasRole
  } = useAuth();
  const [filter, setFilter] = useState("all");
  const [editing, setEditing] = useState(null);
  const list = useQuery({
    queryKey: ["admin", "submissions"],
    queryFn: async () => {
      const {
        data,
        error
      } = await supabase.from("citizen_submissions").select("*").order("created_at", {
        ascending: false
      });
      if (error) throw error;
      return data;
    }
  });
  const filtered = (list.data ?? []).filter((s) => filter === "all" || s.status === filter);
  const save = useMutation({
    mutationFn: async () => {
      if (!editing) return;
      const {
        error
      } = await supabase.from("citizen_submissions").update({
        title: editing.title,
        body: editing.body,
        category: editing.category,
        location: editing.location,
        image_url: editing.image_url,
        review_notes: editing.review_notes
      }).eq("id", editing.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Submission updated");
      setEditing(null);
      qc.invalidateQueries({
        queryKey: ["admin", "submissions"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const approve = useMutation({
    mutationFn: async (sub) => {
      const {
        data: art,
        error: artErr
      } = await supabase.from("articles").insert({
        title: sub.title,
        slug: slugify(sub.title) + "-" + sub.id.slice(0, 6),
        dek: sub.body.slice(0, 160),
        category: sub.category ?? "opinion",
        author_name: sub.submitter_name ?? "Citizen Reporter",
        body: sub.body.split(/\n\n+/).filter(Boolean),
        image_url: sub.image_url,
        status: "published",
        published_at: (/* @__PURE__ */ new Date()).toISOString(),
        tags: ["Citizen Journalism", sub.location].filter(Boolean)
      }).select("id").single();
      if (artErr) throw artErr;
      const {
        error
      } = await supabase.from("citizen_submissions").update({
        status: "approved",
        reviewer_id: user?.id,
        published_article_id: art.id
      }).eq("id", sub.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Approved & published");
      qc.invalidateQueries({
        queryKey: ["admin", "submissions"]
      });
      qc.invalidateQueries({
        queryKey: ["admin", "articles"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const reject = useMutation({
    mutationFn: async (sub) => {
      const {
        error
      } = await supabase.from("citizen_submissions").update({
        status: "rejected",
        reviewer_id: user?.id,
        review_notes: sub.review_notes
      }).eq("id", sub.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Rejected");
      qc.invalidateQueries({
        queryKey: ["admin", "submissions"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const del = useMutation({
    mutationFn: async (id) => {
      const {
        error
      } = await supabase.from("citizen_submissions").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Submission deleted");
      qc.invalidateQueries({
        queryKey: ["admin", "submissions"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const counts = {
    all: list.data?.length ?? 0,
    pending: list.data?.filter((s) => s.status === "pending").length ?? 0,
    approved: list.data?.filter((s) => s.status === "approved").length ?? 0,
    rejected: list.data?.filter((s) => s.status === "rejected").length ?? 0
  };
  return /* @__PURE__ */ jsxs(AdminShell, { title: "Citizen Submissions", children: [
    /* @__PURE__ */ jsx(Tabs, { value: filter, onValueChange: (v) => setFilter(v), className: "mb-6", children: /* @__PURE__ */ jsxs(TabsList, { children: [
      /* @__PURE__ */ jsxs(TabsTrigger, { value: "all", children: [
        "All (",
        counts.all,
        ")"
      ] }),
      /* @__PURE__ */ jsxs(TabsTrigger, { value: "pending", children: [
        "Pending (",
        counts.pending,
        ")"
      ] }),
      /* @__PURE__ */ jsxs(TabsTrigger, { value: "approved", children: [
        "Approved (",
        counts.approved,
        ")"
      ] }),
      /* @__PURE__ */ jsxs(TabsTrigger, { value: "rejected", children: [
        "Rejected (",
        counts.rejected,
        ")"
      ] })
    ] }) }),
    !filtered.length && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "No submissions in this view." }),
    /* @__PURE__ */ jsx("div", { className: "grid gap-4", children: filtered.map((s) => /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-start gap-4", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(CardTitle, { className: "font-serif", children: s.title }),
          /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
            s.submitter_name ?? "Anonymous",
            " · ",
            s.location ?? "—",
            " · ",
            new Date(s.created_at).toLocaleString()
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Badge, { variant: s.status === "pending" ? "default" : "secondary", className: "uppercase", children: s.status }),
          /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => setEditing(s), children: /* @__PURE__ */ jsx(Edit, { className: "w-4 h-4" }) }),
          hasRole("admin") && /* @__PURE__ */ jsx(DeleteButton, { onDelete: () => del.mutate(s.id), title: "Delete submission?", description: "This permanently removes the citizen submission." })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxs(CardContent, { children: [
        s.image_url && /* @__PURE__ */ jsx("img", { src: s.image_url, alt: "", className: "w-full max-h-64 object-cover rounded-sm mb-3" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm whitespace-pre-wrap text-foreground/90", children: s.body }),
        s.review_notes && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-3 border-l-2 border-border pl-3", children: [
          "Review notes: ",
          s.review_notes
        ] }),
        s.published_article_id && /* @__PURE__ */ jsxs(Link, { to: "/admin/articles", className: "inline-flex items-center gap-1 text-xs text-brand-accent mt-3 hover:underline", children: [
          /* @__PURE__ */ jsx(ExternalLink, { className: "w-3 h-3" }),
          " View in articles"
        ] }),
        s.status === "pending" && /* @__PURE__ */ jsxs("div", { className: "flex gap-2 mt-4", children: [
          /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => approve.mutate(s), disabled: approve.isPending, children: [
            /* @__PURE__ */ jsx(Check, { className: "w-4 h-4 mr-1" }),
            " Approve & Publish"
          ] }),
          /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: () => reject.mutate(s), disabled: reject.isPending, children: [
            /* @__PURE__ */ jsx(X, { className: "w-4 h-4 mr-1" }),
            " Reject"
          ] })
        ] })
      ] })
    ] }, s.id)) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!editing, onOpenChange: (o) => !o && setEditing(null), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: "Edit submission" }) }),
      editing && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Title" }),
          /* @__PURE__ */ jsx(Input, { value: editing.title, onChange: (e) => setEditing({
            ...editing,
            title: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Body" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 8, value: editing.body, onChange: (e) => setEditing({
            ...editing,
            body: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Category" }),
            /* @__PURE__ */ jsxs(Select, { value: editing.category ?? "opinion", onValueChange: (v) => setEditing({
              ...editing,
              category: v
            }), children: [
              /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsx(SelectContent, { children: CATEGORIES.map((c) => /* @__PURE__ */ jsx(SelectItem, { value: c.slug, children: c.name }, c.slug)) })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Location" }),
            /* @__PURE__ */ jsx(Input, { value: editing.location ?? "", onChange: (e) => setEditing({
              ...editing,
              location: e.target.value
            }) })
          ] })
        ] }),
        /* @__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: "Review notes (internal)" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 2, value: editing.review_notes ?? "", onChange: (e) => setEditing({
            ...editing,
            review_notes: e.target.value
          }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setEditing(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { onClick: () => save.mutate(), disabled: save.isPending, children: "Save changes" })
      ] })
    ] }) })
  ] });
}
export {
  SubmissionsPage as component
};
