/**
 * tenantLoader.js: Dynamically applies branding and multi-tenant settings.
 */

async function loadTenantBranding() {
    // Determine tenant from URL (e.g., ?tenant=sharma-clinic) or localStorage
    const urlParams = new URLSearchParams(window.location.search);
    let tenantId = urlParams.get('tenant') || localStorage.getItem('Curio_tenant') || 'default';
    
    // Save to localStorage for persistence across pages
    localStorage.setItem('Curio_tenant', tenantId);

    try {
        const response = await fetch(`/api/config/${tenantId}`);
        const config = await response.json();

        applyBranding(config);
    } catch (error) {
        console.error("Failed to load tenant branding:", error);
    }
}

function applyBranding(config) {
    // 1. Apply CSS Variables for dynamic coloring
    document.documentElement.style.setProperty('--primary', config.primaryColor);
    document.documentElement.style.setProperty('--secondary', config.secondaryColor);

    // 2. Update UI Elements (Logo, Name)
    const logoIcons = document.querySelectorAll('.logo-icon');
    const logoTexts = document.querySelectorAll('.logo-text, .header-title h1, .auth-logo h1');
    const hospitalNames = document.querySelectorAll('.hospital-name, .logo-text');

    logoIcons.forEach(icon => icon.innerText = config.logo);
    
    // Update Document Title
    document.title = `${config.name} | Curio`;

    // Update instances of hospital name in text
    document.querySelectorAll('[data-tenant-name]').forEach(el => {
        el.innerText = config.name;
    });

    console.log(`Branding applied for: ${config.name}`);
}

// Auto-load on script include
document.addEventListener('DOMContentLoaded', loadTenantBranding);
