'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Check, Copy, Link2, Loader2, Share2, X } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.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);
    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");
        }
    }
    if (!open)
        return null;
    return (_jsxs("div", { className: "fixed inset-0 z-50 flex items-center justify-center p-4", children: [_jsx("div", { className: "fixed inset-0 bg-black/40", onClick: onClose }), _jsxs("div", { className: "relative w-full max-w-lg rounded-lg bg-white shadow-xl", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Share2, { className: "h-5 w-5 text-gray-600" }), _jsx("h2", { className: "text-lg font-semibold text-gray-900", children: "Share preview link" })] }), _jsx("button", { onClick: onClose, className: "rounded-lg p-1.5 transition-colors hover:bg-gray-100", children: _jsx(X, { className: "h-5 w-5 text-gray-500" }) })] }), _jsxs("div", { className: "space-y-4 px-4 py-4", children: [_jsx("p", { className: "text-sm text-gray-600", 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("label", { className: "text-sm font-medium text-gray-700", 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", { onClick: () => setTtl(choice.seconds), className: `rounded-md border px-3 py-2 text-left text-sm transition-colors ${selected
                                                    ? 'border-blue-500 bg-blue-50 text-blue-900'
                                                    : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'}`, children: [_jsx("div", { className: "font-medium", children: choice.label }), _jsx("div", { className: "text-xs text-gray-500", children: choice.hint })] }, choice.seconds));
                                        }) }), _jsx("p", { className: "text-xs text-gray-500", children: "Preview tokens can't be revoked individually \u2014 pick the shortest TTL that fits." })] }), previewUrl ? (_jsxs("div", { className: "space-y-2 rounded-lg border border-gray-200 bg-gray-50 p-3", children: [_jsx("label", { className: "text-xs font-medium tracking-wide text-gray-500 uppercase", children: "Preview URL" }), _jsxs("div", { className: "flex items-stretch gap-2", children: [_jsx("input", { readOnly: true, value: previewUrl, onFocus: (e) => e.currentTarget.select(), className: "flex-1 rounded-md border border-gray-300 bg-white px-2 py-1.5 font-mono text-xs" }), _jsxs("button", { onClick: copyToClipboard, className: "inline-flex items-center gap-1.5 rounded-md bg-gray-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-gray-700", children: [copied ? _jsx(Check, { className: "h-3.5 w-3.5" }) : _jsx(Copy, { className: "h-3.5 w-3.5" }), copied ? 'Copied' : 'Copy'] })] }), expiresAt && (_jsxs("p", { className: "text-xs text-gray-500", children: ["Expires ", new Date(expiresAt).toLocaleString()] }))] })) : null] }), _jsxs("div", { className: "flex items-center justify-end gap-2 border-t border-gray-200 px-4 py-3", children: [_jsx("button", { onClick: onClose, className: "rounded-md px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100", children: "Close" }), _jsxs("button", { onClick: generate, disabled: generating, className: "inline-flex items-center gap-1.5 rounded-md bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50", children: [generating ? (_jsx(Loader2, { className: "h-4 w-4 animate-spin" })) : (_jsx(Link2, { className: "h-4 w-4" })), previewUrl ? 'Generate new link' : 'Generate link'] })] })] })] }));
}
//# sourceMappingURL=SharePreviewLinkDialog.js.map