import { useMemo, useState } from 'react';
import { ChevronDown, ChevronUp, Filter, Check, X, Search, HelpCircle, FolderKanban, Package, Users, FileText, Coins, RotateCcw } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { CheckBox } from '@/Components/Proto/UI/CheckBox';
import { ListFooter } from '@/Components/Table/ListFooter';
import { Link, router } from '@inertiajs/react';
import { STATUS_GUIDE, STATUS_FILTERS } from '@/Proto/companyProjectData';
import { NativeSelect } from '@/Components/ui/native-select';
import { useClientSort, SortButton } from '@/lib/ClientSort';
import { useResizableColumns, ColumnResizeGrip } from '@/lib/useResizableColumns';
import { useToast } from '@/Components/Toast';
import { SELECTED_TD, SELECTED_HOVER_TD } from '@/lib/rowTint';

const money = (n) => (Number(n) || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
// Status dot colours — mirrors the Company Project Board legend (semantic:
// Exploring = neutral white, Sample = amber, Lab Testing = orange, Approved =
// green, Quotation = brand violet, Failed = red, Commercialized = green).
const STATUS_DOT = { Created: '#9ca3af', Exploring: '#ffffff', Sample: 'var(--color-warning)', 'Lab Testing': '#f97316', Approved: 'var(--color-success)', Quotation: 'var(--color-primary)', Failed: 'var(--color-danger)', Commercialized: '#16a34a' };
// Faint inner ring so a white/light dot stays visible on white surfaces (Board pattern).
const DOT_RING = 'inset 0 0 0 1px color-mix(in srgb, var(--color-card-foreground) 22%, transparent)';
// Priority accent colours (High/Important = amber, Very = red, else neutral).
const priorityDot = (p = '') => {
    const s = p.toLowerCase();
    if (s.includes('very')) return 'var(--color-danger)';
    if (s.includes('high') || s.includes('important')) return 'var(--color-warning)';
    return 'var(--color-muted-foreground)';
};
const CARD = 'rounded-2xl border border-border bg-card shadow-sm';
const TABLE = 'w-full border-separate border-spacing-0 text-foreground [&_thead_th]:whitespace-nowrap [&_thead_th]:bg-[color-mix(in_srgb,var(--color-secondary)_50%,var(--color-card))] [&_thead_th]:px-3.5 [&_thead_th]:py-2.5 [&_thead_th]:text-left [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground [&_thead_th:first-child]:rounded-l-full [&_thead_th:first-child]:pl-4 [&_thead_th:last-child]:rounded-r-full [&_thead_th:last-child]:pr-4 [&_tbody_td]:overflow-hidden [&_tbody_td]:whitespace-nowrap [&_tbody_td]:border-b [&_tbody_td]:border-border/60 [&_tbody_td:first-child]:pl-4 [&_tbody_td:last-child]:pr-4 [&_tbody_td]:px-3.5 [&_tbody_td]:py-[16px] [&_tbody_td]:text-[12px] [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:nth-child(even)_td]:bg-secondary/25 [&_tbody_tr:hover_td]:bg-secondary/60';
const EMPTY_F = { id: '', company: '', division: '', industry: '', principal: '', product: '', application: '', sales: '', creator: '', priority: '' };

// Sortable columns — id → raw row value (house ClientSort pattern).
const SORT_GETTERS = {
    id: (l) => l.id,
    priority: (l) => l.priority,
    company: (l) => l.company,
    product: (l) => l.product,
    target: (l) => l.targetValue,
    status: (l) => l.status,
};
// Resizable-column ids (left→right) + default widths for the table-fixed layout.
const COLS = ['check', 'id', 'priority', 'company', 'product', 'target', 'status', 'action'];
const COL_W = { check: 48, id: 110, priority: 130, company: 220, product: 230, target: 170, status: 140, action: 150 };

// Coloured status/priority pill — tinted bg + accent text + dot (matches the guide colours).
function Pill({ color, children }) {
    const accent = color === '#ffffff' ? 'var(--color-muted-foreground)' : color;
    return (
        <span className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-full py-[3px] pl-2 pr-2.5 text-[11px] font-semibold" style={{ color: accent, background: `color-mix(in srgb, ${accent} 14%, transparent)` }}>
            <span className="size-1.5 shrink-0 rounded-full" style={{ background: color, boxShadow: DOT_RING }} />
            {children}
        </span>
    );
}

// Drawer section block with icon header.
function Section({ icon: Icon, title, children }) {
    return (
        <section>
            <div className="mb-2 flex items-center gap-2">
                <span className="grid size-6 place-items-center rounded-md bg-accent text-primary"><Icon className="size-3.5" /></span>
                <h3 className="m-0 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">{title}</h3>
            </div>
            {children}
        </section>
    );
}

// Definition row inside a drawer section.
function Row({ label, children }) {
    return (
        <div className="flex items-baseline justify-between gap-3 border-b border-border/40 py-1.5 last:border-0">
            <span className="shrink-0 text-[12px] text-muted-foreground">{label}</span>
            <span className="min-w-0 truncate text-right text-[13px] font-semibold text-foreground" title={typeof children === 'string' ? children : undefined}>{children}</span>
        </div>
    );
}

export default function ProjectApprovalSm({ lines = [], scoped = true, filterOptions = {} }) {
    const { show: showToast } = useToast();
    // Server ships one row per PM-approved CC line awaiting SM; derive line-level filter
    // option lists from the shipped set (client-side filter/paginate over the scoped queue).
    const LINES = lines;
    const distinct = (key) => [...new Set(lines.map((l) => l[key]).filter(Boolean))].sort((a, b) => String(a).localeCompare(String(b)));
    const OPT = {
        companies: (filterOptions.companies || []).map((c) => c.CompanyName),
        divisions: (filterOptions.divisions || []).map((d) => d.DivisionName),
        industries: (filterOptions.industries || []).map((i) => i.IndustryName),
        principals: distinct('producer'),
        products: distinct('product'),
        applications: distinct('application'),
        creators: distinct('creator'),
        sales: distinct('sales'),
        priorities: distinct('priority'),
    };
    const [filterOpen, setFilterOpen] = useState(false);
    const [guideOpen, setGuideOpen] = useState(false);
    const [f, setF] = useState({ ...EMPTY_F });
    const [statuses, setStatuses] = useState(new Set());
    const [applied, setApplied] = useState({ f: { ...EMPTY_F }, statuses: new Set() });
    const [selected, setSelected] = useState(new Set());
    const [sort, setSort] = useState('newest');
    const [page, setPage] = useState(1);
    const [perPage, setPerPage] = useState(10);
    const [confirmA, setConfirmA] = useState(null); // { action: 'Approve'|'Revise', items: line[] }
    const [modalComment, setModalComment] = useState('');

    const setField = (k, v) => setF((s) => ({ ...s, [k]: v }));
    const toggleStatus = (s) => setStatuses((prev) => { const n = new Set(prev); n.has(s) ? n.delete(s) : n.add(s); return n; });
    const reset = () => { setF({ ...EMPTY_F }); setStatuses(new Set()); setApplied({ f: { ...EMPTY_F }, statuses: new Set() }); setPage(1); };
    const doSearch = () => { setApplied({ f: { ...f }, statuses: new Set(statuses) }); setPage(1); };

    const rows = useMemo(() => {
        const a = applied.f;
        let r = LINES.filter((l) => {
            if (a.id && String(l.id) !== a.id.trim()) return false;
            if (a.company && l.company !== a.company) return false;
            if (a.division && l.division !== a.division) return false;
            if (a.industry && l.industry !== a.industry) return false;
            if (a.creator && l.creator !== a.creator) return false;
            if (a.sales && l.sales !== a.sales) return false;
            if (a.priority && l.priority !== a.priority) return false;
            if (a.principal && l.producer !== a.principal) return false;
            if (a.product && l.product !== a.product) return false;
            if (a.application && l.application !== a.application) return false;
            if (applied.statuses.size && !applied.statuses.has(l.status)) return false;
            return true;
        });
        return [...r].sort((x, y) => (sort === 'newest' ? y.id - x.id : x.id - y.id));
    }, [applied, sort]);

    // Column-header sort (ClientSort) — applies on top of the Newest/Oldest base order.
    const { sorted, sortKey, sortDir, toggleSort } = useClientSort(rows, SORT_GETTERS);
    // Resizable columns — drag a header's right edge (house pattern).
    const { widthOf, startResize, resizingId } = useResizableColumns(COL_W);
    const tableWidth = COLS.reduce((sum, id) => sum + widthOf(id), 0);

    const totalPages = Math.max(1, Math.ceil(rows.length / perPage));
    const currentPage = Math.min(page, totalPages);
    const pageRows = sorted.slice((currentPage - 1) * perPage, currentPage * perPage);
    const allChecked = pageRows.length > 0 && pageRows.every((l) => selected.has(l.key));
    const toggleAll = () => setSelected((prev) => { const n = new Set(prev); if (allChecked) pageRows.forEach((l) => n.delete(l.key)); else pageRows.forEach((l) => n.add(l.key)); return n; });
    const toggleSel = (k) => setSelected((prev) => { const n = new Set(prev); n.has(k) ? n.delete(k) : n.add(k); return n; });

    const selectedLines = useMemo(() => rows.filter((r) => selected.has(r.key)), [rows, selected]);
    const openConfirm = (action, items) => {
        if (!items.length) { showToast('Select at least one product first.', 'warning'); return; }
        setModalComment('');
        setConfirmA({ action, items });
    };
    const [submitting, setSubmitting] = useState(false);
    const [formError, setFormError] = useState('');
    const submitConfirm = () => {
        const text = modalComment.trim();
        if (!text || submitting) return; // comment mandatory for BOTH actions (legacy-faithful)
        const action = confirmA.action === 'Approve' ? 'approve' : 'revise';
        const details = confirmA.items.map((it) => it.ccId).filter((n) => Number.isInteger(n) && n > 0);
        if (details.length === 0) return;
        setSubmitting(true);
        setFormError('');
        router.post(
            route('company-projects.approval-sm.act', { action }),
            { details, comment: text },
            {
                preserveScroll: true,
                onSuccess: () => {
                    setSelected(new Set());
                    setConfirmA(null);
                },
                onError: (errors) => setFormError(errors.details || errors.comment || 'Processing failed — reload the queue.'),
                onFinish: () => setSubmitting(false),
            },
        );
    };

    return (
        <section className="flex min-w-0 flex-col gap-4">
            <header className="flex flex-wrap items-center justify-between gap-3">
                <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">Approval SM - Company Project</h1>
                <div className="flex items-center gap-3">
                    <div className="relative" onMouseEnter={() => setGuideOpen(true)} onMouseLeave={() => setGuideOpen(false)}>
                        <button
                            type="button"
                            onClick={() => setGuideOpen((v) => !v)}
                            title="Status Guide"
                            aria-label="Status Guide"
                            aria-expanded={guideOpen}
                            className={`inline-grid size-9 place-items-center rounded-full border transition-colors ${guideOpen ? 'border-primary bg-accent text-primary' : 'border-input text-muted-foreground hover:border-primary hover:text-primary'}`}
                        >
                            <HelpCircle className="size-[18px]" />
                        </button>
                        {guideOpen && (
                            <div className="absolute right-0 top-full z-[56] w-[360px] max-w-[90vw] pt-2">
                                <div className="rounded-2xl border border-border bg-card p-3.5 text-left shadow-xl">
                                    <div className="mb-2.5 flex items-center justify-between">
                                        <h3 className="m-0 text-[13px] font-bold text-foreground">Status Guide</h3>
                                        <button type="button" onClick={() => setGuideOpen(false)} className="inline-grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground" aria-label="Close"><X className="size-4" /></button>
                                    </div>
                                    <ul className="m-0 flex list-none flex-col gap-2 p-0">
                                        {STATUS_GUIDE.map(([name, desc]) => (
                                            <li key={name} className="flex items-start gap-2.5">
                                                <span className="inline-flex w-[104px] shrink-0 items-center gap-1.5 pt-0.5">
                                                    <span className="size-2 shrink-0 rounded-full" style={{ background: STATUS_DOT[name], boxShadow: DOT_RING }} />
                                                    <span className="text-[12px] font-semibold leading-tight text-foreground">{name}</span>
                                                </span>
                                                <span className="text-[11px] leading-snug text-muted-foreground">{desc}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </header>

            <div className="flex flex-col items-start gap-4 xl:flex-row">
                {/* Left Pane (Table & Filter) */}
                <div className="flex min-w-0 flex-1 flex-col gap-4 self-stretch">
                    {/* Filter (collapsible) */}
                    <article className={CARD}>
                        <div className="flex items-center px-5 py-3.5">
                            <button type="button" onClick={() => setFilterOpen((v) => !v)} className="flex items-center gap-2 text-sm font-bold text-primary">
                                <Filter className="size-4" /> Filter {filterOpen ? <ChevronUp className="size-4 text-muted-foreground" /> : <ChevronDown className="size-4 text-muted-foreground" />}
                            </button>
                        </div>
                        {filterOpen && (
                            <div className="border-t border-border/60 p-5 pt-4">
                                <div className="grid grid-cols-5 gap-x-3 gap-y-3 max-[1100px]:grid-cols-3 max-[700px]:grid-cols-2 max-[480px]:grid-cols-1">
                                    <FloatingField size="sm" variant="filled" label="Project ID" value={f.id} onChange={(e) => setField('id', e.target.value)} />
                                    <FloatingField size="sm" variant="filled" as="select" label="Company" value={f.company} onChange={(e) => setField('company', e.target.value)}><option value="">Select Company</option>{OPT.companies.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Division" value={f.division} onChange={(e) => setField('division', e.target.value)}><option value="">Select Division</option>{OPT.divisions.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Industry" value={f.industry} onChange={(e) => setField('industry', e.target.value)}><option value="">Select Industry</option>{OPT.industries.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Principal" value={f.principal} onChange={(e) => setField('principal', e.target.value)}><option value="">Select Principal</option>{OPT.principals.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Product" value={f.product} onChange={(e) => setField('product', e.target.value)}><option value="">Select Product</option>{OPT.products.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Application" value={f.application} onChange={(e) => setField('application', e.target.value)}><option value="">Select Application</option>{OPT.applications.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Sales" value={f.sales} onChange={(e) => setField('sales', e.target.value)}><option value="">Select Sales</option>{OPT.sales.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Creator" value={f.creator} onChange={(e) => setField('creator', e.target.value)}><option value="">Select Creator</option>{OPT.creators.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                    <FloatingField size="sm" variant="filled" as="select" label="Project Priority" value={f.priority} onChange={(e) => setField('priority', e.target.value)}><option value="">Select Priority</option>{OPT.priorities.map((o) => <option key={o} value={o}>{o}</option>)}</FloatingField>
                                </div>
                                <div className="mt-4">
                                    <span className="mb-2 block text-[12px] font-semibold text-muted-foreground">Status</span>
                                    <div className="flex flex-wrap gap-2">
                                        {STATUS_FILTERS.map((s) => {
                                            const on = statuses.has(s);
                                            return (
                                                <button key={s} type="button" onClick={() => toggleStatus(s)} className={`inline-flex h-8 items-center gap-1.5 rounded-lg border px-3 text-xs font-semibold transition-colors ${on ? 'border-border-soft-strong bg-accent text-primary' : 'border-input bg-card text-foreground hover:border-primary'}`}>
                                                    <span className="size-2 rounded-full" style={{ backgroundColor: STATUS_DOT[s], boxShadow: DOT_RING }} />{s}{on && <Check className="size-3" />}
                                                </button>
                                            );
                                        })}
                                    </div>
                                </div>
                                <div className="mt-5 flex items-center justify-start gap-2.5">
                                    <button type="button" onClick={doSearch} className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105"><Search className="size-3.5" /> Search</button>
                                    <button type="button" onClick={reset} className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">Reset</button>
                                </div>
                            </div>
                        )}
                    </article>

                    {!scoped && <p className="rounded-lg border border-border bg-secondary/40 px-4 py-2 text-[12px] text-muted-foreground">Oversight view — you head no division, so approving/revising is disabled.</p>}

                    {/* List — one row per product */}
                    <article className={`${CARD} overflow-hidden`}>
                        <div className="flex flex-wrap items-center gap-2 border-b border-border px-5 py-3.5">
                            <h2 className="m-0 text-sm font-extrabold text-foreground">List Project Detail</h2>
                            <span className="rounded-full bg-secondary px-2 py-0.5 text-[11px] font-bold text-muted-foreground">{rows.length} Products</span>
                            <label className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">Sort by
                                <NativeSelect value={sort} onChange={(e) => setSort(e.target.value)} className="h-8 rounded-md border border-input bg-card px-2 text-xs font-medium text-foreground outline-none focus:border-primary"><option value="newest">Newest</option><option value="oldest">Oldest</option></NativeSelect>
                            </label>
                        </div>
                        <div className="flex flex-wrap items-center gap-2.5 border-b border-border/50 bg-muted/20 px-5 py-2.5">
                            <label className="inline-flex items-center gap-2 text-xs font-medium text-muted-foreground"><CheckBox checked={allChecked} onChange={toggleAll} /> Select all</label>
                            <span className="ml-auto text-[11px] font-semibold text-muted-foreground tabular-nums">{selected.size} selected</span>
                            <button type="button" disabled={selected.size === 0 || !scoped} onClick={() => openConfirm('Revise', selectedLines)} className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-card px-3 text-xs font-bold text-foreground hover:border-warning hover:text-warning-text disabled:opacity-50"><RotateCcw className="size-3.5" /> Revise Selected</button>
                            <button type="button" disabled={selected.size === 0 || !scoped} onClick={() => openConfirm('Approve', selectedLines)} className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-card px-3 text-xs font-bold text-foreground hover:border-primary hover:text-primary disabled:opacity-50"><Check className="size-3.5" /> Approve Selected</button>
                        </div>

                        {pageRows.length === 0 ? (
                            <p className="py-12 text-center text-sm text-muted-foreground">No products match the filter.</p>
                        ) : (
                            <div className="overflow-x-auto p-4 pt-3">
                                <table style={{ minWidth: tableWidth }} className={`${TABLE} table-fixed`}>
                                    <colgroup>
                                        {COLS.map((id) => <col key={id} style={{ width: widthOf(id) }} />)}
                                    </colgroup>
                                    <thead>
                                        <tr>
                                            <th>
                                                <CheckBox checked={allChecked} onChange={toggleAll} ariaLabel="Select all rows on page" />
                                            </th>
                                            <th className="group/col relative"><SortButton id="id" label="Project ID" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'id')} active={resizingId === 'id'} /></th>
                                            <th className="group/col relative"><SortButton id="priority" label="Priority" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'priority')} active={resizingId === 'priority'} /></th>
                                            <th className="group/col relative"><SortButton id="company" label="Company / Division" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'company')} active={resizingId === 'company'} /></th>
                                            <th className="group/col relative"><SortButton id="product" label="Product / Principal" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'product')} active={resizingId === 'product'} /></th>
                                            <th className="group/col relative"><SortButton id="target" label="Target Value / Date" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'target')} active={resizingId === 'target'} /></th>
                                            <th className="group/col relative"><SortButton id="status" label="Status" sortKey={sortKey} sortDir={sortDir} onToggle={toggleSort} /><ColumnResizeGrip onMouseDown={(e) => startResize(e, 'status')} active={resizingId === 'status'} /></th>
                                            <th className="group/col relative !text-right">Action<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'action')} active={resizingId === 'action'} /></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {pageRows.map((l) => {
                                            const isSel = selected.has(l.key);
                                            return (
                                                <tr key={l.key} onClick={() => router.visit(route('company-projects.approval-sm.show', l.id))} title="Open full detail" className={`cursor-pointer transition-colors ${isSel ? `${SELECTED_TD} ${SELECTED_HOVER_TD}` : 'hover:bg-secondary/40'}`}>
                                                <td onClick={(e) => e.stopPropagation()}>
                                                    <CheckBox checked={selected.has(l.key)} onChange={() => toggleSel(l.key)} ariaLabel={`Select ${l.key}`} />
                                                </td>
                                                <td className="font-bold tabular-nums text-primary">#{l.id}</td>
                                                <td><Pill color={priorityDot(l.priority)}>{l.priority}</Pill></td>
                                                <td>
                                                    <div className="font-bold text-foreground">{l.company}</div>
                                                    <div className="text-[11px] text-muted-foreground">{l.division}</div>
                                                </td>
                                                <td>
                                                    <div className="font-semibold text-foreground">{l.product || '—'}</div>
                                                    <div className="text-[11px] text-muted-foreground">{l.producer || '—'}{l.application ? ` · ${l.application}` : ''}</div>
                                                </td>
                                                <td>
                                                    <div className="font-bold tabular-nums text-foreground">${money(l.targetValue)}</div>
                                                    <div className="text-[11px] text-muted-foreground">{l.targetDate || '—'}</div>
                                                </td>
                                                <td><Pill color={STATUS_DOT[l.status]}>{l.status}</Pill></td>
                                                <td className="text-right">
                                                    <div className="flex items-center justify-end gap-1.5" onClick={(e) => e.stopPropagation()}>
                                                        <Link href={route('company-projects.approval-sm.show', l.id)} className="inline-flex h-8 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-2.5 text-[11px] font-bold text-foreground transition-colors hover:border-primary hover:text-primary" title="Open full detail (New Status, tabs, history)">
                                                            Detail
                                                        </Link>
                                                        <button type="button" disabled={!scoped} onClick={() => openConfirm('Revise', [l])} className="inline-grid size-8 place-items-center rounded-lg border border-warning/40 bg-card text-warning-text transition-colors hover:border-warning hover:bg-warning/10 disabled:opacity-50" title="Revise"><RotateCcw className="size-4" /></button>
                                                        <button type="button" disabled={!scoped} onClick={() => openConfirm('Approve', [l])} className="inline-grid size-8 place-items-center rounded-lg border border-success/50 bg-card text-success-text transition-colors hover:border-success hover:bg-success/10 disabled:opacity-50" title="Approve"><Check className="size-4" /></button>
                                                    </div>
                                                </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        )}

                        <ListFooter
                            page={currentPage}
                            totalPages={totalPages}
                            onPage={setPage}
                            pageSize={perPage}
                            onPageSize={(n) => { setPerPage(n); setPage(1); }}
                            pageSizeOptions={[10, 25, 50]}
                            total={rows.length}
                            itemLabel="products"
                        />
                    </article>
                </div>

            </div>

            {/* Confirm modal — Approve / Revise (single, drawer, or bulk) */}
            {confirmA && (() => {
                const isApprove = confirmA.action === 'Approve';
                const n = confirmA.items.length;
                return (
                    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
                        <div className="absolute inset-0 bg-black/50 backdrop-blur-[1px]" onClick={() => setConfirmA(null)} aria-hidden="true" />
                        <div role="dialog" aria-modal="true" className="relative w-full max-w-md rounded-2xl border border-border bg-card p-5 shadow-2xl">
                            <div className="flex items-start gap-3">
                                <span className={`grid size-10 shrink-0 place-items-center rounded-full ${isApprove ? 'bg-success/10 text-success-text' : 'bg-warning/10 text-warning-text'}`}>
                                    {isApprove ? <Check className="size-5" /> : <RotateCcw className="size-5" />}
                                </span>
                                <div className="min-w-0">
                                    <h3 className="m-0 text-base font-bold text-foreground">{confirmA.action} {n} product{n > 1 ? 's' : ''}?</h3>
                                    <p className="m-0 mt-0.5 text-[12px] leading-snug text-muted-foreground">
                                        {isApprove ? 'The following product(s) will be approved (SM).' : 'The following product(s) will be sent back for revision.'} This action will be recorded in the history.
                                    </p>
                                </div>
                                <button type="button" onClick={() => setConfirmA(null)} className="-mr-1 -mt-1 inline-grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground" aria-label="Close"><X className="size-4" /></button>
                            </div>

                            <ul className="m-0 mt-3 flex max-h-32 list-none flex-col gap-1 overflow-y-auto rounded-lg border border-border/60 bg-muted/30 p-2 text-[12px]">
                                {confirmA.items.map((it) => (
                                    <li key={it.key} className="flex items-center gap-2 truncate">
                                        <span className="shrink-0 font-bold tabular-nums text-primary">#{it.id}</span>
                                        <span className="truncate font-medium text-foreground">{it.product || '—'}</span>
                                        <span className="ml-auto shrink-0 truncate text-muted-foreground">{it.company}</span>
                                    </li>
                                ))}
                            </ul>

                            <label className="mt-3 block">
                                <span className="mb-1.5 block text-[12px] font-semibold text-muted-foreground">Comment <span className="text-danger-text">*</span></span>
                                <textarea value={modalComment} onChange={(e) => setModalComment(e.target.value)} rows={3} autoFocus placeholder={isApprove ? 'Add a note…' : 'What needs to be revised…'} className="w-full resize-y rounded-lg border border-input bg-card px-3 py-2.5 text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground/55 focus:border-primary focus:ring-1 focus:ring-primary" />
                            </label>
                            {formError && <p className="mt-2 text-[12px] font-medium text-danger-text">{formError}</p>}

                            <div className="mt-4 flex items-center justify-end gap-2.5">
                                <button type="button" onClick={() => setConfirmA(null)} className="inline-flex h-9 items-center rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">Cancel</button>
                                <button
                                    type="button"
                                    disabled={!modalComment.trim() || submitting}
                                    onClick={submitConfirm}
                                    className={`inline-flex h-9 items-center gap-1.5 rounded-lg px-5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50 ${isApprove ? 'bg-success' : 'bg-warning'}`}
                                >
                                    {isApprove ? <Check className="size-3.5" /> : <RotateCcw className="size-3.5" />} {confirmA.action}
                                </button>
                            </div>
                        </div>
                    </div>
                );
            })()}
        </section>
    );
}

ProjectApprovalSm.layout = [AppLayout];
