import { jsxs, jsx } from "react/jsx-runtime";
import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
import { useState, useRef } from "react";
import { s as supabase } from "./client-CJCZGN4z.js";
import { A as AdminShell } from "./AdminShell-fo83oaxY.js";
import { B as Button } from "./button-BXrfXN_b.js";
import { I as Input, L as Label } from "./label-BsuFFEVs.js";
import { T as Textarea } from "./textarea-BBisE2jS.js";
import { S as Select, a as SelectTrigger, b as SelectValue, c as SelectContent, d as SelectItem } from "./select-Dn_c42EA.js";
import { S as Switch } from "./switch-DDHih_sy.js";
import { D as Dialog, a as DialogContent, b as DialogHeader, c as DialogTitle, d as DialogFooter } from "./alert-dialog-Cbc2KPWf.js";
import { T as Table, a as TableHeader, b as TableRow, c as TableHead, d as TableBody, e as TableCell } from "./table-K6UF5XG9.js";
import { Loader2, Upload, X, Plus, ExternalLink, Edit } from "lucide-react";
import { toast } from "sonner";
import { C as CATEGORIES } from "./router-CEaBCHfX.js";
import { s as slugify } from "./slug-ROJCnNRp.js";
import { u as useAuth } from "./use-auth-DoD1gvcu.js";
import { D as DeleteButton } from "./DeleteButton-D7V3t-jE.js";
import { Link } from "@tanstack/react-router";
import "@supabase/supabase-js";
import "@radix-ui/react-slot";
import "class-variance-authority";
import "clsx";
import "tailwind-merge";
import "@radix-ui/react-label";
import "@radix-ui/react-select";
import "@radix-ui/react-switch";
import "@radix-ui/react-dialog";
import "@radix-ui/react-alert-dialog";
function ImageUpload({
  value,
  onChange,
  userId
}) {
  const [busy, setBusy] = useState(false);
  const inputRef = useRef(null);
  async function handleFile(file) {
    if (file.size > 8 * 1024 * 1024) {
      toast.error("Image must be under 8 MB");
      return;
    }
    if (!file.type.startsWith("image/")) {
      toast.error("Only image files are allowed");
      return;
    }
    setBusy(true);
    try {
      const ext = file.name.split(".").pop()?.toLowerCase() || "jpg";
      const path = `${userId ?? "anon"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
      const { error: upErr } = await supabase.storage.from("article-media").upload(path, file, { contentType: file.type, upsert: false });
      if (upErr) throw upErr;
      const { data: signed, error: signErr } = await supabase.storage.from("article-media").createSignedUrl(path, 60 * 60 * 24 * 365 * 10);
      if (signErr) throw signErr;
      onChange(signed.signedUrl);
      toast.success("Image uploaded");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          value,
          onChange: (e) => onChange(e.target.value),
          placeholder: "https://... or upload an image"
        }
      ),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          disabled: busy,
          onClick: () => inputRef.current?.click(),
          children: busy ? /* @__PURE__ */ jsx(Loader2, { className: "w-4 h-4 animate-spin" }) : /* @__PURE__ */ jsx(Upload, { className: "w-4 h-4" })
        }
      ),
      value && /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "icon", onClick: () => onChange(""), children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" }) })
    ] }),
    /* @__PURE__ */ jsx(
      "input",
      {
        ref: inputRef,
        type: "file",
        accept: "image/*",
        className: "hidden",
        onChange: (e) => {
          const f = e.target.files?.[0];
          if (f) handleFile(f);
        }
      }
    ),
    value && /* @__PURE__ */ jsx(
      "img",
      {
        src: value,
        alt: "Preview",
        className: "w-full max-h-48 object-cover rounded-sm border border-border"
      }
    )
  ] });
}
const empty = {
  title: "",
  dek: "",
  category: "politics",
  body: [],
  tags: [],
  status: "draft",
  is_breaking: false,
  is_featured: false,
  read_minutes: 3,
  image_url: "",
  image_alt: "",
  ai_summary: ""
};
function ArticlesPage() {
  const qc = useQueryClient();
  const {
    user
  } = useAuth();
  const [editing, setEditing] = useState(null);
  const [bodyText, setBodyText] = useState("");
  const [tagsText, setTagsText] = useState("");
  const list = useQuery({
    queryKey: ["admin", "articles"],
    queryFn: async () => {
      const {
        data,
        error
      } = await supabase.from("articles").select("id, slug, title, category, status, updated_at, author_name, is_breaking, is_featured, published_at").order("updated_at", {
        ascending: false
      });
      if (error) throw error;
      return data;
    }
  });
  function openNew() {
    setEditing({
      ...empty,
      author_name: user?.email?.split("@")[0]
    });
    setBodyText("");
    setTagsText("");
  }
  async function openEdit(id) {
    const {
      data,
      error
    } = await supabase.from("articles").select("*").eq("id", id).single();
    if (error) return toast.error(error.message);
    setEditing(data);
    setBodyText((data.body ?? []).join("\n\n"));
    setTagsText((data.tags ?? []).join(", "));
  }
  const save = useMutation({
    mutationFn: async () => {
      if (!editing) return;
      const payload = {
        title: editing.title,
        slug: editing.slug || slugify(editing.title),
        dek: editing.dek,
        category: editing.category,
        author_id: user?.id,
        author_name: editing.author_name,
        body: bodyText.split(/\n\n+/).map((p) => p.trim()).filter(Boolean),
        tags: tagsText.split(",").map((t) => t.trim()).filter(Boolean),
        image_url: editing.image_url || null,
        image_alt: editing.image_alt || null,
        ai_summary: editing.ai_summary || null,
        status: editing.status,
        is_breaking: !!editing.is_breaking,
        is_featured: !!editing.is_featured,
        read_minutes: Number(editing.read_minutes) || 3,
        published_at: editing.status === "published" ? editing.published_at ?? (/* @__PURE__ */ new Date()).toISOString() : null
      };
      if (editing.id) {
        const {
          error
        } = await supabase.from("articles").update(payload).eq("id", editing.id);
        if (error) throw error;
      } else {
        const {
          error
        } = await supabase.from("articles").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      toast.success("Article saved");
      setEditing(null);
      qc.invalidateQueries({
        queryKey: ["admin", "articles"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const del = useMutation({
    mutationFn: async (id) => {
      const {
        error
      } = await supabase.from("articles").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Deleted");
      qc.invalidateQueries({
        queryKey: ["admin", "articles"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  return /* @__PURE__ */ jsxs(AdminShell, { title: "Articles", 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,
        " articles total"
      ] }),
      /* @__PURE__ */ jsxs(Button, { onClick: openNew, children: [
        /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
        " New Article"
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "border rounded-sm bg-surface", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "Title" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Category" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Status" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Flags" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Updated" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        list.data?.map((a) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { className: "font-bold max-w-sm truncate", children: a.title }),
          /* @__PURE__ */ jsx(TableCell, { className: "capitalize text-xs", children: a.category }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx("span", { className: `text-[10px] font-black uppercase px-2 py-0.5 rounded-sm ${a.status === "published" ? "bg-brand-accent/10 text-brand-accent" : "bg-muted"}`, children: a.status }) }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-xs", children: [
            a.is_breaking && /* @__PURE__ */ jsx("span", { className: "bg-brand text-primary-foreground px-1.5 py-0.5 rounded-sm mr-1", children: "BREAK" }),
            a.is_featured && /* @__PURE__ */ jsx("span", { className: "bg-secondary px-1.5 py-0.5 rounded-sm", children: "FEAT" })
          ] }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-xs text-muted-foreground", children: new Date(a.updated_at).toLocaleDateString() }),
          /* @__PURE__ */ jsxs(TableCell, { className: "text-right space-x-1", children: [
            a.status === "published" && /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", asChild: true, children: /* @__PURE__ */ jsx(Link, { to: "/article/$slug", params: {
              slug: a.slug
            }, target: "_blank", children: /* @__PURE__ */ jsx(ExternalLink, { className: "w-4 h-4" }) }) }),
            /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => openEdit(a.id), children: /* @__PURE__ */ jsx(Edit, { className: "w-4 h-4" }) }),
            /* @__PURE__ */ jsx(DeleteButton, { onDelete: () => del.mutate(a.id), title: "Delete article?", description: `Permanently remove "${a.title}".` })
          ] })
        ] }, a.id)),
        !list.data?.length && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 6, className: "text-center text-muted-foreground py-12", children: "No articles yet" }) })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!editing, onOpenChange: (o) => !o && setEditing(null), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-3xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: editing?.id ? "Edit article" : "New article" }) }),
      editing && /* @__PURE__ */ jsxs("div", { className: "space-y-4", 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", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Slug (auto if blank)" }),
            /* @__PURE__ */ jsx(Input, { value: editing.slug ?? "", onChange: (e) => setEditing({
              ...editing,
              slug: e.target.value
            }), placeholder: slugify(editing.title ?? "") })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Category" }),
            /* @__PURE__ */ jsxs(Select, { value: editing.category, 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: "Dek (subtitle)" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 2, value: editing.dek ?? "", onChange: (e) => setEditing({
            ...editing,
            dek: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Body (paragraphs separated by blank lines)" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 10, value: bodyText, onChange: (e) => setBodyText(e.target.value) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "AI summary" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 2, value: editing.ai_summary ?? "", onChange: (e) => setEditing({
            ...editing,
            ai_summary: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Image" }),
            /* @__PURE__ */ jsx(ImageUpload, { value: editing.image_url ?? "", onChange: (url) => setEditing({
              ...editing,
              image_url: url
            }), userId: user?.id })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Image alt text" }),
            /* @__PURE__ */ jsx(Input, { value: editing.image_alt ?? "", onChange: (e) => setEditing({
              ...editing,
              image_alt: e.target.value
            }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Author name" }),
            /* @__PURE__ */ jsx(Input, { value: editing.author_name ?? "", onChange: (e) => setEditing({
              ...editing,
              author_name: e.target.value
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Read minutes" }),
            /* @__PURE__ */ jsx(Input, { type: "number", value: editing.read_minutes ?? 3, onChange: (e) => setEditing({
              ...editing,
              read_minutes: Number(e.target.value)
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { children: "Status" }),
            /* @__PURE__ */ jsxs(Select, { value: editing.status, onValueChange: (v) => setEditing({
              ...editing,
              status: v
            }), children: [
              /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "draft", children: "Draft" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "published", children: "Published" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "archived", children: "Archived" })
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Tags (comma separated)" }),
          /* @__PURE__ */ jsx(Input, { value: tagsText, onChange: (e) => setTagsText(e.target.value) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-6", children: [
          /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
            /* @__PURE__ */ jsx(Switch, { checked: !!editing.is_breaking, onCheckedChange: (c) => setEditing({
              ...editing,
              is_breaking: c
            }) }),
            " Breaking"
          ] }),
          /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
            /* @__PURE__ */ jsx(Switch, { checked: !!editing.is_featured, onCheckedChange: (c) => setEditing({
              ...editing,
              is_featured: c
            }) }),
            " Featured"
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setEditing(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { onClick: () => save.mutate(), disabled: save.isPending || !editing?.title, children: "Save" })
      ] })
    ] }) })
  ] });
}
export {
  ArticlesPage as component
};
