import { CheckboxControl } from "@wordpress/components";

function renderHighlightedText(text, ranges, className) {
    if (!text || !Array.isArray(ranges) || ranges.length === 0) {
        return text;
    }

    const output = [];
    let cursor = 0;

    ranges.forEach(([start, end], index) => {
        const rangeStart = Math.max(0, start);
        const rangeEnd = Math.min(text.length - 1, end);

        if (rangeStart > cursor) {
            output.push(text.slice(cursor, rangeStart));
        }

        output.push(
            <mark className={className} key={`${rangeStart}-${rangeEnd}-${index}`}>
                {text.slice(rangeStart, rangeEnd + 1)}
            </mark>,
        );

        cursor = rangeEnd + 1;
    });

    if (cursor < text.length) {
        output.push(text.slice(cursor));
    }

    return output;
}

export default function PageRow({ page, isSelected, onToggle, highlights }) {
    const title = page.title || "(no title)";
    const uri = String(page.uri || "");

    const handleRowClick = (e) => {
        // Don't toggle if clicking on interactive elements
        if (
            e.target.tagName === "INPUT" ||
            e.target.tagName === "BUTTON" ||
            e.target.tagName === "A" ||
            e.target.closest(".components-checkbox-control")
        ) {
            return;
        }
        onToggle();
    };

    return (
        <tr
            className={`ecw-priority-page-row ${
                isSelected ? "ecw-priority-page-row--selected" : ""
            }`}
            onClick={handleRowClick}
        >
            <td className='ecw-priority-pages-table__col-priority'>
                <CheckboxControl checked={isSelected} onChange={onToggle} />
            </td>
            <td className='ecw-priority-pages-table__col-title'>
                {renderHighlightedText(
                    title,
                    highlights?.title,
                    "ecw-search-highlight",
                )}
            </td>
            <td className='ecw-priority-pages-table__col-url'>
                {renderHighlightedText(
                    uri,
                    highlights?.uri,
                    "ecw-search-highlight",
                )}
            </td>
            <td className='ecw-priority-pages-table__col-status'>
                <code className={`is-post-${page.status}`}>{page.status}</code>
            </td>
        </tr>
    );
}
