import { __ } from './i18n';
import type { CommentStatus, ReviewComment } from '../types';

export interface CommentPageGroup {
	url: string;
	title: string;
	comments: ReviewComment[];
}

export function commentPageUrl(comment: ReviewComment): string {
	return reviewPageUrl(comment.anchor?.url || comment.url || '');
}

/**
 * Review controls are navigation state rather than part of the reviewed page.
 * Older local comments may have captured them in their anchor URL, so
 * normalise both historical and newly-created records before grouping pins.
 */
function reviewPageUrl(value: string): string {
	if (!value) return '';
	try {
		const url = new URL(value, window.location.origin);
		url.hash = '';
		url.searchParams.delete('review');
		url.searchParams.delete('commentmate-mode');
		url.searchParams.delete('commentmate-focus');
		url.searchParams.delete('commentmate-focus-kind');
		return url.toString();
	} catch {
		return value;
	}
}

export function commentPageTitle(comment: ReviewComment): string {
	const explicit = (comment.pageTitle || comment.anchor?.title || '').trim();
	if (explicit) return explicit;

	const url = commentPageUrl(comment);
	if (!url) return __('Reviewed page', 'commentmate');
	try {
		const parsed = new URL(url);
		return parsed.pathname === '/' ? parsed.host : `${parsed.host}${parsed.pathname}`;
	} catch {
		return url;
	}
}

export function groupCommentsByPage(comments: ReviewComment[], filter: CommentStatus, temporarilyVisibleIds: Set<number> = new Set()): CommentPageGroup[] {
	const groups = new Map<string, CommentPageGroup>();

	for (const comment of comments) {
		if (comment.status !== filter && !temporarilyVisibleIds.has(comment.id)) continue;
		const url = commentPageUrl(comment);
		const key = url || `comment-${comment.id}`;
		const group = groups.get(key) ?? { url, title: commentPageTitle(comment), comments: [] };
		group.comments.push(comment);
		groups.set(key, group);
	}

	return Array.from(groups.values());
}

export function commentText(value: string): string {
	return value.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
}

export function commentSnippet(value: string): string {
	return commentText(value).slice(0, 105);
}
