<?php
namespace TCB\Frontend;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class SystemNavigation {
    public static function init(): void {
        add_action( 'wp_enqueue_scripts', [ self::class, 'enqueue_assets' ], 20 );
    }

    public static function event_context(): array {
        $name = 'TechCon SoCal 2026';
        $date_range = 'May 21-23, 2026';
        if ( class_exists( '\TCA\DB\EventsDAO' ) ) {
            $events = \TCA\DB\EventsDAO::get_all( 'live' );
            if ( empty( $events ) ) { $events = \TCA\DB\EventsDAO::get_all(); }
            if ( ! empty( $events[0] ) ) {
                $name = trim( (string) ( $events[0]['name'] ?? $name ) ) ?: $name;
                $date_range = trim( (string) ( $events[0]['date_range'] ?? $date_range ) ) ?: $date_range;
            }
        }
        return [
            'system_title' => 'Media Interviews',
            'event_name'   => $name,
            'date_range'   => $date_range,
            'logo_url'     => 'https://media.techconglobal.com/wp-content/uploads/2026/05/techcon-main-logo.png',
        ];
    }


    private static function agenda_enabled(): bool {
        return get_option( 'tca_enable_agenda_pages', 'yes' ) === 'yes';
    }

    private static function items(): array {
        $user = is_user_logged_in() ? wp_get_current_user() : null;
        $roles = $user ? (array) $user->roles : [];
        $items = [
            [ 'label' => 'Home', 'url' => home_url( '/' ), 'key' => 'home' ],
        ];
        if ( self::agenda_enabled() ) {
            $items[] = [ 'label' => 'Agenda', 'url' => home_url( '/agenda/' ), 'key' => 'agenda' ];
        }
        $items[] = [ 'label' => 'Media Partners', 'url' => home_url( '/booking/' ), 'key' => 'booking' ];
        if ( in_array( 'tc_speaker', $roles, true ) ) {
            $items[] = [ 'label' => 'Speaker Dashboard', 'url' => home_url( '/speaker-dashboard/' ), 'key' => 'speaker-dashboard' ];
            $items[] = [ 'label' => 'Sign Out', 'url' => wp_logout_url( home_url( '/speaker-login/' ) ), 'key' => 'logout' ];
        } elseif ( in_array( 'tc_partner', $roles, true ) ) {
            $items[] = [ 'label' => 'Partner Dashboard', 'url' => home_url( '/partner-dashboard/' ), 'key' => 'partner-dashboard' ];
            $items[] = [ 'label' => 'Sign Out', 'url' => wp_logout_url( home_url( '/partner-login/' ) ), 'key' => 'logout' ];
        } else {
            $items[] = [ 'label' => 'Speaker Login', 'url' => home_url( '/speaker-login/' ), 'key' => 'speaker-login' ];
            $items[] = [ 'label' => 'Partner Login', 'url' => home_url( '/partner-login/' ), 'key' => 'partner-login' ];
        }
        return $items;
    }

    private static function active_key(): string {
        $path = trim( (string) parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ), '/' );
        if ( $path === '' ) return 'home';
        if ( preg_match( '#^book/#', $path ) ) return 'booking';
        if ( preg_match( '#^partner/#', $path ) ) return 'booking';
        if ( preg_match( '#^speaker/#', $path ) ) return self::agenda_enabled() ? 'agenda' : 'booking';
        $first = explode( '/', $path )[0] ?? '';
        return $first ?: 'home';
    }

    public static function render( array $args = [] ): string {
        $ctx = self::event_context();
        $active = self::active_key();
        $items = self::items();
        ob_start(); ?>
        <header class="tc-system-global-nav" data-tc-system-nav>
            <div class="tc-system-nav-inner">
                <a class="tc-system-brand" href="<?php echo esc_url( home_url( '/' ) ); ?>" aria-label="Media Interviews Home">
                    <img src="<?php echo esc_url( $ctx['logo_url'] ); ?>" alt="TechCon Global" loading="eager">
                    <span class="tc-system-brand-divider" aria-hidden="true"></span>
                    <span class="tc-system-brand-copy"><strong><?php echo esc_html( $ctx['system_title'] ); ?></strong><small><?php echo esc_html( $ctx['event_name'] ); ?></small></span>
                </a>
                <nav class="tc-system-nav-links" aria-label="Media Interviews Navigation">
                    <?php foreach ( $items as $item ) : ?>
                        <a class="<?php echo esc_attr( $active === $item['key'] ? 'is-active' : '' ); ?>" href="<?php echo esc_url( $item['url'] ); ?>"><?php echo esc_html( $item['label'] ); ?></a>
                    <?php endforeach; ?>
                </nav>
                <div class="tc-system-nav-actions">
                    <button type="button" class="tc-system-back" data-tc-system-back>Back</button>
                    <button type="button" class="tc-system-menu-btn" data-tc-system-menu aria-label="Open navigation" aria-expanded="false"><span></span><span></span><span></span></button>
                </div>
            </div>
            <div class="tc-system-drawer-backdrop" data-tc-system-close></div>
            <aside class="tc-system-drawer" aria-label="Navigation drawer">
                <div class="tc-system-drawer-head">
                    <div><strong><?php echo esc_html( $ctx['system_title'] ); ?></strong><small><?php echo esc_html( $ctx['event_name'] ); ?></small></div>
                    <button type="button" data-tc-system-close aria-label="Close navigation">×</button>
                </div>
                <div class="tc-system-drawer-links">
                    <?php foreach ( $items as $item ) : ?>
                        <a class="<?php echo esc_attr( $active === $item['key'] ? 'is-active' : '' ); ?>" href="<?php echo esc_url( $item['url'] ); ?>"><?php echo esc_html( $item['label'] ); ?></a>
                    <?php endforeach; ?>
                </div>
                <div class="tc-system-drawer-help">Need help? Contact the TechCon coordination team.</div>
            </aside>
        </header>
        <?php return ob_get_clean();
    }

    public static function enqueue_assets(): void {
        $css = self::css();
        if ( wp_style_is( 'tcb-booking', 'registered' ) || wp_style_is( 'tcb-booking', 'enqueued' ) ) {
            wp_add_inline_style( 'tcb-booking', $css );
        } else {
            wp_register_style( 'tcb-system-nav', false, [], defined( 'TCB_VERSION' ) ? TCB_VERSION : '1.0.0' );
            wp_enqueue_style( 'tcb-system-nav' );
            wp_add_inline_style( 'tcb-system-nav', $css );
        }
        wp_register_script( 'tcb-system-nav', false, [], defined( 'TCB_VERSION' ) ? TCB_VERSION : '1.0.0', true );
        wp_enqueue_script( 'tcb-system-nav' );
        wp_add_inline_script( 'tcb-system-nav', self::js() );
    }

    public static function css(): string { return <<<'CSS'
:root{--tc-nav-bg:rgba(7,7,22,.86);--tc-nav-border:rgba(255,255,255,.10);--tc-nav-text:#ffffff;--tc-nav-muted:rgba(255,255,255,.62);--tc-nav-pink:#e61a84;--tc-nav-purple:#4e24c0;--tc-nav-card:#120820;}
body{padding-top:76px!important;}
body.tca-agenda-standalone-body,body.tcb-booking-body{padding-top:76px!important;}
.tc-system-global-nav,.tc-system-global-nav *{box-sizing:border-box}.tc-system-global-nav{position:fixed;top:0;left:0;right:0;z-index:2147482000;background:var(--tc-nav-bg);border-bottom:1px solid var(--tc-nav-border);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);box-shadow:0 14px 48px rgba(0,0,0,.32);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;color:var(--tc-nav-text)}.tc-system-nav-inner{width:100%;max-width:1420px;margin:0 auto;min-height:76px;padding:0 22px;display:flex;align-items:center;gap:22px}.tc-system-brand{display:flex;align-items:center;gap:13px;text-decoration:none!important;color:#fff!important;min-width:0}.tc-system-brand img{height:34px;width:auto;max-width:178px;object-fit:contain;display:block}.tc-system-brand-divider{width:1px;height:30px;background:rgba(255,255,255,.15);display:block}.tc-system-brand-copy{display:flex;flex-direction:column;gap:2px;line-height:1.1;min-width:0}.tc-system-brand-copy strong{font-size:14px;font-weight:900;letter-spacing:.055em;text-transform:uppercase;color:#fff;white-space:nowrap}.tc-system-brand-copy small{font-size:11px;font-weight:800;letter-spacing:.02em;color:var(--tc-nav-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:220px}.tc-system-nav-links{display:flex;align-items:center;gap:8px;margin-left:auto}.tc-system-nav-links a{min-height:38px;display:inline-flex;align-items:center;justify-content:center;padding:9px 14px;border-radius:999px;text-decoration:none!important;color:rgba(255,255,255,.74)!important;font-size:13px;font-weight:850;letter-spacing:.005em;line-height:1;transition:.2s ease}.tc-system-nav-links a:hover,.tc-system-nav-links a.is-active{background:rgba(255,255,255,.075);color:#fff!important}.tc-system-nav-links a.is-active{box-shadow:inset 0 0 0 1px rgba(230,26,132,.35)}.tc-system-nav-actions{display:flex;align-items:center;gap:10px}.tc-system-back{min-height:38px;padding:9px 14px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.055);color:rgba(255,255,255,.82);font-size:13px;font-weight:850;cursor:pointer}.tc-system-back:before{content:"←";color:#ff77be;margin-right:7px}.tc-system-menu-btn{width:42px;height:42px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.055);display:none;align-items:center;justify-content:center;flex-direction:column;gap:5px;cursor:pointer}.tc-system-menu-btn span{width:18px;height:2px;border-radius:99px;background:#fff;display:block}.tc-system-drawer-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.55);opacity:0;visibility:hidden;transition:.22s ease;z-index:2147482001}.tc-system-drawer{position:fixed;top:0;right:0;height:100vh;width:min(390px,88vw);background:linear-gradient(180deg,#120820,#070716);border-left:1px solid rgba(255,255,255,.12);box-shadow:-24px 0 80px rgba(0,0,0,.65);transform:translateX(105%);transition:.28s cubic-bezier(.23,1,.32,1);z-index:2147482002;padding:20px;display:flex;flex-direction:column;gap:18px}.tc-system-drawer-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;border-bottom:1px solid rgba(255,255,255,.09);padding-bottom:18px}.tc-system-drawer-head strong{display:block;font-size:18px;font-weight:950;color:#fff;letter-spacing:.04em;text-transform:uppercase}.tc-system-drawer-head small{display:block;margin-top:4px;color:rgba(255,255,255,.58);font-weight:750}.tc-system-drawer-head button{width:40px;height:40px;border-radius:14px;border:1px solid rgba(255,255,255,.13);background:rgba(255,255,255,.06);color:#fff;font-size:25px;line-height:1;cursor:pointer}.tc-system-drawer-links{display:grid;gap:10px}.tc-system-drawer-links a{display:flex;align-items:center;min-height:52px;border-radius:18px;background:rgba(255,255,255,.045);border:1px solid rgba(255,255,255,.08);padding:15px 16px;color:#fff!important;text-decoration:none!important;font-size:15px;font-weight:850}.tc-system-drawer-links a.is-active{background:linear-gradient(90deg,rgba(230,26,132,.25),rgba(78,36,192,.18));border-color:rgba(230,26,132,.38)}.tc-system-drawer-help{margin-top:auto;color:rgba(255,255,255,.56);font-size:13px;line-height:1.5;border-top:1px solid rgba(255,255,255,.09);padding-top:16px}.tc-system-nav-open .tc-system-drawer-backdrop{opacity:1;visibility:visible}.tc-system-nav-open .tc-system-drawer{transform:translateX(0)}
@media(max-width:1040px){.tc-system-nav-links{display:none}.tc-system-menu-btn{display:flex}.tc-system-back{display:none}.tc-system-nav-inner{min-height:68px;padding:0 16px}.tc-system-global-nav{box-shadow:0 12px 38px rgba(0,0,0,.42)}body,body.tca-agenda-standalone-body,body.tcb-booking-body{padding-top:68px!important}.tc-system-brand img{height:30px;max-width:158px}.tc-system-brand-copy strong{font-size:13px}.tc-system-brand-copy small{max-width:170px}.tc-system-brand-divider{height:26px}}
@media(max-width:560px){.tc-system-nav-inner{gap:10px;padding:0 12px}.tc-system-brand{gap:9px}.tc-system-brand img{height:28px;max-width:132px}.tc-system-brand-divider{display:none}.tc-system-brand-copy strong{font-size:12px;letter-spacing:.035em}.tc-system-brand-copy small{font-size:10px;max-width:132px}.tc-system-menu-btn{width:40px;height:40px;border-radius:13px}.tc-system-drawer{width:min(360px,92vw);padding:16px}.tc-system-drawer-links a{min-height:50px;border-radius:16px;font-size:14px}}
CSS; }

    public static function js(): string { return <<<'JS'
(function(){function ready(fn){if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);}ready(function(){document.querySelectorAll('[data-tc-system-nav]').forEach(function(nav){var open=nav.querySelector('[data-tc-system-menu]');var closers=nav.querySelectorAll('[data-tc-system-close]');function set(v){nav.classList.toggle('tc-system-nav-open',v);if(open)open.setAttribute('aria-expanded',v?'true':'false');document.documentElement.classList.toggle('tc-system-drawer-open',v);}if(open)open.addEventListener('click',function(){set(!nav.classList.contains('tc-system-nav-open'));});closers.forEach(function(c){c.addEventListener('click',function(){set(false);});});document.addEventListener('keydown',function(e){if(e.key==='Escape')set(false);});});document.querySelectorAll('[data-tc-system-back]').forEach(function(b){b.addEventListener('click',function(e){e.preventDefault();if(window.history.length>1){window.history.back();}else{window.location.href='/';}});});});})();
JS; }
}

if ( ! function_exists( 'tcb_system_navigation_render' ) ) {
    function tcb_system_navigation_render( array $args = [] ): string {
        return SystemNavigation::render( $args );
    }
}
