<?php

declare(strict_types=1);

namespace PpPhp\Core\Build;

use PpPhp\Core\Designer\Auth\DesignerAuthRenderer;

/**
 * Compiles a Designer common Login page into a functional generated PHP page.
 *
 * The Designer owns presentation. BuildWriter owns authentication processing.
 * This compiler joins them without replacing POST handling with preview-only HTML.
 */
final class LoginPageCompiler
{
    /** Replace the auth form's provider list with providers enabled in Security. */
    public static function withProviders(array $page, array $providers): array
    {
        $walk = static function (array &$components) use (&$walk, $providers): void {
            foreach ($components as &$component) {
                if (!is_array($component)) continue;
                if (($component['type'] ?? '') === 'auth_form') $component['props']['socialProviders'] = array_values($providers);
                if (!empty($component['children']) && is_array($component['children'])) $walk($component['children']);
            }
        };
        if (!empty($page['components']) && is_array($page['components'])) $walk($page['components']);
        return $page;
    }
    public static function supports(array $page): bool
    {
        return self::authProps($page) !== [];
    }

    /** @return string[] */
    public static function providers(array $page): array
    {
        $props = self::authProps($page);
        $raw = $props['socialProviders'] ?? [];
        // Inspector saves an array, but hand-edited/legacy states may hold a
        // comma-separated string — split before sanitizing so "google, apple"
        // doesn't collapse into one mangled provider id.
        if (is_string($raw)) {
            $raw = explode(',', $raw);
        }
        $providers = array_map(
            static fn(mixed $provider): string => preg_replace('/[^a-z0-9_-]/', '', strtolower(trim((string) $provider))),
            (array) $raw
        );

        return array_values(array_unique(array_filter($providers)));
    }

    public static function compile(array $page, string $phpLogic, array $appBrand = []): string
    {
        $props = self::authProps($page);
        if ($props === []) {
            throw new \InvalidArgumentException('The Login page does not contain an auth_form component.');
        }

        $template = preg_replace('/[^a-z0-9_-]/', '', strtolower((string) ($props['template'] ?? 'aurora'))) ?: 'aurora';
        $accent = self::color((string) ($props['accentColor'] ?? '#6d5dfc'), '#6d5dfc');
        $title = self::e((string) ($props['title'] ?? $page['title'] ?? 'Sign in'));
        $brand = self::brand($props, $appBrand);
        $social = self::social($props);
        $socialBefore = (($props['socialPosition'] ?? 'after') === 'before') ? $social : '';
        $socialAfter = (($props['socialPosition'] ?? 'after') !== 'before') ? $social : '';

        $showcase = '<aside class="ppd-auth-showcase">' . $brand .
            '<div><small>' . self::e((string) ($props['showcaseEyebrow'] ?? '')) . '</small><h1>' .
            self::e((string) ($props['showcaseTitle'] ?? '')) . '</h1><p>' .
            self::e((string) ($props['showcaseText'] ?? '')) . '</p></div>';
        if (trim((string) ($props['testimonial'] ?? '')) !== '') {
            $author = trim((string) ($props['quoteAuthor'] ?? ''));
            $footer = $author !== '' ? '<footer>' . self::e($author) . '</footer>' : '';
            $showcase .= '<blockquote>“' . self::e((string) $props['testimonial']) . '”' . $footer . '</blockquote>';
        }
        $showcase .= '</aside>';

        $passwordToggle = !empty($props['showPasswordToggle'])
            ? '<button class="ppd-auth-password-toggle" type="button" data-password-toggle aria-label="Show password">Show</button>'
            : '';
        $options = '<div class="ppd-auth-options">';
        if (!empty($props['showRemember'])) {
            $options .= '<label><input type="checkbox" name="remember" value="1"> ' .
                self::e((string) ($props['rememberLabel'] ?? 'Remember me')) . '</label>';
        } else {
            $options .= '<span></span>';
        }
        if (!empty($props['showForgot'])) {
            $options .= '<a href="<?= APP_BASE ?>/generated/auth/forgot-password.php">' .
                self::e((string) ($props['forgotLabel'] ?? 'Forgot password?')) . '</a>';
        }
        $options .= '</div>';

        $signup = '';
        if (!empty($props['showSignup'])) {
            $signup = '<div class="ppd-auth-links">' . self::e((string) ($props['signupText'] ?? '')) .
                ' <a href="<?= APP_BASE ?>/generated/auth/register.php">' .
                self::e((string) ($props['signupLabel'] ?? 'Create an account')) . '</a></div>';
        }
        $security = !empty($props['showSecurityNote'])
            ? '<small class="ppd-auth-security">✓ ' . self::e((string) ($props['securityNote'] ?? '')) . '</small>'
            : '';

        $fields = '<label class="ppd-auth-field"><span>' . self::e((string) ($props['emailLabel'] ?? 'Username or email')) .
            '</span><input name="username" autocomplete="username" placeholder="' . self::e((string) ($props['emailPlaceholder'] ?? '')) . '" required></label>' .
            '<label class="ppd-auth-field"><span>' . self::e((string) ($props['passwordLabel'] ?? 'Password')) .
            '</span><div class="ppd-auth-password"><input name="password" type="password" autocomplete="current-password" placeholder="' . self::e((string) ($props['passwordPlaceholder'] ?? '')) . '" required>' . $passwordToggle . '</div></label>';

        return strtr(self::documentShell(), [
            '__PAGE_TYPE__' => 'login',
            '__PHP_LOGIC__' => rtrim($phpLogic),
            '__TITLE__' => $title,
            '__STYLES__' => DesignerAuthRenderer::templateStyles() . self::extraStyles(),
            '__TEMPLATE__' => $template,
            '__ACCENT__' => 'var(--pp-primary,' . $accent . ')',
            '__SHOWCASE__' => $showcase,
            '__BRAND__' => $brand,
            '__SUBTITLE__' => self::e((string) ($props['subtitle'] ?? '')),
            '__SOCIAL_BEFORE__' => $socialBefore,
            '__FIELDS__' => $fields,
            '__OPTIONS__' => $options,
            '__SUBMIT_LABEL__' => self::e((string) ($props['submitLabel'] ?? 'Sign in')),
            '__SOCIAL_AFTER__' => $socialAfter,
            '__SIGNUP__' => $signup,
            '__SECURITY__' => $security,
        ]);
    }

    /** Shared page shell for compiled login/register pages. */
    private static function documentShell(): string
    {
        return <<<'PHP'
<?php
require_once __DIR__ . '/../../_runtime.php';
$error = $error ?? '';
$message = $message ?? '';
__PHP_LOGIC__
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__TITLE__</title>
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/icons/bootstrap-icons.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/css/designer-base.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/vendor/inter/inter.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/vendor/fonts/fonts.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/css/theme.css">
<style>__STYLES__</style>
</head>
<body>
<section class="ppd-auth-page is-__TEMPLATE__" style="--auth-accent:__ACCENT__" data-auth-page="__PAGE_TYPE__">
__SHOWCASE__
<main class="ppd-auth-card-zone">
<form method="post" class="ppd-auth-form">
__BRAND__
<h2>__TITLE__</h2>
<p class="ppd-auth-subtitle">__SUBTITLE__</p>
<?= flashMessage() ?>
<?php if ($error): ?><div class="ppd-auth-alert is-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($message): ?><div class="ppd-auth-alert is-info"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<?php if (!empty($__adminHint)): ?><div class="ppd-auth-alert is-hint"><?= $__adminHint ?></div><?php endif; ?>
__SOCIAL_BEFORE__
<?= csrfField() ?>
__FIELDS__
__OPTIONS__
<button class="ppd-auth-action ppd-auth-action-primary" type="submit">__SUBMIT_LABEL__</button>
__SOCIAL_AFTER__
__SIGNUP__
__SECURITY__
</form>
</main>
</section>
<script>
document.querySelector('[data-password-toggle]')?.addEventListener('click', function () {
    var input = document.querySelector('input[name="password"]');
    if (!input) return;
    var showing = input.type === 'text';
    input.type = showing ? 'password' : 'text';
    this.textContent = showing ? 'Show' : 'Hide';
    this.setAttribute('aria-label', showing ? 'Show password' : 'Hide password');
});
</script>
</body>
</html>
PHP;
    }

    private static function extraStyles(): string
    {
        return <<<'CSS'
.ppd-auth-alert{margin:0 0 14px;padding:10px 12px;border-radius:10px;font-size:12px}.ppd-auth-alert.is-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}.ppd-auth-alert.is-info{border:1px solid #bfdbfe;background:#eff6ff;color:#1e40af}.ppd-auth-alert.is-hint{border:1px dashed color-mix(in srgb,var(--auth-accent) 45%,#cbd5e1);background:color-mix(in srgb,var(--auth-accent) 8%,transparent);color:#334155;display:flex;align-items:flex-start;gap:7px;line-height:1.5}.ppd-auth-alert.is-hint i{margin-top:1px;flex:0 0 auto}.ppd-auth-alert.is-hint strong{color:var(--auth-accent);white-space:nowrap}@media (prefers-color-scheme:dark){.ppd-auth-alert.is-hint{color:#cbd5e1}}.ppd-auth-password{position:relative}.ppd-auth-password input{width:100%;padding-right:58px}.ppd-auth-password-toggle{position:absolute;right:8px;top:50%;transform:translateY(-50%);border:0;background:transparent;color:var(--auth-accent);font-size:10px;font-weight:750;cursor:pointer}.ppd-auth-social button{cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;font-size:12px}.ppd-auth-social button i{font-size:15px}.ppd-auth-social button:hover{border-color:var(--auth-accent);color:var(--auth-accent)}.ppd-auth-brand-img{height:40px;max-width:150px;object-fit:contain;border-radius:8px}
CSS;
    }

    /**
     * Compile a Designer common Register page (auth_form with
     * pageType 'register') around BuildWriter's registration POST logic.
     * Same visual shells as the login templates.
     */
    public static function compileRegister(array $page, string $phpLogic, array $appBrand = []): string
    {
        $props = self::authProps($page);
        if ($props === []) {
            throw new \InvalidArgumentException('The Register page does not contain an auth_form component.');
        }

        $template = preg_replace('/[^a-z0-9_-]/', '', strtolower((string) ($props['template'] ?? 'aurora'))) ?: 'aurora';
        $accent = self::color((string) ($props['accentColor'] ?? '#6d5dfc'), '#6d5dfc');
        $title = self::e((string) ($props['title'] ?? $page['title'] ?? 'Create your account'));
        $brand = self::brand($props, $appBrand);
        $social = self::social($props);
        $socialBefore = (($props['socialPosition'] ?? 'after') === 'before') ? $social : '';
        $socialAfter = (($props['socialPosition'] ?? 'after') !== 'before') ? $social : '';

        $showcase = '<aside class="ppd-auth-showcase">' . $brand .
            '<div><small>' . self::e((string) ($props['showcaseEyebrow'] ?? '')) . '</small><h1>' .
            self::e((string) ($props['showcaseTitle'] ?? '')) . '</h1><p>' .
            self::e((string) ($props['showcaseText'] ?? '')) . '</p></div>';
        if (trim((string) ($props['testimonial'] ?? '')) !== '') {
            $author = trim((string) ($props['quoteAuthor'] ?? ''));
            $footer = $author !== '' ? '<footer>' . self::e($author) . '</footer>' : '';
            $showcase .= '<blockquote>“' . self::e((string) $props['testimonial']) . '”' . $footer . '</blockquote>';
        }
        $showcase .= '</aside>';

        $passwordToggle = !empty($props['showPasswordToggle'])
            ? '<button class="ppd-auth-password-toggle" type="button" data-password-toggle aria-label="Show password">Show</button>'
            : '';

        $signin = '';
        if (($props['showSignup'] ?? true) !== false) {
            $signin = '<div class="ppd-auth-links">' . self::e((string) ($props['signupText'] ?? 'Already have an account?')) .
                ' <a href="<?= APP_BASE ?>/generated/auth/login.php">' .
                self::e((string) ($props['signupLabel'] ?? 'Sign in')) . '</a></div>';
        }
        $security = !empty($props['showSecurityNote'])
            ? '<small class="ppd-auth-security">✓ ' . self::e((string) ($props['securityNote'] ?? '')) . '</small>'
            : '';

        $fields = '<label class="ppd-auth-field"><span>' . self::e((string) ($props['nameLabel'] ?? 'Username')) .
            '</span><input name="username" autocomplete="username" placeholder="' . self::e((string) ($props['namePlaceholder'] ?? '')) . '" value="<?= htmlspecialchars($_POST[\'username\'] ?? \'\') ?>" required></label>' .
            '<label class="ppd-auth-field"><span>' . self::e((string) ($props['emailLabel'] ?? 'Email')) .
            '</span><input name="email" type="email" autocomplete="email" placeholder="' . self::e((string) ($props['emailPlaceholder'] ?? '')) . '" value="<?= htmlspecialchars($_POST[\'email\'] ?? \'\') ?>" required></label>' .
            '<label class="ppd-auth-field"><span>' . self::e((string) ($props['passwordLabel'] ?? 'Password')) .
            '</span><div class="ppd-auth-password"><input name="password" type="password" autocomplete="new-password" placeholder="' . self::e((string) ($props['passwordPlaceholder'] ?? '')) . '" required>' . $passwordToggle . '</div></label>' .
            '<label class="ppd-auth-field"><span>' . self::e((string) ($props['confirmLabel'] ?? 'Confirm password')) .
            '</span><input name="confirm_password" type="password" autocomplete="new-password" placeholder="' . self::e((string) ($props['confirmPlaceholder'] ?? '')) . '" required></label>';

        $document = self::documentShell();

        return strtr($document, [
            '__PAGE_TYPE__' => 'register',
            '__PHP_LOGIC__' => rtrim($phpLogic),
            '__TITLE__' => $title,
            '__STYLES__' => DesignerAuthRenderer::templateStyles() . self::extraStyles(),
            '__TEMPLATE__' => $template,
            '__ACCENT__' => 'var(--pp-primary,' . $accent . ')',
            '__SHOWCASE__' => $showcase,
            '__BRAND__' => $brand,
            '__SUBTITLE__' => self::e((string) ($props['subtitle'] ?? '')),
            '__SOCIAL_BEFORE__' => $socialBefore,
            '__FIELDS__' => $fields,
            '__OPTIONS__' => '',
            '__SUBMIT_LABEL__' => self::e((string) ($props['submitLabel'] ?? 'Create account')),
            '__SOCIAL_AFTER__' => $socialAfter,
            '__SIGNUP__' => $signin,
            '__SECURITY__' => $security,
        ]);
    }

    /**
     * Compile a Designer common Forgot Password page (auth_form with
     * pageType 'forgot_password') around BuildWriter's email logic.
     * Single email field; same visual shells as the rest of the auth suite.
     */
    public static function compileForgot(array $page, string $phpLogic, array $appBrand = []): string
    {
        $props = self::authProps($page);
        if ($props === []) {
            throw new \InvalidArgumentException('The Forgot Password page does not contain an auth_form component.');
        }

        $template = preg_replace('/[^a-z0-9_-]/', '', strtolower((string) ($props['template'] ?? 'aurora'))) ?: 'aurora';
        $accent = self::color((string) ($props['accentColor'] ?? '#6d5dfc'), '#6d5dfc');
        $title = self::e((string) ($props['title'] ?? $page['title'] ?? 'Forgot your password?'));
        $brand = self::brand($props, $appBrand);

        $showcase = '<aside class="ppd-auth-showcase">' . $brand .
            '<div><small>' . self::e((string) ($props['showcaseEyebrow'] ?? '')) . '</small><h1>' .
            self::e((string) ($props['showcaseTitle'] ?? '')) . '</h1><p>' .
            self::e((string) ($props['showcaseText'] ?? '')) . '</p></div>';
        if (trim((string) ($props['testimonial'] ?? '')) !== '') {
            $author = trim((string) ($props['quoteAuthor'] ?? ''));
            $footer = $author !== '' ? '<footer>' . self::e($author) . '</footer>' : '';
            $showcase .= '<blockquote>“' . self::e((string) $props['testimonial']) . '”' . $footer . '</blockquote>';
        }
        $showcase .= '</aside>';

        $signin = '';
        if (($props['showSignup'] ?? true) !== false) {
            $signin = '<div class="ppd-auth-links">' . self::e((string) ($props['signupText'] ?? 'Remembered it?')) .
                ' <a href="<?= APP_BASE ?>/generated/auth/login.php">' .
                self::e((string) ($props['signupLabel'] ?? 'Back to sign in')) . '</a></div>';
        }
        $security = !empty($props['showSecurityNote'])
            ? '<small class="ppd-auth-security">✓ ' . self::e((string) ($props['securityNote'] ?? '')) . '</small>'
            : '';

        $fields = '<label class="ppd-auth-field"><span>' . self::e((string) ($props['emailLabel'] ?? 'Account email')) .
            '</span><input name="email" type="email" autocomplete="email" placeholder="' .
            self::e((string) ($props['emailPlaceholder'] ?? '')) . '" required></label>';
        if (trim((string) ($props['helpText'] ?? '')) !== '') {
            $fields .= '<div class="ppd-auth-helpbox">' . self::e((string) $props['helpText']) . '</div>';
        }

        return strtr(self::documentShell(), [
            '__PAGE_TYPE__' => 'forgot_password',
            '__PHP_LOGIC__' => rtrim($phpLogic),
            '__TITLE__' => $title,
            '__STYLES__' => DesignerAuthRenderer::templateStyles() . self::extraStyles()
                . '.ppd-auth-helpbox{margin:-4px 0 12px;padding:9px 12px;border-radius:10px;font-size:11.5px;line-height:1.55;color:#6b7280;background:color-mix(in srgb,var(--auth-accent) 6%,#fff);border:1px solid color-mix(in srgb,var(--auth-accent) 16%,transparent)}',
            '__TEMPLATE__' => $template,
            '__ACCENT__' => 'var(--pp-primary,' . $accent . ')',
            '__SHOWCASE__' => $showcase,
            '__BRAND__' => $brand,
            '__SUBTITLE__' => self::e((string) ($props['subtitle'] ?? '')),
            '__SOCIAL_BEFORE__' => '',
            '__FIELDS__' => $fields,
            '__OPTIONS__' => '',
            '__SUBMIT_LABEL__' => self::e((string) ($props['submitLabel'] ?? 'Send reset link')),
            '__SOCIAL_AFTER__' => '',
            '__SIGNUP__' => $signin,
            '__SECURITY__' => $security,
        ]);
    }

    /**
     * Compile a Designer common Reset Password page (auth_form with
     * pageType 'reset_password') around BuildWriter's token logic — the
     * page users reach from the forgot-password email link. Shows the
     * new-password form for a valid token, a friendly expired state
     * otherwise. Same visual shells as login/register.
     */
    public static function compileReset(array $page, string $phpLogic, array $appBrand = []): string
    {
        $props = self::authProps($page);
        if ($props === []) {
            throw new \InvalidArgumentException('The Reset Password page does not contain an auth_form component.');
        }

        $template = preg_replace('/[^a-z0-9_-]/', '', strtolower((string) ($props['template'] ?? 'aurora'))) ?: 'aurora';
        $accent = self::color((string) ($props['accentColor'] ?? '#6d5dfc'), '#6d5dfc');
        $title = self::e((string) ($props['title'] ?? $page['title'] ?? 'Set a new password'));
        $brand = self::brand($props, $appBrand);

        $showcase = '<aside class="ppd-auth-showcase">' . $brand .
            '<div><small>' . self::e((string) ($props['showcaseEyebrow'] ?? '')) . '</small><h1>' .
            self::e((string) ($props['showcaseTitle'] ?? '')) . '</h1><p>' .
            self::e((string) ($props['showcaseText'] ?? '')) . '</p></div></aside>';

        $toggle = !empty($props['showPasswordToggle'])
            ? '<button class="ppd-auth-password-toggle" type="button" data-password-toggle aria-label="Show password">Show</button>'
            : '';
        $strength = ($props['showStrength'] ?? true) !== false
            ? '<div class="ppd-auth-strengthbar" data-strength><i></i><i></i><i></i><i></i><small>&nbsp;</small></div>'
            : '';
        $signin = '';
        if (($props['showSignup'] ?? true) !== false) {
            $signin = '<div class="ppd-auth-links">' . self::e((string) ($props['signupText'] ?? 'Remembered it?')) .
                ' <a href="<?= APP_BASE ?>/generated/auth/login.php">' .
                self::e((string) ($props['signupLabel'] ?? 'Back to sign in')) . '</a></div>';
        }
        $security = !empty($props['showSecurityNote'])
            ? '<small class="ppd-auth-security">✓ ' . self::e((string) ($props['securityNote'] ?? '')) . '</small>'
            : '';

        $formState = '<h2>' . $title . '</h2><p class="ppd-auth-subtitle">' . self::e((string) ($props['subtitle'] ?? '')) . '</p>'
            . '<?php if ($error && $reset !== null): ?><div class="ppd-auth-alert is-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>'
            . '<?= csrfField() ?>'
            . '<input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">'
            . '<label class="ppd-auth-field"><span>' . self::e((string) ($props['passwordLabel'] ?? 'New password'))
            . '</span><div class="ppd-auth-password"><input name="password" type="password" autocomplete="new-password" placeholder="'
            . self::e((string) ($props['passwordPlaceholder'] ?? '')) . '" required>' . $toggle . '</div></label>'
            . $strength
            . '<label class="ppd-auth-field"><span>' . self::e((string) ($props['confirmLabel'] ?? 'Confirm new password'))
            . '</span><input name="confirm_password" type="password" autocomplete="new-password" placeholder="'
            . self::e((string) ($props['confirmPlaceholder'] ?? '')) . '" required></label>'
            . '<button class="ppd-auth-action ppd-auth-action-primary" type="submit">'
            . self::e((string) ($props['submitLabel'] ?? 'Reset password')) . '</button>';

        $invalidState = '<div class="ppd-auth-invalid"><span class="ppd-auth-invalid-icon"><i class="bi bi-hourglass-bottom"></i></span>'
            . '<h2>' . self::e((string) ($props['invalidTitle'] ?? 'This link has expired')) . '</h2>'
            . '<p class="ppd-auth-subtitle">' . self::e((string) ($props['invalidText'] ?? 'Reset links are valid for a limited time. Request a new one and check your inbox.')) . '</p>'
            . '<a class="ppd-auth-action ppd-auth-action-primary ppd-auth-action-link" href="<?= APP_BASE ?>/generated/auth/forgot-password.php">'
            . self::e((string) ($props['requestLabel'] ?? 'Request a new link')) . '</a></div>';

        $extra = self::extraStyles()
            . '.ppd-auth-strengthbar{display:flex;align-items:center;gap:5px;margin:-4px 0 12px}'
            . '.ppd-auth-strengthbar i{flex:1;height:5px;border-radius:99px;background:#e5e7eb;transition:background .2s}'
            . '.ppd-auth-strengthbar i.on.s1{background:#dc2626}.ppd-auth-strengthbar i.on.s2{background:#d97706}'
            . '.ppd-auth-strengthbar i.on.s3{background:#65a30d}.ppd-auth-strengthbar i.on.s4{background:#16a34a}'
            . '.ppd-auth-strengthbar small{color:#9aa3b2;font-size:10px;font-weight:750;min-width:44px;text-align:right}'
            . '.ppd-auth-invalid{text-align:center}.ppd-auth-invalid-icon{width:56px;height:56px;margin:0 auto 14px;border-radius:16px;display:grid;place-items:center;font-size:24px;background:color-mix(in srgb,var(--auth-accent) 12%,#fff);color:var(--auth-accent)}'
            . '.ppd-auth-action-link{display:block;text-decoration:none;text-align:center;line-height:44px}';

        $document = <<<'PHP'
<?php
require_once __DIR__ . '/../../_runtime.php';
$error = $error ?? '';
$message = $message ?? '';
__PHP_LOGIC__
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__TITLE__</title>
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/icons/bootstrap-icons.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/css/designer-base.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/vendor/inter/inter.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/vendor/fonts/fonts.css">
<link rel="stylesheet" href="<?= APP_BASE ?>/assets/css/theme.css">
<style>__STYLES__</style>
</head>
<body>
<section class="ppd-auth-page is-__TEMPLATE__" style="--auth-accent:__ACCENT__" data-auth-page="reset_password">
__SHOWCASE__
<main class="ppd-auth-card-zone">
<form method="post" class="ppd-auth-form">
__BRAND__
<?= flashMessage() ?>
<?php if ($reset !== null): ?>
__FORM_STATE__
<?php else: ?>
__INVALID_STATE__
<?php endif; ?>
__SIGNIN__
__SECURITY__
</form>
</main>
</section>
<script>
document.querySelector('[data-password-toggle]')?.addEventListener('click', function () {
    var input = document.querySelector('input[name="password"]');
    if (!input) return;
    var showing = input.type === 'text';
    input.type = showing ? 'password' : 'text';
    this.textContent = showing ? 'Show' : 'Hide';
});
(function () {
    var pwd = document.querySelector('input[name="password"]');
    var bars = document.querySelectorAll('[data-strength] i');
    var label = document.querySelector('[data-strength] small');
    if (!pwd || !bars.length) return;
    var names = ['Weak', 'Fair', 'Good', 'Strong'];
    pwd.addEventListener('input', function () {
        var v = pwd.value, s = 0;
        if (v.length >= 8) s++;
        if (v.length >= 12) s++;
        if (/[a-z]/.test(v) && /[A-Z]/.test(v)) s++;
        if (/[0-9]/.test(v) && /[^a-zA-Z0-9]/.test(v)) s++;
        else if (/[0-9]/.test(v) || /[^a-zA-Z0-9]/.test(v)) s += (s < 3 ? 1 : 0);
        s = Math.min(4, Math.max(v ? 1 : 0, s));
        bars.forEach(function (b, i) { b.className = i < s ? 'on s' + s : ''; });
        if (label) label.textContent = v ? names[s - 1] || 'Weak' : ' ';
    });
})();
</script>
</body>
</html>
PHP;

        return strtr($document, [
            '__PHP_LOGIC__' => rtrim($phpLogic),
            '__TITLE__' => $title,
            '__STYLES__' => DesignerAuthRenderer::templateStyles() . $extra,
            '__TEMPLATE__' => $template,
            '__ACCENT__' => 'var(--pp-primary,' . $accent . ')',
            '__SHOWCASE__' => $showcase,
            '__BRAND__' => $brand,
            '__FORM_STATE__' => $formState,
            '__INVALID_STATE__' => $invalidState,
            '__SIGNIN__' => $signin,
            '__SECURITY__' => $security,
        ]);
    }

    private static function authProps(array $page): array
    {
        $walk = function (array $components) use (&$walk): array {
            foreach ($components as $component) {
                if (!is_array($component)) {
                    continue;
                }
                if (($component['type'] ?? '') === 'auth_form') {
                    return (array) ($component['props'] ?? []);
                }
                $found = $walk((array) ($component['children'] ?? []));
                if ($found !== []) {
                    return $found;
                }
            }
            return [];
        };

        return $walk((array) ($page['components'] ?? []));
    }

    /**
     * Brand block. The APP brand (Style → Layout → Logo: name + optional
     * image, passed by BuildWriter) always wins over per-template props, so
     * renaming the app or swapping the logo is a one-place change.
     */
    private static function brand(array $props, array $app = []): string
    {
        $name = trim((string) ($app['name'] ?? ''));
        if ($name === '') {
            $name = (string) ($props['brandName'] ?? 'Application');
        }
        $image = trim((string) ($app['image'] ?? ''));
        if ($image === '') {
            $image = trim((string) ($props['brandImage'] ?? ''));
        }

        if ($image !== '') {
            $src = preg_match('#^https?://#i', $image)
                ? self::e($image)
                : '<?= APP_BASE ?>/' . self::e(ltrim($image, '/'));
            $mark = '<img class="ppd-auth-brand-img" src="' . $src . '" alt="' . self::e($name) . '">';
        } else {
            $mark = '<b>' . self::e(mb_strtoupper(mb_substr($name !== '' ? $name : 'A', 0, 1))) . '</b>';
        }

        return '<div class="ppd-auth-brand">' . $mark . '<span><strong>' . self::e($name) .
            '</strong><small>' . self::e((string) ($props['brandTagline'] ?? '')) . '</small></span></div>';
    }

    private static function social(array $props): string
    {
        $providers = self::providers(['components' => [['type' => 'auth_form', 'props' => $props]]]);
        if ($providers === []) {
            return '';
        }

        $names = [
            'google' => 'Google',
            'microsoft' => 'Microsoft',
            'facebook' => 'Facebook',
            'apple' => 'Apple',
            'github' => 'GitHub',
            'linkedin' => 'LinkedIn',
            'okta' => 'Okta',
        ];
        // Same brand icons the Designer canvas shows (registry.js auth_form).
        $icons = [
            'google' => 'bi-google',
            'microsoft' => 'bi-microsoft',
            'facebook' => 'bi-facebook',
            'apple' => 'bi-apple',
            'github' => 'bi-github',
            'linkedin' => 'bi-linkedin',
            'okta' => 'bi-shield-check',
        ];
        $iconsOnly = ($props['socialStyle'] ?? 'buttons') === 'icons';
        $buttons = [];
        foreach ($providers as $provider) {
            $label = $names[$provider] ?? ucwords(str_replace(['-', '_'], ' ', $provider));
            $icon = '<i class="bi ' . self::e($icons[$provider] ?? 'bi-shield-lock') . '"></i>';
            $text = $iconsOnly ? '' : '<span>Continue with ' . self::e($label) . '</span>';
            $buttons[] = '<button type="submit" name="auth_provider" value="' . self::e($provider) .
                '" data-auth-provider="' . self::e($provider) . '" title="Continue with ' . self::e($label) . '">' .
                $icon . $text . '</button>';
        }
        $style = $iconsOnly ? ' is-icons' : '';

        return '<div class="ppd-auth-divider"><span>' .
            self::e((string) ($props['dividerText'] ?? 'or continue with')) .
            '</span></div><div class="ppd-auth-social' . $style . '">' . implode('', $buttons) . '</div>';
    }

    private static function color(string $value, string $fallback): string
    {
        return preg_match('/^#[0-9a-f]{3,8}$/i', $value) ? $value : $fallback;
    }

    private static function e(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}
