/* eslint-disable @next/next/no-img-element -- Local file preview requires raw <img>, not next/image */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Dialog, DialogTrigger, DialogContent, DialogTitle } from '../../ui/dialog.js';
import { VisuallyHidden } from 'radix-ui';
import { DownloadIcon, ImageOff } from 'lucide-react';
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.ico', '.bmp']);
function isImagePath(path) {
    const dot = path.lastIndexOf('.');
    return dot >= 0 && IMAGE_EXTS.has(path.slice(dot).toLowerCase());
}
function previewUrl(path) {
    const ext = path.lastIndexOf('.') >= 0 ? path.slice(path.lastIndexOf('.')) : '';
    const mimeGuess = isImagePath(path) ? `image/${ext.slice(1).replace('jpg', 'jpeg')}` : '';
    const params = new URLSearchParams({ path, ...(mimeGuess && { mimeType: mimeGuess }) });
    return `/api/attachments/preview?${params.toString()}`;
}
function getFilename(path) {
    return path.split('/').pop() ?? path;
}
/** Regex matching `@/absolute/path` attachment references in text. */
const ATTACHMENT_REF_RE = /(?:^|\s)@(\/[^\s]+)/g;
/** Parse text into segments of plain text and attachment references. */
export function parseAttachmentRefs(text) {
    const segments = [];
    let lastIndex = 0;
    for (const match of text.matchAll(ATTACHMENT_REF_RE)) {
        const fullMatchStart = match.index;
        // The path capture starts after the optional leading whitespace
        const leadingWs = match[0].length - match[0].trimStart().length;
        const refStart = fullMatchStart + leadingWs;
        // Add text before this reference (including leading whitespace)
        if (refStart > lastIndex) {
            segments.push({ type: 'text', value: text.slice(lastIndex, refStart) });
        }
        segments.push({ type: 'attachment', path: match[1] });
        lastIndex = fullMatchStart + match[0].length;
    }
    if (lastIndex < text.length) {
        segments.push({ type: 'text', value: text.slice(lastIndex) });
    }
    return segments;
}
export function InlineAttachments({ text, attachmentPaths }) {
    const segments = parseAttachmentRefs(text);
    const hasInlineAttachments = segments.some((s) => s.type === 'attachment');
    const extraPaths = attachmentPaths?.filter(Boolean) ?? [];
    if (!hasInlineAttachments && extraPaths.length === 0) {
        return _jsx("span", { className: "text-sm leading-relaxed", children: text });
    }
    return (_jsxs("div", { className: "flex flex-col gap-2", children: [segments.map((segment) => {
                if (segment.type === 'text') {
                    const trimmed = segment.value.trim();
                    if (!trimmed)
                        return null;
                    return (_jsx("span", { className: "text-sm leading-relaxed", children: trimmed }, `text-${trimmed.slice(0, 40)}`));
                }
                return _jsx(AttachmentPreview, { path: segment.path }, `att-${segment.path}`);
            }), extraPaths.map((path) => (_jsx(AttachmentPreview, { path: path }, `extra-${path}`)))] }));
}
function AttachmentPreview({ path }) {
    const filename = getFilename(path);
    const [loadError, setLoadError] = useState(false);
    if (isImagePath(path)) {
        if (loadError) {
            return (_jsxs("div", { "data-testid": "inline-attachment-image-error", className: "text-muted-foreground flex items-center gap-2 rounded-md border px-3 py-2 text-sm", children: [_jsx(ImageOff, { className: "h-4 w-4 shrink-0" }), _jsx("span", { className: "truncate", children: filename })] }));
        }
        return (_jsxs(Dialog, { children: [_jsx(DialogTrigger, { asChild: true, children: _jsx("img", { src: previewUrl(path), alt: filename, "data-testid": "inline-attachment-image", onError: () => setLoadError(true), className: "max-h-48 max-w-full cursor-pointer rounded-md border object-contain transition-opacity hover:opacity-80" }) }), _jsxs(DialogContent, { className: "max-w-3xl gap-0 overflow-hidden border-0 p-0 [&>button:last-child]:!cursor-pointer [&>button:last-child]:!rounded-full [&>button:last-child]:!bg-black/70 [&>button:last-child]:!p-1.5 [&>button:last-child]:!text-white [&>button:last-child]:!opacity-100 [&>button:last-child]:!shadow-lg [&>button:last-child]:!backdrop-blur-md [&>button:last-child]:hover:!bg-black/90", children: [_jsx(VisuallyHidden.Root, { children: _jsxs(DialogTitle, { children: ["Preview: ", filename] }) }), _jsx("div", { className: "relative bg-black/90", children: _jsx("img", { src: previewUrl(path), alt: filename, className: "h-auto max-h-[70vh] w-full object-contain" }) }), _jsxs("div", { className: "bg-background flex items-center gap-3 px-4 py-3", children: [_jsx("div", { className: "flex min-w-0 flex-1 flex-col", children: _jsx("span", { className: "truncate text-sm font-medium", children: filename }) }), _jsx("a", { href: previewUrl(path), download: filename, className: "text-muted-foreground hover:text-foreground shrink-0 cursor-pointer rounded p-1.5 transition-colors", "aria-label": `Download ${filename}`, children: _jsx(DownloadIcon, { className: "h-4 w-4" }) })] })] })] }));
    }
    return (_jsx("a", { href: previewUrl(path), download: filename, "data-testid": "inline-attachment-file", className: "text-primary text-sm underline underline-offset-2", children: filename }));
}
