// pages/ProfilePage.ts
import { SplitColumnLayout } from '../layouts/SplitColumnLayout';
import { ProfileWidget } from '../widgets/ProfileWidget';
import { StudentFinancialWidget } from '../widgets/StudentFinancialWidget';
import { PostFeedWidget } from '../widgets/PostFeedWidget';
import { AccountSettingsWidget } from '../widgets/AccountSettingsWidget';
import { Modal } from '../components/Modal';
import { createElement } from '../utils/utils';

let accountSettingsModalInstance: Modal | null = null; // Keep track of modal instance

export const renderProfilePage = () => {
    const layout = new SplitColumnLayout();
    const sidebar = createElement('div');

    const profileWidget = new ProfileWidget();
    const financesWidget = new StudentFinancialWidget('mockUserId');
    const postFeedWidget = new PostFeedWidget();

    sidebar.appendChild(profileWidget.render());
    sidebar.appendChild(financesWidget.render());

    layout.setSidebarContent(sidebar);
    layout.setContentAreaContent(postFeedWidget.render());

    const appElement = document.querySelector<HTMLDivElement>('#app');
    if (appElement) {
        appElement.innerHTML = ''; // Clear existing content
        appElement.appendChild(layout.render());

        // Handle 'Account settings' link click from TopBar or ProfileWidget
        const accountSettingsLinks = document.querySelectorAll('[data-action="open-account-settings"]');
        accountSettingsLinks.forEach(link => {
            link.addEventListener('click', (event) => {
                event.preventDefault(); // Prevent default link behavior
                if (!accountSettingsModalInstance) {
                    accountSettingsModalInstance = new Modal();
                    const settingsWidget = new AccountSettingsWidget(() => {
                        accountSettingsModalInstance?.hide(); // Callback to hide modal after settings update
                    });
                    accountSettingsModalInstance.setWidget(settingsWidget);
                }
                accountSettingsModalInstance.show();
            });
        });
    }
};