'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from 'react';
import { ArrowLeft, Check, Copy, Sparkles } from 'lucide-react';
import { toast } from 'sonner';
import { resolvePostTypeIcon } from '../../components/posts/icons.js';
import { paletteFor } from '../../components/posts/badges.js';
import { POST_TYPE_PRESETS } from './post-type-presets.js';
/**
 * /posts/types/new — Quick Post Type gallery + snippet generator.
 *
 * Two ways to start:
 *   1. Pick a Quick Post Type preset (Blog) — pre-fills the form and
 *      tailored extra fields.
 *   2. Fill the form from scratch.
 *
 * Either way the page emits a paste-ready `actuate.config.ts` snippet.
 *
 * Why this isn't a runtime form-driven CRUD:
 *   Collections in ActuateCMS are file-defined in `actuate.config.ts`.
 *   Writing to that file at runtime would require either a parallel
 *   DB-only post-type model that duplicates the Collection concept, or
 *   mutating a source file on disk — which breaks Vercel's read-only
 *   serverless filesystem and any immutable deploy model. So we
 *   generate the snippet and the developer commits + redeploys. Same
 *   model Sanity, Keystone, and Payload use for code-defined schemas.
 */
const SLUG_RE = /^[a-z][a-z0-9-]*$/;
const ICON_OPTIONS = [
    { value: 'file-text', label: 'Document' },
    { value: 'briefcase', label: 'Briefcase' },
    { value: 'newspaper', label: 'Newspaper' },
    { value: 'book', label: 'Book' },
    { value: 'folder', label: 'Folder' },
    { value: 'layers', label: 'Layers' },
    { value: 'image', label: 'Image' },
    { value: 'calendar', label: 'Calendar' },
    { value: 'users', label: 'People' },
    { value: 'help', label: 'Help' },
];
const BLANK_DRAFT = {
    slug: '',
    singular: '',
    plural: '',
    color: 'purple',
    icon: 'file-text',
    description: '',
    extraFields: [],
};
export function NewPostTypeInstructions({ onNavigate }) {
    const [draft, setDraft] = useState(BLANK_DRAFT);
    const [activePreset, setActivePreset] = useState(null);
    const [copied, setCopied] = useState(false);
    const snippet = useMemo(() => renderSnippet(draft), [draft]);
    const slugValid = SLUG_RE.test(draft.slug);
    const applyPreset = (preset) => {
        setActivePreset(preset.key);
        setDraft({
            slug: preset.slug,
            singular: preset.singular,
            plural: preset.plural,
            color: preset.color,
            icon: preset.icon,
            description: preset.description,
            extraFields: preset.extraFields,
        });
    };
    // Manual edits clear the active-preset highlight but keep any
    // preset-seeded extra fields (the user may still want them).
    const patchDraft = (patch) => {
        setActivePreset(null);
        setDraft((d) => ({ ...d, ...patch }));
    };
    const copy = async () => {
        try {
            await navigator.clipboard.writeText(snippet);
            setCopied(true);
            toast.success('Snippet copied to clipboard');
            setTimeout(() => setCopied(false), 1800);
        }
        catch {
            toast.error('Copy failed — select the snippet manually');
        }
    };
    return (_jsxs("div", { className: "mx-auto flex h-full max-w-3xl flex-col gap-6 p-4 sm:p-6", children: [_jsxs("button", { type: "button", onClick: () => onNavigate('/posts/types'), className: "text-muted-foreground hover:text-foreground inline-flex w-fit items-center gap-1.5 text-sm transition-colors", children: [_jsx(ArrowLeft, { className: "h-3.5 w-3.5", "aria-hidden": true }), "Back to Post Types"] }), _jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("h1", { className: "text-foreground text-xl font-medium tracking-tight sm:text-2xl", children: "Add a Post Type" }), _jsxs("p", { className: "text-muted-foreground text-sm", children: ["Post Types are content models defined in", ' ', _jsx("code", { className: "font-mono", children: "actuate.config.ts" }), ". Start from a quick template or fill in the details below, then paste the generated snippet into your config and redeploy."] })] }), _jsxs("section", { "aria-labelledby": "quick-types-heading", className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Sparkles, { className: "text-muted-foreground h-3.5 w-3.5", "aria-hidden": true }), _jsx("h2", { id: "quick-types-heading", className: "text-foreground text-sm font-medium", children: "Quick start" })] }), _jsx("div", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5", children: POST_TYPE_PRESETS.map((preset) => {
                            const palette = paletteFor(preset.color);
                            const Icon = resolvePostTypeIcon(preset.icon);
                            const selected = activePreset === preset.key;
                            return (_jsxs("button", { type: "button", onClick: () => applyPreset(preset), "aria-pressed": selected, className: `focus-visible:ring-ring flex flex-col items-start gap-2 rounded-xl border p-3 text-left shadow-sm transition-colors focus:outline-none focus-visible:ring-2 ${selected
                                    ? 'border-primary bg-primary/5'
                                    : 'border-border bg-card hover:border-primary/40 hover:bg-accent'}`, children: [_jsx("span", { className: `inline-flex h-8 w-8 items-center justify-center rounded-lg ${palette.bg} ${palette.text}`, children: _jsx(Icon, { className: "h-4 w-4", "aria-hidden": true }) }), _jsx("span", { className: "text-foreground text-sm leading-tight font-medium", children: preset.label })] }, preset.key));
                        }) })] }), _jsxs("div", { className: "bg-card border-border grid grid-cols-1 gap-4 rounded-xl border p-5 shadow-sm sm:grid-cols-2", children: [_jsx(Field, { label: "Slug", htmlFor: "pt-slug", error: draft.slug && !slugValid ? 'lowercase letters, numbers, and dashes only' : null, children: _jsx("input", { id: "pt-slug", value: draft.slug, onChange: (e) => patchDraft({ slug: e.target.value.trim() }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", placeholder: "reviews" }) }), _jsx(Field, { label: "Singular label", htmlFor: "pt-singular", children: _jsx("input", { id: "pt-singular", value: draft.singular, onChange: (e) => patchDraft({ singular: e.target.value }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", placeholder: "Review" }) }), _jsx(Field, { label: "Plural label", htmlFor: "pt-plural", children: _jsx("input", { id: "pt-plural", value: draft.plural, onChange: (e) => patchDraft({ plural: e.target.value }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", placeholder: "Reviews" }) }), _jsx(Field, { label: "Description", htmlFor: "pt-desc", children: _jsx("input", { id: "pt-desc", value: draft.description, onChange: (e) => patchDraft({ description: e.target.value }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", placeholder: "Product reviews and editorial pieces." }) }), _jsx(Field, { label: "Accent color", htmlFor: "pt-color", children: _jsxs("select", { id: "pt-color", value: draft.color, onChange: (e) => patchDraft({ color: e.target.value }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "purple", children: "Purple" }), _jsx("option", { value: "green", children: "Green" }), _jsx("option", { value: "orange", children: "Orange" }), _jsx("option", { value: "blue", children: "Blue" }), _jsx("option", { value: "red", children: "Red" }), _jsx("option", { value: "pink", children: "Pink" })] }) }), _jsx(Field, { label: "Icon", htmlFor: "pt-icon", children: _jsx("select", { id: "pt-icon", value: draft.icon, onChange: (e) => patchDraft({ icon: e.target.value }), className: "border-border bg-background text-foreground focus:border-primary focus:ring-primary/30 w-full rounded-lg border px-3 py-1.5 text-sm focus:ring-2 focus:outline-none", children: ICON_OPTIONS.map((o) => (_jsx("option", { value: o.value, children: o.label }, o.value))) }) })] }), _jsxs("div", { children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsxs("h2", { className: "text-foreground text-sm font-medium", children: ["Add to ", _jsx("code", { className: "font-mono", children: "actuate.config.ts" })] }), _jsxs("button", { type: "button", onClick: copy, disabled: !slugValid, className: "border-border bg-background text-foreground hover:bg-accent inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40", children: [copied ? (_jsx(Check, { className: "h-3.5 w-3.5", "aria-hidden": true })) : (_jsx(Copy, { className: "h-3.5 w-3.5", "aria-hidden": true })), copied ? 'Copied' : 'Copy snippet'] })] }), _jsx("pre", { className: "border-border bg-muted text-foreground overflow-x-auto rounded-lg border p-4 text-xs leading-relaxed", children: _jsx("code", { children: snippet }) }), _jsx("p", { className: "text-muted-foreground mt-3 text-xs", children: "After adding the snippet and redeploying, the new type will appear in the Posts area tabs and on this Post Types page automatically." })] })] }));
}
function Field({ label, htmlFor, error, children, }) {
    return (_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("label", { htmlFor: htmlFor, className: "text-foreground text-sm font-medium", children: label }), children, error ? _jsx("span", { className: "text-destructive text-xs", children: error }) : null] }));
}
export function renderSnippet(draft) {
    const safeSlug = draft.slug || 'new-type';
    const extraFieldsBlock = draft.extraFields.length > 0
        ? '\n      // type-specific fields\n' +
            draft.extraFields.map((line) => `      ${line}`).join('\n') +
            '\n'
        : '';
    return `// Add this entry to the \`collections\` map in actuate.config.ts:
collections: {
  // …existing collections,
  '${safeSlug}': {
    slug: '${safeSlug}',
    labels: {
      singular: '${escapeString(draft.singular || 'Entry')}',
      plural: '${escapeString(draft.plural || 'Entries')}',
    },
    type: 'post',
    urlPrefix: '${safeSlug}',
    admin: {
      group: 'Posts',
      icon: '${draft.icon}',
      color: '${draft.color}',
      description: '${escapeString(draft.description)}',
    },
    fields: {
      title: { type: 'text', label: 'Title', required: true },
      slug: { type: 'slug', label: 'Slug', from: 'title' },
      excerpt: { type: 'text', label: 'Excerpt' },
      featuredImage: { type: 'media', label: 'Featured Image' },
      body: { type: 'richText', label: 'Body' },
      status: {
        type: 'select',
        label: 'Status',
        options: [
          { label: 'Draft', value: 'draft' },
          { label: 'Published', value: 'published' },
          { label: 'Scheduled', value: 'scheduled' },
        ],
      },
      publishDate: { type: 'date', label: 'Publish Date', includeTime: true },
      metaTitle: { type: 'text', label: 'SEO Title' },
      metaDescription: { type: 'text', label: 'SEO Description' },
${extraFieldsBlock}    },
  },
},
`;
}
function escapeString(input) {
    return input.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
}
//# sourceMappingURL=NewPostTypeInstructions.js.map