/**
 * Alpine.js Entry Point (bundled)
 *
 * Import Alpine, đăng ký tất cả components, rồi start.
 * Bundle thành public/build/alpine.js.
 */
import Alpine from 'alpinejs';

// Core components
import { registerModal } from './core/modal';
import { registerNotifications } from './core/notifications';
import { registerSidebar } from './core/sidebar';
import { registerDropdown } from './core/dropdown';
import { registerSelectAllCheckbox, tabularMixin } from './core/table';
import { registerPagination } from './core/pagination';
import { registerColumnVisibility } from './core/columnVisibility';
import { registerScrollToTop } from './core/scrollToTop';
import { registerNotesChat } from './core/notes';

// Page components
import { registerCampaignsPage } from './pages/campaigns';
import { registerCampaignBriefModal } from './pages/campaign-brief';
import { registerCampaignDetailPage } from './pages/campaign-detail';
import { registerStaffPage } from './pages/staff';
import { registerCreatorPage } from './pages/creator';
import { registerVideosPage } from './pages/videos';
import { registerReportsPage } from './pages/reports';
import { registerDashboardPage } from './pages/dashboard';
import { registerProfilePage } from './pages/profile';
import { registerAnalysisPage } from './pages/analysis';
import { registerLiveAnalysisPage } from './pages/live-analysis';
import { registerCreatorAnalysisPage } from './pages/creator-analysis';
import { registerTasksPage } from './pages/tasks';
import { registerBookingSopPage } from './pages/booking-sop';

// Shared helpers
import { initContactPopover, initDescriptionPopover, initPortalTooltip, buildStatusBadgeHtml, buildSocialLinksHtml, buildContactButtonHtml, buildDescriptionToggleHtml, buildClassificationBadgeHtml, escapeHtml, formatNumber, formatNumberTyping, unformatNumber, cleanNumberForSubmit, onNumberInput } from './helpers';

// Date utilities (single source of truth)
import { formatDate as _fmtDate, formatDateTime } from './utils/date';

// Message constants tập trung
import messages from './messages';
window.MSG = messages;

// Utility chống double-click submit
import { withSubmitGuard, resetAllSubmitting } from './utils/antiDoubleClick';
window.withSubmitGuard = withSubmitGuard;
window.resetAllSubmitting = resetAllSubmitting;

// Global helper render badge ghi chú trong bảng
window.renderNotesBadgeHtml = function (koc) {
    // [FIX] Dùng booking_notes_count thay vì booking_notes.length
    // Vì Phase 1 đã set booking_notes = [] (lazy load), count được lưu riêng
    const count = parseInt(koc?.booking_notes_count ?? 0, 10);
    const bookingId = koc?.id || '';
    const name = koc?.creator_name || koc?.koc?.creator_name || '...';
    const attrs = 'data-notes-booking="' + escapeHtml(bookingId) + '" data-notes-name="' + escapeHtml(name) + '"';
    if (count > 0) {
        return '<span class="notes-badge notes-badge--has-notes" ' + attrs + '>💬 ' + count + '</span>';
    }
    return '<span class="notes-badge notes-badge--empty" ' + attrs + '>💬</span>';
};

// Global helpers cho Blade components dùng qua x-html
window.statusBadgeHtml = function (value, enumName) {
    const list = window.__enums?.[enumName] || [];
    return buildStatusBadgeHtml(value, list);
};
window.buildSocialLinksHtml = buildSocialLinksHtml;
window.buildContactButtonHtml = buildContactButtonHtml;
window.buildClassificationBadgeHtml = buildClassificationBadgeHtml;
window.buildDescriptionToggleHtml = buildDescriptionToggleHtml;

// Global helpers cho Staff page (roleLabel, formatDate dùng trong x-ui.tabular render)
window.roleLabel = function (r) {
    const labels = { admin: 'Admin', staff: 'Nhân viên', owner: 'Chủ sở hữu' };
    return labels[r] || r || 'Không xác định';
};
window.formatDate = _fmtDate;
window.formatDateTime = formatDateTime;

// Global helpers cho number formatting (dùng trong @input, :value, và tabular type=number)
window.formatNumber = formatNumber;
window.formatNumberTyping = formatNumberTyping;
window.unformatNumber = unformatNumber;
window.cleanNumberForSubmit = cleanNumberForSubmit;
window.onNumberInput = onNumberInput;

// Register tất cả components
registerModal(Alpine);
registerNotifications(Alpine);
registerSidebar(Alpine);
registerDropdown(Alpine);
registerSelectAllCheckbox(Alpine);
registerPagination(Alpine);
registerColumnVisibility(Alpine);
registerScrollToTop(Alpine);
registerNotesChat(Alpine);
registerCampaignsPage(Alpine);
registerCampaignBriefModal(Alpine);
registerCampaignDetailPage(Alpine);
registerStaffPage(Alpine);
registerCreatorPage(Alpine);
registerVideosPage(Alpine);
registerReportsPage(Alpine);
registerDashboardPage(Alpine);
registerProfilePage(Alpine);
registerAnalysisPage(Alpine);
registerLiveAnalysisPage(Alpine);
registerCreatorAnalysisPage(Alpine);
registerTasksPage(Alpine);
registerBookingSopPage(Alpine);

// Start Alpine
window.Alpine = Alpine;
window.tabularMixin = tabularMixin;
Alpine.start();

// Global click delegation cho notes badge — mở chat modal
document.addEventListener('click', function (e) {
    const badge = e.target.closest('[data-notes-booking]');
    if (!badge) return;
    const bookingId = badge.dataset.notesBooking;
    const name = badge.dataset.notesName || '...';
    window.dispatchEvent(new CustomEvent('open-notes-chat', { detail: { bookingId, name } }));
    e.stopPropagation();
});

// Khởi tạo contact popover toàn cục
initContactPopover();

// Khởi tạo description popover toàn cục
initDescriptionPopover();

// Khởi tạo portal tooltip toàn cục cho các cột tiêu đề (data-tooltip)
initPortalTooltip();
