<?php
$startTime = microtime(true);
$publicDir = realpath($_SERVER['DOCUMENT_ROOT']);
$customCssPath = __DIR__ . '/../styles/base.css';
$defaultCssPath = __DIR__ . '/../../default/styles/base.css';
$cssPath = file_exists($customCssPath) ? $customCssPath : $defaultCssPath;
$cssUrl = file_exists($customCssPath) ? '/app/styles/base.css' : '/app/default-styles/base.css';
$cssHash = file_exists($cssPath) ? hash_file('md5', $cssPath) : 'file_not_found';
if (isset($GLOBALS['_SERVER']['SCRIPT_FILENAME'])) { $includingFile = $_SERVER['SCRIPT_FILENAME']; }
if (!empty($includingFile)) { $pageName = pathinfo($includingFile, PATHINFO_FILENAME); }
if (!in_array(basename(dirname($includingFile)), ['latest', 'live', 'frozen']) && basename(dirname($includingFile)) !== '') { $dirName = basename(dirname($includingFile)); }
function getActiveClass($href) { return rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/') === rtrim($href, '/') ? 'active' : ''; }
?>

<!DOCTYPE html>
<html lang="<?= htmlspecialchars($currentLang ?? 'no') ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <?php
    // Prepare social media metadata
    $siteTitle = 'Stopp lidelsen';
    $fullTitle = !empty($pageTitle) ? htmlspecialchars($pageTitle) . ' - ' . $siteTitle : $siteTitle;
    $description = !empty($metaDescription) ? htmlspecialchars($metaDescription) : 'Vi arbeider for at pasienter som kan ha nytte av medisinsk cannabis skal motta likeverdig og trygg behandling med oppfølging fra lege.';
    $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    // Determine social media image
    $socialImage = null;
    if (!empty($socialImageUrl)) {
        // Use provided social image URL
        $socialImage = $socialImageUrl;
    } elseif ($_SERVER['REQUEST_URI'] === '/' || rtrim($_SERVER['REQUEST_URI'], '/') === '') {
        // Use hero-bg.webp for frontpage
        $socialImage = '/hero-bg.webp';
    }
    
    // Convert relative URLs to absolute for social media
    if ($socialImage && !str_starts_with($socialImage, 'http')) {
        $socialImage = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $socialImage;
    }
    ?>
    
    <title><?= $fullTitle ?></title>
    
    <!-- Standard metadata -->
    <meta name="description" content="<?= $description ?>">
    <meta name="fediverse:creator" content="@stopplidelsen@oslo.town">
    
    <!-- Open Graph metadata (Facebook, Mastodon, etc.) -->
    <meta property="og:type" content="website">
    <meta property="og:site_name" content="<?= $siteTitle ?>">
    <meta property="og:title" content="<?= $fullTitle ?>">
    <meta property="og:description" content="<?= $description ?>">
    <meta property="og:url" content="<?= htmlspecialchars($currentUrl) ?>">
    <?php if ($socialImage): ?>
    <meta property="og:image" content="<?= htmlspecialchars($socialImage) ?>">
    <meta property="og:image:alt" content="<?= $fullTitle ?>">
    <?php endif; ?>
    
    <!-- Twitter Card metadata -->
    <meta name="twitter:card" content="<?= $socialImage ? 'summary_large_image' : 'summary' ?>">
    <meta name="twitter:title" content="<?= $fullTitle ?>">
    <meta name="twitter:description" content="<?= $description ?>">
    <?php if ($socialImage): ?>
    <meta name="twitter:image" content="<?= htmlspecialchars($socialImage) ?>">
    <meta name="twitter:image:alt" content="<?= $fullTitle ?>">
    <?php endif; ?>
    
    <link rel="stylesheet" href="<?= $cssUrl ?>?v=<?= $cssHash ?>">
    <?php if (!empty($pageCssUrl)): ?>
    <link rel="stylesheet" href="<?= $pageCssUrl ?>?v=<?= $pageCssHash ?? '' ?>">
    <?php endif; ?>
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.png" type="image/png">
    <link href="/app/fonts/pt-serif/pt-serif.css" rel="stylesheet">
    <?php if (!empty($feedUrl)): ?>
    <link rel="alternate" type="application/atom+xml" title="<?= htmlspecialchars($pageTitle ?? 'Feed') ?>" href="<?= htmlspecialchars($feedUrl) ?>">
    <?php endif; ?>
</head>

<body class="<?php if (isset($dirName)) echo 'section-' . $dirName . ' '; ?><?php if (isset($pageName)) echo 'page-' . $pageName; ?>">
    <div class="grid-container">
        <header class="contain">
            <div>
                <div class="logo">
                    <a href="<?= $langPrefix ?>/"><?php include $publicDir . '/logo.svg'; ?></a>
                </div>
                <nav>
                    <ul>
                        <li><a href="<?= $langPrefix ?>/" class="button <?php echo getActiveClass('/'); ?>"><?= htmlspecialchars($homeLabel ?? 'Forsiden') ?></a></li>
                        <?php if (!empty($navigation)): ?>
                            <?php foreach ($navigation as $item): ?>
                        <li><a href="<?= htmlspecialchars($item['url']) ?>" class="button <?php echo getActiveClass($item['url']); ?>"><?= htmlspecialchars($item['title']) ?></a></li>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        <?php
                        // Language switcher - show alternate language only
                        $currentLangCode = $currentLang ?? 'no';
                        $availableLanguages = $availableLangs ?? ['no', 'en'];
                        $langUrls = $languageUrls ?? [];
                        $trans = $translations ?? [];
                        
                        // Find the alternate language
                        $alternateLang = null;
                        foreach ($availableLanguages as $lang) {
                            if ($lang !== $currentLangCode) {
                                $alternateLang = $lang;
                                break;
                            }
                        }
                        
                        if ($alternateLang && isset($langUrls[$alternateLang])) {
                            // Get language name from translations
                            $alternateName = $trans["language_name_$alternateLang"] ?? strtoupper($alternateLang);
                        ?>
                        <li><a href="<?= htmlspecialchars($langUrls[$alternateLang]) ?>" 
                               class="button"
                               hreflang="<?= htmlspecialchars($alternateLang) ?>">
                            <?= htmlspecialchars($alternateName) ?>
                        </a></li>
                        <?php } ?>
                    </ul>
                </nav>
            </div>
        </header>

        <main>
            <?php echo $wrappedContent ?? $content ?? ''; ?>
        </main>

        <footer>
            <div class="contain">
                <?php if (!empty($trans['footer.social'])): ?>
                    <p><?= $trans['footer.social'] ?></p>
                <?php endif; ?>
                <?php $endTime = microtime(true); $pageLoadTime = round(($endTime - $startTime) * 1000, 2); ?>
                <?php if (!empty($trans['footer.handcoded'])): ?>
                    <p class="generated"><?= $trans['footer.handcoded'] ?> <?= $pageLoadTime ?><?= $trans['footer.page_time'] ?? 'ms' ?></p>
                <?php endif; ?>
                <p>
                    <?php
                    $langUrls = $languageUrls ?? [];
                    foreach ($availableLanguages as $index => $lang) {
                        $url = $langUrls[$lang] ?? '/';
                        
                        // Get language name: use language_name from that language's translations
                        if ($lang === $currentLangCode) {
                            $langName = $trans['language_name'] ?? strtoupper($lang);
                        } else {
                            $langName = $trans["language_name_$lang"] ?? strtoupper($lang);
                        }
                        
                        if ($index > 0) echo ' | ';
                        echo '<a href="' . htmlspecialchars($url) . '" hreflang="' . htmlspecialchars($lang) . '">' . htmlspecialchars($langName) . '</a>';
                    }
                    ?>
                </p>
            </div>
        </footer>
    </div>
    <img style="display:none" src="https://stopplidelsen.goatcounter.com/count?p=<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?>">
</body>
</html>
