<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<!--<base href="/" />-->
    <style>
        :root {
            --font-stack: 'Inter', 'Noto Sans', sans-serif;
            --bg-color: #050505;
            --text-color: #050505;
        }

        body {
            margin: 0;
            background: var(--bg-color);
            color: var(--text-color);
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-family: var(--font-stack); 
            overflow: hidden;
        }

        h1 {
            font-weight: 700; 
            font-size: 8rem;
            margin: 0;
            letter-spacing: -0.04em;
            line-height: 1;
        }

        @media (max-width: 600px) {
            h1 { font-size: 4rem; }
        }
    </style>

	<!-- 1. LOAD SHARED LOGIC SYNCHRONOUSLY -->
	<script src="./vendor/@tandion/tenant@0.1.0/src/loader.js"></script>

	<!-- 2. SECURE CONFIG LOADER (Uses globals from ./src/loader.js) -->
	<script>
		(async () => {
			// Use constants/functions from ./config/loader.js
			const SALT = window.SALT || 'h3cr8';
			const getID = window.getID;
			const extractHostname = window.extractHostname;

			if (!getID || !extractHostname) {
				console.error("Critical: ./vendor/@tandion/tenant@0.1.0/src/loader.js failed to load.");
				return;
			}

			//const url = "https://app.example.com/index.html"; // Example with BRAND NAME
			const url = window.location.href;
			const hostname = extractHostname(url);

			// Helper: Inject DOM Elements
			const inject = (tag, attr = {}, parent = document.head) => {
				const el = document.createElement(tag);
				for (const k in attr) el.setAttribute(k, attr[k]);
				parent.appendChild(el);
				return el;
			};

			// Helper: Wait for DOM to be ready
			const ready = () => new Promise(r => document.readyState !== 'loading' ? r() : document.addEventListener('DOMContentLoaded', r));

			// --- CASCADING LOOKUP ---
			let config = null;

			// Generate hierarchy candidates: e.g. ["sub.domain.com", "domain.com", "com", ""]
			const candidates = [];
			if (hostname) {
				const labels = hostname.split('.');
				for (let i = 0; i < labels.length; i++) {
					candidates.push(labels.slice(i).join('.'));
				}
			}
			// Fallback: The empty string evaluates to the root hash (gtmu080g3r2e4eqoix3c6r1dw)
			candidates.push("");

			for (const domain of candidates) {
				try {
					const hash = await getID(domain, SALT);
					// Import config. The config file itself MUST resolve its own asset paths.
					config = (await import(`./vendor/@tandion/tenant@0.1.0/config/${hash}/config.js`)).default;
					if (config) {
						console.log(`Config loaded for '${domain}' (${hash})`);
						break;
					}
				} catch (e) {
					// alert(domain);
					// Config not found for this level, continue cascading up
				}
			}

			// --- APPLY ---
			if (config) {
				// 1. Expose Config Globally for UI Components (OmniBar, etc.)
				window.CONFIG = config;

				// 2. Set Meta Title (Browser Tab)
				// Priority: metaTitle -> title
				document.title = config.metaTitle || config.title;

				// 3. Set Theme Color
				document.documentElement.style.setProperty('--bg-app', config.color);

				if (config.manifest) inject('link', { rel: 'manifest', href: config.manifest });
				if (config.color) inject('meta', { name: 'theme-color', content: config.color });

				// --- DYNAMIC SVG ICON GENERATION ---
				// UPDATED LOGIC: Prioritize explicit Initials over inherited Icons.
				// This fixes the issue where spread syntax (...primary) causes specific configs
				// to inherit the fallback icon even when they defined 'initials'.

				const hasExplicitInitials = (typeof config.initials === 'string');

				if (hasExplicitInitials) {
					// 1. Explicit Initials (User wanted this)
					const initials = config.initials;
					const svgString = `
                    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
                    <circle cx="50" cy="50" r="50" fill="white"/>
                    <text x="50" y="50" font-family="sans-serif" font-weight="bold" font-size="60" text-anchor="middle" dominant-baseline="central" fill="black">${initials}</text>
                    </svg>
                `.trim();
					const svgDataUri = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
					inject('link', { rel: 'icon', type: 'image/svg+xml', href: svgDataUri });

				} else if (config.icon) {
					// 2. Explicit or Inherited Icon
					inject('link', { rel: 'icon', type: 'image/svg+xml', href: config.icon });

				} else {
					// 3. Fallback Generation (Initials from Title)
					const initials = (config.title || "").replace(/[^a-zA-Z0-9\.]/g, '').substring(0, 2).toUpperCase();
					const svgString = `
                    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
                    <circle cx="50" cy="50" r="50" fill="white"/>
                    <text x="50" y="50" font-family="sans-serif" font-weight="bold" font-size="60" text-anchor="middle" dominant-baseline="central" fill="black">${initials}</text>
                    </svg>
                `.trim();
					const svgDataUri = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
					inject('link', { rel: 'icon', type: 'image/svg+xml', href: svgDataUri });
				}

				// --- INJECT APP (Only on Success & Ready) ---
				await ready();
				const mainHeading = document.createElement('h1');
				mainHeading.textContent = config.appTitle;
				document.body.appendChild(mainHeading);
				//inject('script', { type: 'module', src: './src/app.js' }, document.body);
			}
		})();
	</script>

	<script type="module">

        const FONTS_TO_REGISTER = [
            './vendor/@tandion/fonts@0.1.0/inter@2025-12-24/700-normal/inter-700-normal.mjs',
        ];

        async function initFonts() {
            try {
                const imports = FONTS_TO_REGISTER.map(path => import(path));
                const modules = await Promise.all(imports);

                modules.forEach(m => m.load());
                
                console.log("Fonts registered. Browser will lazy-load binaries on demand.");
            } catch (e) {
                console.warn("Some font modules could not be loaded.", e);
            }
        }

        initFonts();
    </script>
</head>
<body>
</body>
</html>