<?php

declare(strict_types=1);

if (!function_exists('e')) {
    function e(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

function request_path(): string
{
    $uri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
    $path = parse_url($uri, PHP_URL_PATH);

    if (!is_string($path) || $path === '') {
        return '/';
    }

    return $path;
}

function is_https_request(): bool
{
    $https = strtolower((string) ($_SERVER['HTTPS'] ?? ''));
    $forwardedProto = strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''));
    $cfVisitor = (string) ($_SERVER['HTTP_CF_VISITOR'] ?? '');

    return $https === 'on'
        || $https === '1'
        || $forwardedProto === 'https'
        || str_contains($cfVisitor, '"scheme":"https"');
}

function safe_host(): string
{
    $host = strtolower((string) ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    $host = preg_replace('/:\d+\z/', '', $host) ?? 'localhost';
    $host = trim($host, '.');

    if ($host === '' || !preg_match('/\A[a-z0-9.-]{1,253}\z/', $host)) {
        return 'localhost';
    }

    return $host;
}

function canonical_url(): string
{
    $scheme = is_https_request() ? 'https' : 'http';

    return $scheme . '://' . safe_host() . '/';
}

$path = request_path();
$isWrongPath = !in_array($path, ['/', '/index.php'], true);
$_preCode = http_response_code();
$statusCode = (is_int($_preCode) && $_preCode >= 400) ? $_preCode : ($isWrongPath ? 404 : 200);
$nonce = bin2hex(random_bytes(16));
$brandName = 'Wrong URL';
$pageTitle = $isWrongPath ? '404 - Wrong URL' : 'Wrong URL';
$canonical = canonical_url();
$year = date('Y');

http_response_code($statusCode);
header('Content-Type: text/html; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: same-origin');
header('Permissions-Policy: accelerometer=(), autoplay=(), camera=(), encrypted-media=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=()');
header('Cross-Origin-Opener-Policy: same-origin');
header('Cross-Origin-Resource-Policy: same-origin');
header('X-Robots-Tag: ' . ($isWrongPath ? 'noindex, nofollow, noarchive' : 'index, follow'));
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if (is_https_request()) {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
}

$csp = [
    "default-src 'self'",
    "base-uri 'self'",
    "form-action 'none'",
    "frame-ancestors 'self'",
    "object-src 'none'",
    "img-src 'self' data:",
    "font-src 'self' data:",
    "style-src 'self' 'nonce-{$nonce}'",
    "script-src 'self' 'nonce-{$nonce}'",
    "connect-src 'self'",
    'upgrade-insecure-requests',
];
header('Content-Security-Policy: ' . implode('; ', $csp));

$schema = [
    '@context' => 'https://schema.org',
    '@type' => 'WebPage',
    'name' => $brandName,
    'url' => $canonical,
    'description' => 'Standalone wrong URL landing page for invalid, incomplete, or removed links.',
    'inLanguage' => 'en',
];
$schemaJson = json_encode(
    $schema,
    JSON_UNESCAPED_SLASHES
    | JSON_UNESCAPED_UNICODE
    | JSON_HEX_TAG
    | JSON_HEX_AMP
    | JSON_HEX_APOS
    | JSON_HEX_QUOT
    | JSON_THROW_ON_ERROR
);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($pageTitle); ?></title>
    <meta name="description" content="A clean fallback page for invalid, incomplete, or removed links.">
    <meta name="robots" content="<?= $isWrongPath ? 'noindex,nofollow,noarchive' : 'index,follow'; ?>">
    <link rel="canonical" href="<?= e($canonical); ?>">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">
    <meta name="theme-color" content="#ff5a0a">
    <style nonce="<?= e($nonce); ?>">
        :root{--bg:#fffaf6;--surface:rgba(255,255,255,.86);--surface-strong:#fff;--text:#171717;--muted:#575757;--soft:#fff0e7;--line:rgba(255,90,10,.18);--orange:#ff5a0a;--orange-2:#f24b00;--shadow:0 1.25rem 3.5rem rgba(28,18,11,.11);--radius:.3rem;--max:74rem;--font-cursive:cursive;--font-mono:monospace}
*{box-sizing:border-box}
*::selection{background:transparent;color:inherit}
*::-moz-selection{background:transparent;color:inherit}
html{width:100%;height:100%;overflow:hidden;background:var(--bg);color:var(--text);text-size-adjust:100%;-webkit-tap-highlight-color:#fff0}
body{width:100%;height:100dvh;min-height:100svh;margin:0;overflow:hidden;font-family:var(--font-cursive);background:radial-gradient(circle at 50% 9%,rgb(255 90 10/.1),transparent 22rem),linear-gradient(180deg,#fff 0%,#fffaf6 54%,#fff6ee 100%);user-select:none;-webkit-user-select:none;-webkit-touch-callout:none}
body::before,body::after{position:fixed;z-index:0;pointer-events:none;content:"";border-radius:999rem}
body::before{width:18rem;height:18rem;left:-7rem;top:8rem;background:rgb(255 90 10/.08);filter:blur(.25rem)}
body::after{width:15rem;height:15rem;right:-6rem;top:18rem;background:rgb(255 190 123/.14);filter:blur(.25rem)}
a,button{-webkit-tap-highlight-color:#fff0}
a{color:inherit;text-decoration:none}
.page{position:relative;z-index:1;display:flex;width:100%;height:100dvh;min-height:100svh;flex-direction:column;overflow:hidden}
.topbar{display:flex;flex:0 0 auto;align-items:center;justify-content:space-between;width:min(100%,var(--max));margin:0 auto;padding:clamp(.72rem,1.8dvh,1.05rem) clamp(1rem,4vw,2rem)}
.brand{display:inline-flex;font-family:var(--font-cursive);align-items:center;gap:.65rem;font-size:clamp(.72rem,1.45dvh,.86rem);font-weight:850;letter-spacing:.01em}
.brand-mark{display:grid;width:2.35rem;height:2.35rem;place-items:center;border:1px solid var(--line);border-radius:var(--radius);background:var(--surface-strong);box-shadow:0 .75rem 1.75rem rgb(255 90 10/.1)}
.brand-mark svg{display:block;width:1.45rem;height:1.45rem}
.status-pill{display:inline-flex;font-family:var(--font-cursive);align-items:center;gap:.5rem;min-height:2.35rem;padding:0 .9rem;border:1px solid var(--line);border-radius:var(--radius);background:rgb(255 255 255/.72);color:#7a3414;font-size:.82rem;font-weight:800;box-shadow:0 .75rem 1.8rem rgb(28 18 11/.06);backdrop-filter:blur(.75rem)}
.status-dot{width:.5rem;height:.5rem;border-radius:999rem;background:var(--orange);box-shadow:0 0 0 .25rem rgb(255 90 10/.12)}
.hero{position:relative;display:grid;flex:1 1 auto;min-height:0;width:min(100%,var(--max));margin:0 auto;overflow:hidden;padding:clamp(.2rem,1.2dvh,.85rem) clamp(1rem,4vw,2rem) clamp(5.15rem,11dvh,7.35rem);place-items:center;text-align:center}
.cloud,.bird,.dots{position:absolute;pointer-events:none;opacity:.52}
.cloud{width:clamp(5.8rem,13vw,10rem);height:auto;stroke:#d7d2ce;fill:none;stroke-width:4;stroke-linecap:round;stroke-linejoin:round}
.cloud-left{left:clamp(1rem,9vw,5rem);top:5.8rem}
.cloud-right{right:clamp(1rem,12vw,7rem);top:2.2rem;transform:scale(.82)}
.bird{right:clamp(3rem,11vw,8rem);top:8.6rem;width:clamp(4rem,8vw,5.8rem);stroke:#3e3e3e;fill:none;stroke-width:4;stroke-linecap:round}
.dots{width:5.6rem;height:5.6rem;background-image:radial-gradient(circle,rgb(255 90 10/.18) .12rem,transparent .14rem);background-size:.82rem .82rem}
.dots-left{left:clamp(1rem,10vw,5.4rem);top:18rem}
.dots-right{right:clamp(1rem,10vw,5.4rem);bottom:13rem}
.hero-inner{position:relative;z-index:2;display:grid;justify-items:center;width:100%}
.logo-card{display:grid;width:min(100%,67rem);justify-items:center;margin-top:clamp(.25rem,2vh,1.5rem)}
.main-logo{display:block;width:min(100%,52rem);max-height:clamp(14rem,43dvh,31rem);height:auto;object-fit:contain;user-select:none;-webkit-user-select:none;-webkit-user-drag:none;-webkit-touch-callout:none;filter:drop-shadow(0 1.2rem 2.4rem rgb(23 23 23/.1))}
.copy{width:min(100%,48rem);margin-top:clamp(.4rem,1.6vw,.85rem)}
.copy h1{margin:0;color:var(--text);font-family:var(--font-cursive);font-size:clamp(1.25rem,2.25vw,2.05rem);line-height:1.16;letter-spacing:0}
.copy p{margin:.58rem auto 0;color:var(--muted);font-family:var(--font-cursive);font-size:clamp(.96rem,1.25vw,1.08rem);line-height:1.42}
.actions{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:.85rem;margin-top:1.15rem}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:.6rem;min-width:11rem;min-height:2.95rem;padding:.72rem 1.25rem;border:1px solid #fff0;border-radius:var(--radius);cursor:pointer;font:inherit;font-weight:850;transition:transform 160ms ease,box-shadow 160ms ease,border-color 160ms ease,background 160ms ease}
.btn svg{width:1.12rem;height:1.12rem;flex:0 0 auto}
.btn-primary{background:linear-gradient(135deg,var(--orange),var(--orange-2));color:#fff;box-shadow:0 1rem 2rem rgb(255 90 10/.25)}
.btn-secondary{border-color:rgb(255 90 10/.72);background:rgb(255 255 255/.78);color:#1d1d1d}
.btn:hover,.btn:focus-visible{transform:translateY(-.08rem);outline:none}
.btn-primary:hover,.btn-primary:focus-visible{box-shadow:0 1.15rem 2.35rem rgb(255 90 10/.33)}
.btn-secondary:hover,.btn-secondary:focus-visible{background:var(--soft)}
.footer-wave{position:absolute;right:0;bottom:0;left:0;z-index:0;height:clamp(5.4rem,10dvh,7.4rem);overflow:hidden;pointer-events:none}
.footer-wave::before,.footer-wave::after{position:absolute;content:"";border-radius:50% 50% 0 0}
.footer-wave::before{right:-12%;bottom:-6.35rem;left:-12%;height:12.5rem;background:linear-gradient(135deg,var(--orange),#ff7a1a);box-shadow:inset 0 .45rem 0 rgb(181 55 0/.22)}
.footer-wave::after{right:-22%;bottom:-7.6rem;width:58%;height:10.5rem;background:rgb(255 255 255/.1)}
.footer-copy{position:absolute;right:1rem;bottom:.8rem;font-family:var(--font-mono);left:1rem;z-index:2;color:rgb(255 255 255/.92);font-size:clamp(.72rem,1.45dvh,.86rem);text-align:center}
@media (max-width:760px){.topbar{padding-top:.6rem;padding-bottom:.45rem}.status-pill{display:none}.hero{padding-top:.15rem;padding-bottom:clamp(4.85rem,10dvh,6.3rem)}.cloud-left,.cloud-right,.bird,.dots{opacity:.24}.cloud-left{left:.85rem;top:3.8rem}.cloud-right{right:.5rem;top:1.2rem}.bird{right:1rem;top:8rem}.dots-left{left:.9rem;top:14.5rem}.dots-right{right:1rem;bottom:12rem}.main-logo{width:min(100%,38rem);max-height:38dvh}.copy h1{max-width:24rem}.copy p{max-width:25rem}.actions{width:100%}.btn{width:min(100%,20rem)}}
@media (max-height:680px){.brand-mark{width:2rem;height:2rem}.brand-mark svg{width:1.25rem;height:1.25rem}.main-logo{max-height:37dvh}.copy p{margin-top:.42rem;line-height:1.32}.actions{margin-top:.75rem;gap:.62rem}.btn{min-height:2.62rem;padding:.58rem 1rem}}
@media (max-height:560px){.status-pill,.cloud,.bird,.dots{display:none}.main-logo{max-height:34dvh}.copy p{display:none}}
@media (prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition-duration:.001ms!important;animation-duration:.001ms!important;animation-iteration-count:1!important}}
    </style>
    <script type="application/ld+json" nonce="<?= e($nonce); ?>"><?= $schemaJson; ?></script>
</head>
<body>
    <div class="page">
        <header class="topbar" aria-label="Page header">
            <a class="brand" aria-label="Wrong URL homepage"></a>
            <div class="status-pill" aria-label="Fallback page status">
                <span class="status-dot" aria-hidden="true"></span>
                <span><?= $isWrongPath ? '404 fallback' : 'standalone homepage'; ?></span>
            </div>
        </header>

        <main class="hero" aria-labelledby="page-title">
            <svg class="cloud cloud-left" viewBox="0 0 160 60" aria-hidden="true" focusable="false">
                <path d="M18 48h123M36 48c-12-23 20-33 33-17 10-31 55-22 54 7 15-3 26 2 30 10"/>
            </svg>
            <svg class="cloud cloud-right" viewBox="0 0 160 60" aria-hidden="true" focusable="false">
                <path d="M18 48h123M36 48c-12-23 20-33 33-17 10-31 55-22 54 7 15-3 26 2 30 10"/>
            </svg>
            <svg class="bird" viewBox="0 0 150 60" aria-hidden="true" focusable="false">
                <path d="M16 38c11-16 24-16 34 0M68 32c10-17 25-17 36 0M112 39c8-12 18-12 27 0"/>
            </svg>
            <span class="dots dots-left" aria-hidden="true"></span>
            <span class="dots dots-right" aria-hidden="true"></span>

            <section class="hero-inner">
                <div class="logo-card">
                    <img class="main-logo" src="/assets/wrong-url-logo.png" width="1402" height="886" alt="Wrong URL fox logo with invalid or missing sub_id detail" draggable="false" decoding="async">
                </div>

                <div class="copy">
                    <h1 id="page-title">Oops! The link you visited is invalid or incomplete.</h1>
                    <p>The page you’re looking for might be mistyped, removed, or never existed. Please double-check the URL or go back to the homepage.</p>
                </div>

                <nav class="actions" aria-label="Page recovery actions">
                    <a class="btn btn-primary" href="/">
                        <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
                            <path d="M3 10.6 12 3l9 7.6V21h-6v-6H9v6H3V10.6Z" fill="currentColor"/>
                        </svg>
                        <span>Go to Homepage</span>
                    </a>
                    <button class="btn btn-secondary" type="button" data-go-back>
                        <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
                            <path d="M11 6 5 12l6 6M6 12h13" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                        <span>Go Back</span>
                    </button>
                </nav>
            </section>
        </main>

        <footer class="footer-wave" aria-hidden="true"></footer>
        <div class="footer-copy">© <?= e($year); ?> NGIX ⸺ XCTD. All rights reserved.</div>
    </div>

    <script nonce="<?= e($nonce); ?>">
        (() => {
            const protectedImages = document.querySelectorAll('img.main-logo');

            protectedImages.forEach((image) => {
                image.addEventListener('contextmenu', (event) => {
                    event.preventDefault();
                });

                image.addEventListener('dragstart', (event) => {
                    event.preventDefault();
                });
            });

            const backButton = document.querySelector('[data-go-back]');

            if (!backButton) {
                return;
            }

            backButton.addEventListener('click', () => {
                if (window.history.length > 1) {
                    window.history.back();
                    return;
                }

                window.location.assign('/');
            });
        })();
    </script>
</body>
</html>
