// 서버·클라이언트 공용 순수 유틸. 'use client' 지시어 금지.

export function formatDate(dateString: string|null): string {
	if (!dateString) {
		return '-';
	}

	const date = new Date(dateString);
	const now = new Date();
	const diffMs = now.getTime() - date.getTime();
	const diffSec = Math.floor(diffMs / 1000);
	const diffMin = Math.floor(diffSec / 60);
	const diffHour = Math.floor(diffMin / 60);
	const diffDay = Math.floor(diffHour / 24);
	const diffWeek = Math.floor(diffDay / 7);
	const diffMonth = Math.floor(diffDay / 30);
	const diffYear = Math.floor(diffDay / 365);

	if (diffSec < 60) return '방금 전';
	if (diffMin < 60) return `${diffMin}분 전`;
	if (diffHour < 24) return `${diffHour}시간 전`;
	if (diffDay < 7) return `${diffDay}일 전`;
	if (diffWeek < 5) return `${diffWeek}주 전`;
	if (diffMonth < 12) return `${diffMonth}개월 전`;
	return `${diffYear}년 전`;
}

export function getDateTime(dateString: string|null): string {
	if (!dateString) {
		return '-';
	}

	const date = new Date(dateString);

	return date.toLocaleString('ko-KR', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit',
		hour12: false
	}).replace(/\. /g, '.').replace(/\.(\d{2}:)/, ' $1');
}

export function isDateOverdue(dateString: string|null, days = 0): boolean {
	if (!dateString) {
		return false;
	}

	const limitDate = new Date(new Date(dateString));
	limitDate.setDate(limitDate.getDate() + days);

	return (new Date()) > limitDate;
}

/** Date → "yyyy.MM.dd HH:mm" (datetime-local 대체 입력 표시용) */
export function formatDateInput(date: Date): string {
	const y = date.getFullYear();
	const m = String(date.getMonth() + 1).padStart(2, '0');
	const d = String(date.getDate()).padStart(2, '0');
	const h = String(date.getHours()).padStart(2, '0');
	const min = String(date.getMinutes()).padStart(2, '0');
	return `${y}.${m}.${d} ${h}:${min}`;
}

/** "yyyy.MM.dd HH:mm" → ISO string. 실패 시 빈 문자열 */
export function parseDateInput(str: string): string {
	const match = str.match(/^(\d{4})\.(\d{2})\.(\d{2})\s+(\d{2}):(\d{2})$/);
	if (!match) {
		return '';
	}
	const [, y, m, d, h, min] = match;
	const date = new Date(+y, +m - 1, +d, +h, +min);
	if (isNaN(date.getTime())) {
		return '';
	}
	return date.toISOString();
}