'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Embed tab of the Form Schema drawer. Shows the public submission/schema
 * endpoints and copy-paste embed snippets, and lets the editor restrict which
 * origins may host the embedded form. Snippets are derived from the form slug;
 * the live public endpoints land in a later phase (PR 5) but the paths shown
 * here are the committed contract.
 */
import { Check, Copy } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { fetchEmbedSettings, updateEmbedSettings, } from '../../lib/forms-service.js';
import { FormsErrorState, FormsLoading, btnSecondary } from './primitives.js';
function siteOrigin() {
    if (typeof window !== 'undefined')
        return window.location.origin;
    return 'https://your-site.com';
}
export function EmbedPanel({ formId, slug, status, }) {
    const [settings, setSettings] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [domains, setDomains] = useState('');
    const [saving, setSaving] = useState(false);
    useEffect(() => {
        let active = true;
        setLoading(true);
        setError(null);
        fetchEmbedSettings(formId)
            .then((s) => {
            if (!active)
                return;
            setSettings(s);
            setDomains((s.allowedDomains ?? []).join('\n'));
        })
            .catch((e) => {
            if (active)
                setError(e instanceof Error ? e.message : 'Failed to load embed settings');
        })
            .finally(() => {
            if (active)
                setLoading(false);
        });
        return () => {
            active = false;
        };
    }, [formId]);
    const origin = siteOrigin();
    const submitUrl = `${origin}/api/forms/${slug}/submit`;
    const schemaUrl = `${origin}/api/forms/${slug}/schema`;
    const embedUrl = `${origin}/forms/embed/${slug}`;
    const iframeSnippet = `<iframe src="${embedUrl}" title="${slug}" style="width:100%;border:0;" loading="lazy"></iframe>`;
    const scriptSnippet = `<div data-actuate-form="${slug}"></div>\n<script src="${origin}/api/forms/embed.js" async></script>`;
    async function saveDomains() {
        setSaving(true);
        const list = domains
            .split('\n')
            .map((d) => d.trim())
            .filter(Boolean);
        const res = await updateEmbedSettings(formId, { allowedDomains: list });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.data)
            setSettings(res.data);
        toast.success('Embed settings saved.');
    }
    if (loading)
        return _jsx(FormsLoading, { label: "Loading embed settings\u2026" });
    if (error)
        return _jsx(FormsErrorState, { message: error });
    return (_jsxs("div", { className: "space-y-5", children: [status !== 'active' && (_jsxs("p", { className: "border-warning/30 bg-warning/10 text-warning rounded-md border px-3 py-2 text-sm", children: ["This form is ", _jsx("span", { className: "font-medium", children: status }), " and won't accept public submissions until it's set to Active."] })), _jsx(CopyField, { label: "Public submission endpoint", value: submitUrl }), _jsx(CopyField, { label: "Schema endpoint", value: schemaUrl }), _jsx(CopyField, { label: "Iframe embed", value: iframeSnippet, multiline: true }), _jsx(CopyField, { label: "Script embed", value: scriptSnippet, multiline: true }), _jsxs("div", { children: [_jsxs("label", { className: "text-foreground mb-1 block text-sm font-medium", children: ["Allowed domains", _jsx("span", { className: "text-muted-foreground ml-1 font-normal", children: "(one per line \u2014 leave empty to allow any)" })] }), _jsx("textarea", { rows: 3, value: domains, onChange: (e) => setDomains(e.target.value), placeholder: "example.com", className: "border-border bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-2.5 py-1.5 text-sm focus-visible:ring-2 focus-visible:outline-none" }), _jsx("div", { className: "mt-2 flex justify-end", children: _jsx("button", { className: btnSecondary, onClick: saveDomains, disabled: saving, children: saving ? 'Saving…' : 'Save domains' }) })] }), settings === null && null] }));
}
function CopyField({ label, value, multiline = false, }) {
    const [copied, setCopied] = useState(false);
    async function copy() {
        try {
            await navigator.clipboard.writeText(value);
            setCopied(true);
            setTimeout(() => setCopied(false), 1500);
        }
        catch {
            toast.error('Copy failed — your browser blocked clipboard access.');
        }
    }
    return (_jsxs("div", { children: [_jsxs("div", { className: "mb-1 flex items-center justify-between", children: [_jsx("span", { className: "text-foreground text-sm font-medium", children: label }), _jsxs("button", { type: "button", onClick: copy, className: "text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium focus-visible:ring-2 focus-visible:outline-none", "aria-label": `Copy ${label}`, 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'] })] }), _jsx("pre", { className: `border-border bg-muted text-foreground overflow-x-auto rounded-md border px-2.5 py-2 font-mono text-xs ${multiline ? 'whitespace-pre-wrap' : 'whitespace-nowrap'}`, children: value })] }));
}
//# sourceMappingURL=EmbedPanel.js.map