'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Check, FileImage, ImageIcon, SquarePen, TriangleAlert, X } from 'lucide-react';
import { useMemo, useState } from 'react';
import { FilterPill } from '../components/ui/FilterPill.js';
const FILTERS = [
    ['all', 'All items'],
    ['alt', 'Missing Alt'],
    ['title', 'Missing Title'],
    ['poor', 'Poor score'],
];
const hasValue = (value) => Boolean(value?.trim());
const itemScore = (item) => item.seoScore ?? 0;
/** Presentational buckets for the score bar/number — score itself comes from cms-core. */
function scoreToneClass(score) {
    if (score >= 80)
        return 'text-[var(--suc)]';
    if (score >= 30)
        return 'text-[var(--warn)]';
    return 'text-[var(--err)]';
}
function scoreBarClass(score) {
    if (score >= 80)
        return 'bg-[var(--suc)]';
    if (score >= 30)
        return 'bg-[var(--warn)]';
    return 'bg-[var(--err)]';
}
function scoreLabel(score) {
    if (score >= 80)
        return 'Good';
    if (score >= 55)
        return 'Fair';
    if (score >= 30)
        return 'Needs work';
    return 'Poor';
}
function isImageItem(item) {
    return (Boolean(item.url) &&
        (item.type?.startsWith('image/') || /\.(avif|gif|jpe?g|png|webp|svg)$/i.test(item.url)));
}
function typeLabel(item) {
    return (item.format ?? item.type ?? '').replace(/^.*\//, '').toUpperCase();
}
function ScoreBar({ score }) {
    return (_jsxs("div", { className: "flex items-center gap-[7px]", children: [_jsx("div", { role: "meter", "aria-label": "SEO score", "aria-valuenow": score, "aria-valuemin": 0, "aria-valuemax": 100, className: "h-[5px] w-[60px] overflow-hidden rounded-full bg-[var(--bdr)]", children: _jsx("div", { className: `h-full rounded-full motion-safe:transition-[width] motion-safe:duration-300 ${scoreBarClass(score)}`, style: { width: `${score}%` } }) }), _jsx("span", { className: `w-7 text-right text-xs font-semibold tabular-nums ${scoreToneClass(score)}`, children: score })] }));
}
function SeoCheck({ set, missTone }) {
    if (set) {
        return (_jsxs("span", { className: "inline-flex items-center gap-[3px] rounded-[4px] bg-[var(--suc-l)] px-[7px] py-[2px] text-[11px] font-medium text-[var(--suc)]", children: [_jsx(Check, { size: 10, "aria-hidden": true }), "Set"] }));
    }
    const Icon = missTone === 'err' ? X : TriangleAlert;
    const tone = missTone === 'err'
        ? 'bg-[var(--err-l)] text-[var(--err)]'
        : 'bg-[var(--warn-l)] text-[var(--warn)]';
    return (_jsxs("span", { className: `inline-flex items-center gap-[3px] rounded-[4px] px-[7px] py-[2px] text-[11px] font-medium ${tone}`, children: [_jsx(Icon, { size: 10, "aria-hidden": true }), "Missing"] }));
}
function StatCard({ value, label, sub, toneClass, }) {
    return (_jsxs("div", { className: "rounded-[10px] border border-[var(--bdr)] bg-[var(--card)] px-4 py-3.5", children: [_jsx("div", { className: `text-[26px] leading-none font-bold tracking-[-0.8px] ${toneClass}`, children: value }), _jsx("div", { className: "mt-1 text-xs text-[var(--sub)]", children: label }), _jsx("div", { className: `mt-[3px] text-[11px] font-medium ${toneClass}`, children: sub })] }));
}
export function MediaSeoAudit({ items, onEdit, error, onRetry }) {
    const [filter, setFilter] = useState('all');
    const stats = useMemo(() => {
        const total = items.length;
        const missingAlt = items.filter((it) => !hasValue(it.altTag)).length;
        const missingTitle = items.filter((it) => !hasValue(it.title)).length;
        const missingDesc = items.filter((it) => !hasValue(it.description)).length;
        const avgScore = total === 0 ? 0 : Math.round(items.reduce((sum, it) => sum + itemScore(it), 0) / total);
        return { total, missingAlt, missingTitle, missingDesc, avgScore };
    }, [items]);
    const filtered = useMemo(() => {
        switch (filter) {
            case 'all':
                return items;
            case 'alt':
                return items.filter((it) => !hasValue(it.altTag));
            case 'title':
                return items.filter((it) => !hasValue(it.title));
            case 'poor':
                return items.filter((it) => itemScore(it) < 40);
            default: {
                const exhaustive = filter;
                return exhaustive;
            }
        }
    }, [items, filter]);
    if (error && items.length === 0) {
        return (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: _jsxs("div", { role: "alert", className: "flex flex-col items-center justify-center rounded-[10px] border border-[var(--bdr)] bg-[var(--card)] px-4 py-14 text-center", children: [_jsx(TriangleAlert, { size: 24, className: "mb-3 text-[var(--err)]", "aria-hidden": true }), _jsx("p", { className: "text-sm font-medium text-[var(--txt)]", children: "Couldn't load media" }), _jsx("p", { className: "mt-1 max-w-sm text-xs text-[var(--sub)]", children: error }), onRetry && (_jsx("button", { type: "button", onClick: onRetry, className: "mt-4 rounded-[7px] border border-[var(--bdr)] bg-[var(--card)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--txt)] transition-colors hover:border-[var(--acc)] hover:text-[var(--acc)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: "Retry" }))] }) }));
    }
    return (_jsxs("div", { className: "min-h-0 flex-1 overflow-y-auto", children: [_jsxs("div", { className: "mb-[18px] grid grid-cols-2 gap-2.5 lg:grid-cols-4", children: [_jsx(StatCard, { value: `${stats.avgScore}/100`, label: "Avg SEO Score", sub: scoreLabel(stats.avgScore), toneClass: scoreToneClass(stats.avgScore) }), _jsx(StatCard, { value: String(stats.missingAlt), label: "Missing Alt Text", sub: `${stats.total - stats.missingAlt} have alt text`, toneClass: stats.missingAlt > 0 ? 'text-[var(--err)]' : 'text-[var(--suc)]' }), _jsx(StatCard, { value: String(stats.missingTitle), label: "Missing Titles", sub: `${stats.total - stats.missingTitle} have titles`, toneClass: stats.missingTitle > 0 ? 'text-[var(--warn)]' : 'text-[var(--suc)]' }), _jsx(StatCard, { value: String(stats.missingDesc), label: "Missing Descriptions", sub: `${stats.total - stats.missingDesc} have descriptions`, toneClass: stats.missingDesc > 5 ? 'text-[var(--warn)]' : 'text-[var(--sub)]' })] }), _jsxs("div", { className: "mb-3 flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "text-[12.5px] font-medium text-[var(--sub)]", children: "Show:" }), FILTERS.map(([value, label]) => (_jsx(FilterPill, { active: filter === value, onClick: () => setFilter(value), children: label }, value))), _jsxs("span", { className: "ml-auto text-xs text-[var(--muted)]", children: [filtered.length, " item", filtered.length !== 1 ? 's' : ''] })] }), _jsx("div", { className: "overflow-x-auto rounded-[10px] border border-[var(--bdr)] bg-[var(--card)]", children: filtered.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center px-4 py-14 text-center", children: [_jsx(ImageIcon, { size: 24, className: "mb-3 text-[var(--muted)]", "aria-hidden": true }), _jsx("p", { className: "text-sm font-medium text-[var(--txt)]", children: items.length === 0 ? 'No media to audit' : 'No items match this filter' }), _jsx("p", { className: "mt-1 text-xs text-[var(--muted)]", children: items.length === 0
                                ? 'Upload files to the library to see their SEO health here.'
                                : 'Try a different filter to see more items.' })] })) : (
                // min-w keeps the 7 columns readable; narrow viewports scroll sideways.
                _jsxs("table", { className: "w-full min-w-[820px] border-collapse", "aria-label": "Media SEO audit", children: [_jsx("thead", { children: _jsx("tr", { children: ['File', 'Type', 'Alt Text', 'Title', 'Description', 'SEO Score', 'Action'].map((heading) => (_jsx("th", { scope: "col", className: `border-b border-[var(--bdr)] bg-[var(--bg)] px-3 py-2 text-[11px] font-semibold tracking-[0.5px] whitespace-nowrap text-[var(--muted)] uppercase ${heading === 'Action' ? 'text-right' : 'text-left'}`, children: heading }, heading))) }) }), _jsx("tbody", { children: filtered.map((item) => {
                                const score = itemScore(item);
                                return (_jsxs("tr", { tabIndex: 0, onClick: () => onEdit(item), onKeyDown: (e) => {
                                        if (e.target !== e.currentTarget)
                                            return;
                                        if (e.key === 'Enter' || e.key === ' ') {
                                            e.preventDefault();
                                            onEdit(item);
                                        }
                                    }, "aria-label": `Edit SEO metadata for ${item.name}`, className: "cursor-pointer border-b border-[var(--bdr)] transition-colors last:border-b-0 hover:bg-[var(--acc-l)] focus-visible:bg-[var(--acc-l)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none focus-visible:ring-inset", children: [_jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsxs("div", { className: "flex items-center gap-2.5", children: [_jsx("div", { className: "flex h-[30px] w-[38px] shrink-0 items-center justify-center overflow-hidden rounded-[5px] border border-[var(--bdr)] bg-[var(--bg)]", children: isImageItem(item) ? (_jsx("img", { src: item.url, alt: "", className: "h-full w-full object-cover", loading: "lazy" })) : (_jsx(FileImage, { size: 14, className: "text-[var(--muted)]", "aria-hidden": true })) }), _jsxs("div", { className: "min-w-0", children: [_jsx("div", { className: "max-w-[160px] truncate text-[12.5px] font-medium text-[var(--txt)]", children: item.name }), _jsx("div", { className: "text-[11px] text-[var(--muted)]", children: item.size })] })] }) }), _jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsx("span", { className: "text-[11.5px] font-semibold tracking-[0.3px] text-[var(--sub)] uppercase", children: typeLabel(item) }) }), _jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsx(SeoCheck, { set: hasValue(item.altTag), missTone: "err" }) }), _jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsx(SeoCheck, { set: hasValue(item.title), missTone: "warn" }) }), _jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsx(SeoCheck, { set: hasValue(item.description), missTone: "warn" }) }), _jsx("td", { className: "px-3 py-[9px] align-middle", children: _jsx(ScoreBar, { score: score }) }), _jsx("td", { className: "px-3 py-[9px] text-right align-middle", children: _jsxs("button", { type: "button", onClick: (e) => {
                                                    e.stopPropagation();
                                                    onEdit(item);
                                                }, className: "inline-flex items-center gap-[5px] rounded-[7px] px-2 py-1 text-[11.5px] text-[var(--sub)] transition-colors hover:bg-[var(--acc-l)] hover:text-[var(--acc)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: [_jsx(SquarePen, { size: 11, "aria-hidden": true }), "Edit"] }) })] }, item.id));
                            }) })] })) })] }));
}
//# sourceMappingURL=MediaSeoAudit.js.map