'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useId, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Check, Copy, Link2, Loader2, Share2, X } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
import { adminPortalContainer } from '../lib/portal-container.js';
const TTL_CHOICES = [
    { label: '1 hour', seconds: 60 * 60, hint: 'Quick review' },
    { label: '1 day', seconds: 24 * 60 * 60, hint: 'Single workday' },
    { label: '7 days', seconds: 7 * 24 * 60 * 60, hint: 'Client review' },
    { label: '30 days', seconds: 30 * 24 * 60 * 60, hint: 'Long-running staging' },
];
function buildPreviewUrl({ siteUrl, urlPrefix, collectionSlug, documentSlug, token, }) {
    const base = (siteUrl ?? '').replace(/\/+$/, '');
    // Build the same path /resolve would match: <urlPrefix>/<slug>, or
    // /<slug> for top-level page collections. If there's no slug yet we
    // fall back to /admin's preview endpoint as a safety net.
    const slug = documentSlug?.toString().trim() ?? '';
    if (!slug) {
        return `${base}/preview/${collectionSlug}/_?token=${encodeURIComponent(token)}`;
    }
    const prefix = (urlPrefix ?? collectionSlug).replace(/^\/+|\/+$/g, '');
    const path = prefix ? `/${prefix}/${slug}` : `/${slug}`;
    return `${base}${path}?preview=${encodeURIComponent(token)}`;
}
export function SharePreviewLinkDialog({ collectionSlug, documentId, documentSlug, siteUrl, urlPrefix, open, onClose, }) {
    const [ttl, setTtl] = useState(TTL_CHOICES[2].seconds);
    const [token, setToken] = useState('');
    const [previewUrl, setPreviewUrl] = useState('');
    const [expiresAt, setExpiresAt] = useState('');
    const [generating, setGenerating] = useState(false);
    const [copied, setCopied] = useState(false);
    const previewUrlId = useId();
    async function generate() {
        setGenerating(true);
        const res = await cmsApi('/preview/token', {
            method: 'POST',
            body: JSON.stringify({
                collection: collectionSlug,
                documentId,
                ttlSeconds: ttl,
            }),
        });
        setGenerating(false);
        if (res.error || !res.data) {
            toast.error(res.error ?? 'Failed to create preview token');
            return;
        }
        const data = res.data;
        setToken(data.token);
        setExpiresAt(data.expiresAt ?? '');
        const url = buildPreviewUrl({
            siteUrl,
            urlPrefix,
            collectionSlug,
            documentSlug: data.slug ?? documentSlug,
            token: data.token,
        });
        setPreviewUrl(url);
        setCopied(false);
    }
    async function copyToClipboard() {
        if (!previewUrl)
            return;
        try {
            await navigator.clipboard.writeText(previewUrl);
            setCopied(true);
            toast.success('Preview link copied');
            setTimeout(() => setCopied(false), 2000);
        }
        catch {
            toast.error("Couldn't copy to clipboard");
        }
    }
    return (_jsx(Dialog.Root, { open: open, onOpenChange: (next) => !next && onClose(), children: _jsxs(Dialog.Portal, { container: adminPortalContainer(), children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-50 bg-black/40" }), _jsxs(Dialog.Content, { className: "bg-card text-card-foreground border-border fixed top-1/2 left-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg border shadow-xl focus:outline-none", children: [_jsxs("div", { className: "border-border flex items-center justify-between border-b px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Share2, { className: "text-muted-foreground h-5 w-5", "aria-hidden": true }), _jsx(Dialog.Title, { className: "text-foreground text-lg font-medium", children: "Share preview link" })] }), _jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "Close dialog", className: "text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring rounded-lg p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none", children: _jsx(X, { className: "h-5 w-5", "aria-hidden": true }) }) })] }), _jsxs("div", { className: "space-y-4 px-4 py-4", children: [_jsx(Dialog.Description, { className: "text-muted-foreground text-sm", children: "Generate a signed URL that lets anyone with the link view the current draft of this document \u2014 even if it's never been published." }), _jsxs("div", { className: "space-y-2", children: [_jsx("span", { className: "text-foreground text-sm font-medium", children: "Link lifetime" }), _jsx("div", { className: "grid grid-cols-2 gap-2", children: TTL_CHOICES.map((choice) => {
                                                const selected = ttl === choice.seconds;
                                                return (_jsxs("button", { type: "button", "aria-pressed": selected, onClick: () => setTtl(choice.seconds), className: `rounded-md border px-3 py-2 text-left text-sm transition-colors ${selected
                                                        ? 'border-primary bg-primary/10 text-foreground'
                                                        : 'border-border hover:border-input hover:bg-accent'}`, children: [_jsx("div", { className: "font-medium", children: choice.label }), _jsx("div", { className: "text-muted-foreground text-xs", children: choice.hint })] }, choice.seconds));
                                            }) }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Preview tokens can't be revoked individually \u2014 pick the shortest TTL that fits." })] }), previewUrl ? (_jsxs("div", { className: "border-border bg-muted space-y-2 rounded-lg border p-3", children: [_jsx("label", { htmlFor: previewUrlId, className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "Preview URL" }), _jsxs("div", { className: "flex items-stretch gap-2", children: [_jsx("input", { id: previewUrlId, readOnly: true, value: previewUrl, onFocus: (e) => e.currentTarget.select(), className: "border-input bg-background text-foreground flex-1 rounded-md border px-2 py-1.5 font-mono text-xs" }), _jsxs("button", { type: "button", onClick: copyToClipboard, className: "bg-primary text-primary-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium hover:opacity-90", 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'] })] }), expiresAt && (_jsxs("p", { className: "text-muted-foreground text-xs", children: ["Expires ", new Date(expiresAt).toLocaleString()] }))] })) : null] }), _jsxs("div", { className: "border-border flex items-center justify-end gap-2 border-t px-4 py-3", children: [_jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", className: "text-foreground hover:bg-accent rounded-md px-3 py-1.5 text-sm", children: "Close" }) }), _jsxs("button", { type: "button", onClick: generate, disabled: generating, className: "bg-primary text-primary-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium hover:opacity-90 disabled:opacity-50", children: [generating ? (_jsx(Loader2, { className: "h-4 w-4 animate-spin", "aria-hidden": true })) : (_jsx(Link2, { className: "h-4 w-4", "aria-hidden": true })), previewUrl ? 'Generate new link' : 'Generate link'] })] })] })] }) }));
}
//# sourceMappingURL=SharePreviewLinkDialog.js.map