<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';

function dbnToolsSafeReturn(mixed $value, string $default = '/'): string
{
    $return = trim((string)$value);
    if ($return === '') {
        return $default;
    }
    if (!str_starts_with($return, '/') || str_starts_with($return, '//')) {
        return $default;
    }
    if (preg_match('/[\r\n]/', $return)) {
        return $default;
    }
    return $return;
}

$uiLang = dbnToolsCurrentLanguage();
$returnPath = dbnToolsSafeReturn($_GET['return'] ?? '/', '/');

// Handle SSO token from dobetternorge.no
if (isset($_GET['sso']) && !dbnToolsIsAuthenticated()) {
    $ssoSecret = (string) dbnToolsEnv('DBN_SSO_SECRET', '');
    if ($ssoSecret !== '') {
        $tokenData = dbnToolsValidateSsoToken((string)$_GET['sso'], $ssoSecret);
        if ($tokenData !== null) {
            session_regenerate_id(true);
            $_SESSION['dbn_tools_authenticated']    = true;
            $_SESSION['dbn_tools_authenticated_at'] = time();
            $_SESSION['dbn_tools_sso_uid']          = (int)$tokenData['uid'];
            $_SESSION['dbn_tools_user_id']          = (int)$tokenData['uid'];
            $_SESSION['dbn_tools_user_email']       = (string)$tokenData['email'];
            $_SESSION['dbn_tools_user_role']        = 'sso';
            $_SESSION['dbn_tools_tier']             = (string)($tokenData['tier'] ?? 'free');
            // Send to workbench directly after SSO; honour a specific return path if set
            header('Location: ' . ($returnPath === '/' ? '/dashboard.php' : $returnPath));
            exit;
        }
    }
    header('Location: https://dobetternorge.no/account.php?error=' . urlencode('Session expired. Please log in and try again.'));
    exit;
}

$isAuthed    = dbnToolsIsAuthenticated();
$userEmail   = $isAuthed ? (string)($_SESSION['dbn_tools_user_email'] ?? '') : '';
$tools       = dbnToolsLaunchedTools($uiLang);
$workbench   = dbnToolsWorkbenchMeta($uiLang);
$langPath    = '/';
$toolsLogin  = 'https://dobetternorge.no/tools-login.php?return=' . urlencode($returnPath);
$registerUrl = 'https://dobetternorge.no/register.php';

require_once __DIR__ . '/includes/tool-svgs.php';
?>
<!doctype html>
<html lang="<?= htmlspecialchars($uiLang) ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars(dbnToolsT('meta_title', $uiLang)) ?></title>
    <meta name="description" content="AI legal preparation tools for Do Better Norge: transcribe, timeline, Barnevernet document analysis, advocate briefs, deep research, and corpus search.">
    <meta name="robots" content="index, follow">
    <link rel="canonical" href="https://tools.dobetternorge.no/">
    <meta property="og:title" content="<?= htmlspecialchars(dbnToolsT('meta_title', $uiLang)) ?>">
    <meta property="og:description" content="<?= htmlspecialchars(dbnToolsT('landing_sub', $uiLang)) ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://tools.dobetternorge.no/">
    <meta name="theme-color" content="#00205B">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Crimson+Pro:wght@400;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap">
    <link rel="stylesheet" href="assets/css/tools.css">
</head>
<body data-authenticated="<?= $isAuthed ? 'true' : 'false' ?>" class="lt-landing">
<script>
window.DBN_TOOLS_AUTHENTICATED = <?= $isAuthed ? 'true' : 'false' ?>;
window.DBN_TOOLS_LANG = <?= json_encode($uiLang, JSON_UNESCAPED_UNICODE) ?>;
</script>

<main id="publicLanding" class="dbn-public-tools">

    <header class="lt-nav">
        <a href="https://dobetternorge.no" class="lt-nav__brand">
            <picture>
                <source srcset="assets/images/logo-header.webp" type="image/webp">
                <img class="lt-nav__logo" src="assets/images/logo-header.png" alt="Do Better Norge" width="140" height="36" loading="eager">
            </picture>
            <span class="lt-nav__badge">Legal Tools</span>
        </a>
        <div class="lt-nav__right">
            <nav class="shell-lang-switcher" aria-label="Language">
<?php foreach (dbnToolsSupportedLanguages() as $langCode): ?>
                <a href="<?= htmlspecialchars($langPath . '?lang=' . $langCode . '&return=' . urlencode($returnPath)) ?>" class="<?= $langCode === $uiLang ? 'is-active' : '' ?>"><?= htmlspecialchars(dbnToolsLanguageLabel($langCode)) ?></a>
<?php endforeach; ?>
            </nav>
<?php if ($isAuthed): ?>
            <div class="lt-auth-nav">
                <span class="lt-auth-nav__email"><?= htmlspecialchars($userEmail) ?></span>
                <a href="/dashboard.php" class="lt-nav__cta lt-nav__cta--enter"><?= htmlspecialchars(dbnToolsT('enter_workbench', $uiLang)) ?> &rarr;</a>
            </div>
<?php else: ?>
            <a href="#access" class="lt-nav__cta"><?= htmlspecialchars(dbnToolsT('primary_access', $uiLang)) ?></a>
<?php endif; ?>
        </div>
    </header>

    <section class="lt-hero">
        <div class="lt-hero__inner">
            <p class="lt-hero__kicker">AI Legal Tools &middot; Norway &middot; Free for members</p>
            <h1 class="lt-hero__title"><?= htmlspecialchars(dbnToolsT('landing_title', $uiLang)) ?></h1>
            <p class="lt-hero__body"><?= htmlspecialchars(dbnToolsT('landing_sub', $uiLang)) ?></p>
            <div class="lt-hero__stats">
                <div class="lt-hero__stat">
                    <strong>23</strong>
                    <span><?= htmlspecialchars(dbnToolsT('stat_echr', $uiLang)) ?></span>
                </div>
                <div class="lt-hero__stat">
                    <strong>1,731</strong>
                    <span><?= htmlspecialchars(dbnToolsT('stat_tribunal', $uiLang)) ?></span>
                </div>
                <div class="lt-hero__stat">
                    <strong>20+</strong>
                    <span><?= htmlspecialchars(dbnToolsT('stat_pending', $uiLang)) ?></span>
                </div>
                <div class="lt-hero__stat">
                    <strong>220K</strong>
                    <span>Legal passages indexed</span>
                </div>
            </div>
<?php if ($isAuthed): ?>
            <div class="lt-hero__auth-cta">
                <span class="lt-hero__auth-check" aria-hidden="true">&#10003;</span>
                <span class="lt-hero__auth-label"><?= htmlspecialchars(dbnToolsT('signed_in_as', $uiLang)) ?> <?= htmlspecialchars($userEmail) ?></span>
                <a href="/dashboard.php" class="lt-hero__enter-btn"><?= htmlspecialchars(dbnToolsT('enter_workbench', $uiLang)) ?> &rarr;</a>
            </div>
<?php else: ?>
            <a href="#tools" class="lt-hero__cta-link">Explore tools &#x2193;</a>
<?php endif; ?>
        </div>
    </section>

    <section class="lt-tools" id="tools">
        <div class="lt-tools__header">
            <p class="lt-tools__eyebrow"><?= htmlspecialchars(dbnToolsT('tools_title', $uiLang)) ?></p>
            <h2 class="lt-tools__title">Built for families navigating a complex system.</h2>
            <p class="lt-tools__sub">Seven purpose-built AI tools &mdash; from audio transcription to deep legal research. Every tool processes your documents in memory and discards them when you&rsquo;re done.</p>
        </div>
        <div class="lt-grid">
            <a class="lt-card lt-card--workbench" href="<?= $isAuthed ? '/workbench.php' : '#access' ?>" data-tool="workbench">
                <div class="lt-card__art workbench-entry-art" aria-hidden="true">
                    <span>WB</span>
                </div>
                <div class="lt-card__body">
                    <p class="lt-card__badge"><?= htmlspecialchars($workbench['badge']) ?></p>
                    <h3 class="lt-card__title"><?= htmlspecialchars($workbench['label']) ?></h3>
                    <p class="lt-card__desc"><?= htmlspecialchars($workbench['description']) ?></p>
                    <span class="lt-card__arrow"><?= htmlspecialchars($isAuthed ? dbnToolsT('enter_workbench', $uiLang) : dbnToolsT('primary_access', $uiLang)) ?> &#x2192;</span>
                </div>
            </a>
<?php foreach ($tools as $slug => $item): ?>
            <a class="lt-card" href="preview.php?tool=<?= htmlspecialchars($slug) ?>" data-tool="<?= htmlspecialchars($slug) ?>">
                <div class="lt-card__art" aria-hidden="true">
                    <?= $toolSvgs[$slug] ?? '' ?>
                </div>
                <div class="lt-card__body">
                    <p class="lt-card__badge"><?= htmlspecialchars($item['badge']) ?></p>
                    <h3 class="lt-card__title"><?= htmlspecialchars($item['label']) ?></h3>
                    <p class="lt-card__desc"><?= htmlspecialchars($item['description']) ?></p>
                    <span class="lt-card__arrow">Learn more &#x2192;</span>
                </div>
            </a>
<?php endforeach; ?>
        </div>
<?php if ($isAuthed): ?>
        <div class="lt-tools__enter-strip">
            <a href="/dashboard.php" class="lt-access-btn"><?= htmlspecialchars(dbnToolsT('enter_workbench', $uiLang)) ?> &rarr;</a>
        </div>
<?php endif; ?>
    </section>

    <section class="lt-trust">
        <div class="lt-trust__grid">
            <div class="lt-trust__item">
                <h3><?= htmlspecialchars(dbnToolsT('cause_title', $uiLang)) ?></h3>
                <p><?= htmlspecialchars(dbnToolsT('cause_text', $uiLang)) ?></p>
            </div>
            <div class="lt-trust__item">
                <h3><?= htmlspecialchars(dbnToolsT('privacy_title', $uiLang)) ?></h3>
                <p><?= htmlspecialchars(dbnToolsT('privacy_text', $uiLang)) ?></p>
            </div>
            <div class="lt-trust__item">
                <h3><?= htmlspecialchars(dbnToolsT('source_title', $uiLang)) ?></h3>
                <p><?= htmlspecialchars(dbnToolsT('source_text', $uiLang)) ?></p>
            </div>
        </div>
        <div style="text-align:center;margin-top:2rem">
            <a href="/why-ours.php" style="display:inline-block;padding:.6rem 1.4rem;border:1.5px solid rgba(0,32,91,.25);border-radius:8px;font-size:.85rem;font-weight:600;color:var(--dbn-blue,#00205b);text-decoration:none;transition:border-color .2s,background .2s" onmouseover="this.style.background='rgba(0,32,91,.05)'" onmouseout="this.style.background=''">Why our tools give different answers than ChatGPT &rarr;</a>
        </div>
    </section>

<?php if (!$isAuthed): ?>
    <section id="access" class="lt-access lt-gate" aria-labelledby="ltGateTitle">
        <div class="lt-gate__grid">

            <div class="lt-gate__card lt-gate__card--member">
                <p class="lt-gate__card-eyebrow">Do Better Norge</p>
                <h2 class="lt-gate__card-title" id="ltGateTitle"><?= htmlspecialchars(dbnToolsT('member_card_title', $uiLang)) ?></h2>
                <p class="lt-gate__card-note"><?= htmlspecialchars(dbnToolsT('member_card_note', $uiLang)) ?></p>
                <a class="lt-access-btn" href="<?= htmlspecialchars($toolsLogin) ?>"><?= htmlspecialchars(dbnToolsT('primary_access', $uiLang)) ?></a>
                <details class="fallback-login">
                    <summary><?= htmlspecialchars(dbnToolsT('secondary_access', $uiLang)) ?></summary>
                    <form id="passcodeForm" class="passcode-form">
                        <label for="loginEmail"><?= htmlspecialchars(dbnToolsT('email', $uiLang)) ?></label>
                        <input id="loginEmail" name="email" type="email" autocomplete="username email" required>
                        <label for="loginPassword"><?= htmlspecialchars(dbnToolsT('password', $uiLang)) ?></label>
                        <div class="passcode-row">
                            <input id="loginPassword" name="password" type="password" autocomplete="current-password" required>
                            <button type="submit"><?= htmlspecialchars(dbnToolsT('sign_in', $uiLang)) ?></button>
                        </div>
                        <p id="gateStatus" class="form-status" role="status" aria-live="polite"></p>
                    </form>
                </details>
            </div>

            <div class="lt-gate__card lt-gate__card--register">
                <p class="lt-gate__card-eyebrow">Free membership</p>
                <h2 class="lt-gate__card-title"><?= htmlspecialchars(dbnToolsT('register_card_title', $uiLang)) ?></h2>
                <p class="lt-gate__card-note"><?= htmlspecialchars(dbnToolsT('register_card_note', $uiLang)) ?></p>
                <a class="lt-register-btn lt-register-btn--google" href="<?= htmlspecialchars($registerUrl . '?method=google') ?>">
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true" focusable="false">
                        <path d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615Z" fill="#4285F4"/>
                        <path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18Z" fill="#34A853"/>
                        <path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332Z" fill="#FBBC05"/>
                        <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58Z" fill="#EA4335"/>
                    </svg>
                    <?= htmlspecialchars(dbnToolsT('register_google', $uiLang)) ?>
                </a>
                <a class="lt-register-btn lt-register-btn--email" href="<?= htmlspecialchars($registerUrl) ?>">
                    <?= htmlspecialchars(dbnToolsT('register_email', $uiLang)) ?>
                </a>
            </div>

        </div>
    </section>
<?php endif; ?>

</main>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
<script src="assets/js/tools.js" defer></script>
</body>
</html>
