(function () {
    window.AgentFrontendModules = window.AgentFrontendModules || {};

    window.AgentFrontendModules.createIdentityModule = function createIdentityModule(deps) {
        function ensurePaneStructure() {
            let soulPane = deps.identityContainer.querySelector('#identity-soul-pane');
            let userPane = deps.identityContainer.querySelector('#identity-user-pane');
            if (soulPane && userPane) return { soulPane, userPane };

            deps.identityContainer.innerHTML = `
                <div class="identity-sub-tabs" style="display:flex;gap:4px;padding:8px 10px 4px;border-bottom:1px solid var(--border);margin-bottom:6px">
                    <button class="btn-xs identity-sub-tab active" data-identity-tab="soul" type="button">AI Soul</button>
                    <button class="btn-xs identity-sub-tab" data-identity-tab="user" type="button">User Identity</button>
                </div>
                <div id="identity-soul-pane"></div>
                <div id="identity-user-pane" style="display:none"></div>`;

            soulPane = deps.identityContainer.querySelector('#identity-soul-pane');
            userPane = deps.identityContainer.querySelector('#identity-user-pane');
            return { soulPane, userPane };
        }

        function formatInline(text) {
            const safe = deps.escapeHtml(text || '');
            return safe
                .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
                .replace(/`([^`]+)`/g, '<code>$1</code>');
        }

        function renderMarkdown(text, emptyFallback) {
            const raw = String(text || '').trim();
            if (!raw) {
                return `<p class="identity-empty">${deps.escapeHtml(emptyFallback)}</p>`;
            }

            const lines = raw.split(/\r?\n/);
            const html = [];
            let listType = '';

            function closeList() {
                if (!listType) return;
                html.push(listType === 'ol' ? '</ol>' : '</ul>');
                listType = '';
            }

            for (const line of lines) {
                const trimmed = line.trim();
                if (!trimmed) {
                    closeList();
                    continue;
                }

                const headingMatch = trimmed.match(/^(#{1,6})\s+(.+)$/);
                if (headingMatch) {
                    closeList();
                    const level = Math.min(6, headingMatch[1].length + 1);
                    html.push(`<h${level} class="identity-heading">${formatInline(headingMatch[2])}</h${level}>`);
                    continue;
                }

                const bulletMatch = trimmed.match(/^[-*]\s+(.+)$/);
                if (bulletMatch) {
                    if (listType !== 'ul') {
                        closeList();
                        html.push('<ul class="identity-list">');
                        listType = 'ul';
                    }
                    html.push(`<li>${formatInline(bulletMatch[1])}</li>`);
                    continue;
                }

                const orderedMatch = trimmed.match(/^(\d+)\.\s+(.+)$/);
                if (orderedMatch) {
                    if (listType !== 'ol') {
                        closeList();
                        html.push('<ol class="identity-list identity-list-ordered">');
                        listType = 'ol';
                    }
                    html.push(`<li>${formatInline(orderedMatch[2])}</li>`);
                    continue;
                }

                closeList();
                html.push(`<p class="identity-paragraph">${formatInline(trimmed)}</p>`);
            }

            closeList();
            return html.join('') || `<p class="identity-empty">${deps.escapeHtml(emptyFallback)}</p>`;
        }

        function renderError(message) {
            const { soulPane, userPane } = ensurePaneStructure();
            const safeMessage = deps.escapeHtml(message || 'Could not load identity data.');
            if (soulPane) {
                soulPane.innerHTML = `<div class="sessions-empty">${safeMessage}</div>`;
                soulPane.style.display = '';
            }
            if (userPane) {
                userPane.innerHTML = `<div class="sessions-empty">${safeMessage}</div>`;
                userPane.style.display = 'none';
            }
            deps.identityContainer.querySelectorAll('.identity-sub-tab').forEach((button, index) => {
                button.classList.toggle('active', index === 0);
            });
        }

        function bindTabSwitching(soulPane, userPane) {
            deps.identityContainer.querySelectorAll('.identity-sub-tab').forEach((button) => {
                button.addEventListener('click', () => {
                    deps.identityContainer.querySelectorAll('.identity-sub-tab').forEach((item) => item.classList.remove('active'));
                    button.classList.add('active');
                    const tab = button.dataset.identityTab;
                    if (soulPane) soulPane.style.display = tab === 'soul' ? '' : 'none';
                    if (userPane) userPane.style.display = tab === 'user' ? '' : 'none';
                });
            });
        }

        function bindEditActions() {
            deps.identityContainer.querySelectorAll('.identity-edit-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    const target = button.dataset.target;
                    const card = target === 'soul'
                        ? deps.identityContainer.querySelector('#identity-soul-card')
                        : deps.identityContainer.querySelector('#identity-user-card');
                    card.querySelector('.identity-view-body').style.display = 'none';
                    card.querySelector('.identity-edit-form').style.display = 'block';
                    button.style.display = 'none';
                });
            });

            deps.identityContainer.querySelectorAll('.identity-save-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    const target = button.dataset.target;
                    const card = target === 'soul'
                        ? deps.identityContainer.querySelector('#identity-soul-card')
                        : deps.identityContainer.querySelector('#identity-user-card');
                    const textarea = card.querySelector('.identity-edit-textarea');
                    const content = textarea.value;
                    button.disabled = true;
                    button.textContent = 'Saving…';
                    deps.authFetchJson(`${deps.backendUrl}/api/identity/${target}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ content }),
                    })
                        .then((response) => {
                            if (response.ok) loadIdentity();
                            else alert(response.error || `Failed to save ${target}.md`);
                        })
                        .catch(() => alert(`Failed to save ${target}.md`));
                });
            });

            deps.identityContainer.querySelectorAll('.identity-cancel-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    loadIdentity();
                });
            });

            const clearButton = deps.identityContainer.querySelector('.clear-user-btn');
            if (clearButton) {
                clearButton.addEventListener('click', () => {
                    if (!confirm('Are you sure you want to clear all user profile data? This cannot be undone.')) return;
                    deps.authFetchJson(`${deps.backendUrl}/api/identity/user`, { method: 'DELETE' })
                        .then((response) => {
                            if (response.ok) loadIdentity();
                            else alert(response.error || 'Failed to clear user profile.');
                        })
                        .catch(() => alert('Failed to clear user profile.'));
                });
            }
        }

        function renderIdentity(data) {
            const soul = String(data.soul || '').trim();
            const user = String(data.user || '').trim();
            const soulRendered = renderMarkdown(soul, '(soul.md is empty or missing)');
            const userRendered = renderMarkdown(user, '(user.md is empty or missing)');
            const hasUserContent = user.length > 0 && user !== '# User Profile';

            const { soulPane, userPane } = ensurePaneStructure();

            if (soulPane) {
                soulPane.innerHTML = `
                <div class="memory-item" id="identity-soul-card">
                    <div class="memory-item-header">
                        <span class="memory-step-badge">SOUL</span>
                        <span class="memory-item-step">soul.md</span>
                        <button class="btn-xs identity-edit-btn" data-target="soul" title="Edit soul.md">Edit</button>
                    </div>
                    <div class="memory-item-body identity-view-body identity-rich-body">${soulRendered}</div>
                    <div class="identity-edit-form" style="display:none;">
                        <textarea class="identity-edit-textarea" data-target="soul">${deps.escapeHtml(soul)}</textarea>
                        <div class="identity-edit-actions">
                            <button class="btn-xs primary identity-save-btn" data-target="soul">Save</button>
                            <button class="btn-xs identity-cancel-btn" data-target="soul">Cancel</button>
                        </div>
                    </div>
                </div>`;
            }

            if (userPane) {
                userPane.innerHTML = `
                <div class="memory-item" id="identity-user-card">
                    <div class="memory-item-header">
                        <span class="memory-step-badge">USER</span>
                        <span class="memory-item-step">user.md</span>
                        <button class="btn-xs identity-edit-btn" data-target="user" title="Edit user.md">Edit</button>
                        ${hasUserContent ? '<button class="btn-xs danger clear-user-btn" title="Clear all user profile data">Clear</button>' : ''}
                    </div>
                    <div class="memory-item-body identity-view-body identity-rich-body">${userRendered}</div>
                    <div class="identity-edit-form" style="display:none;">
                        <textarea class="identity-edit-textarea" data-target="user">${deps.escapeHtml(user)}</textarea>
                        <div class="identity-edit-actions">
                            <button class="btn-xs primary identity-save-btn" data-target="user">Save</button>
                            <button class="btn-xs identity-cancel-btn" data-target="user">Cancel</button>
                        </div>
                    </div>
                    <div class="identity-hint" style="font-size:.72rem;opacity:.55;margin-top:6px;padding:0 13px 8px;">User insights are collected automatically from your conversations.</div>
                </div>`;
            }

            bindTabSwitching(soulPane, userPane);
            if (deps.memoryCount) deps.memoryCount.textContent = '';
            bindEditActions();
        }

        function loadIdentity() {
            deps.authFetchJson(`${deps.backendUrl}/api/identity`)
                .then((data) => renderIdentity(data || {}))
                .catch(() => {
                    renderError('Could not load soul.md / user.md data.');
                });
        }

        return {
            loadIdentity,
        };
    };
})();