<?php
/*
 * CDN-only widget tag helpers for the react.<customer>.timetoscore.com
 * docroot (/www/common/react). Unlike include/asset-version.php (used by
 * the legacy public/test/ shells, which still support a no-CDN fallback),
 * this docroot ALWAYS loads widgets from the CDN — there is no local
 * <slug>-assets build here and no WIDGET_CDN gate.
 *
 * widget_js_tag() emits a single stable loader:
 *     <cdn>/<slug>/loader.js
 * The loader (rebuilt each release with the content-hashed bundle names
 * baked in) injects the real <link rel=stylesheet> + <script type=module>
 * at runtime, so widget_css_tag() returns '' (emitting a <link> here would
 * race the loader).
 *
 * Hidden canary flag: ?wv=<buildid> swaps loader.js for a staged, versioned
 * loader <cdn>/<slug>/loader.<buildid>.js (uploaded by `deploy-cdn.sh stage`
 * but NOT yet promoted to the stable loader.js). This lets a tester preview
 * a new release on production before `deploy-cdn.sh promote` flips it for
 * everyone. The value is strictly validated to a safe filename charset.
 *
 * $slug is the widget directory name: player, team, game, standings,
 * scorebug, schedule, skater-leaders, goalie-leaders, playoff.
 *
 * REACT_CDN_BASE is the CDN origin. Defaults to https://cdn.timetoscore.com;
 * override it in a customer config (e.g. to the *.cloudfront.net domain while
 * the vanity DNS is being set up) by defining REACT_CDN_BASE before this runs.
 */

if (!defined('REACT_CDN_BASE')) {
    define('REACT_CDN_BASE', 'https://cdn.timetoscore.com');
}

if (!function_exists('asset_url')) {
    /* ?v=<mtime> cache-buster for same-origin static assets (site.css etc.). */
    function asset_url($path)
    {
        $abs = $_SERVER['DOCUMENT_ROOT'] . $path;
        $v = @filemtime($abs);
        return $v ? $path . '?v=' . $v : $path;
    }
}

if (!function_exists('widget_css_tag')) {
    function widget_css_tag($slug)
    {
        // The CDN loader injects the stylesheet; nothing to emit here.
        return '';
    }
}

if (!function_exists('widget_js_tag')) {
    function widget_js_tag($slug)
    {
        $base   = rtrim(REACT_CDN_BASE, '/');
        $loader = 'loader.js';

        // Hidden canary: ?wv=<buildid> -> staged versioned loader.
        if (!empty($_GET['wv'])) {
            $wv = (string) $_GET['wv'];
            if (preg_match('/^[A-Za-z0-9._-]{1,64}$/', $wv)) {
                $loader = 'loader.' . $wv . '.js';
            }
        }

        $url = "{$base}/{$slug}/{$loader}";
        return '<script src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></script>';
    }
}
?>
