<?php
namespace TCA\Frontend;
use TCA\DB\SpeakersDAO;
use TCA\Installer;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class ProfilePages {
    public static function init(): void { add_action( 'template_redirect', [ self::class, 'intercept_speaker_url' ] ); }

    public static function intercept_speaker_url(): void {
        $path = trim( (string) parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ), '/' );
        if ( preg_match( '#^speaker/([^/]+)$#i', $path, $matches ) ) {
            $speaker = SpeakersDAO::get_by_slug( sanitize_title( $matches[1] ) );
            if ( ! $speaker ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); return; }
            self::render_profile( $speaker ); exit;
        }
    }

    private static function initials( string $name ): string {
        $parts = preg_split( '/\s+/', trim( $name ) ); $out = '';
        foreach ( $parts as $part ) { if ( $part !== '' ) $out .= strtoupper( substr( $part, 0, 1 ) ); }
        return substr( $out ?: 'TC', 0, 2 );
    }

    private static function speaker_event_label( int $speaker_id ): string {
        global $wpdb;
        $event = $wpdb->get_row( $wpdb->prepare(
            "SELECT e.name FROM " . Installer::t_events() . " e INNER JOIN " . Installer::t_event_speakers() . " es ON es.event_id = e.id WHERE es.speaker_id = %d ORDER BY CASE WHEN e.status = 'live' THEN 0 ELSE 1 END, e.created_at DESC LIMIT 1",
            $speaker_id
        ), ARRAY_A );
        $name = trim( (string) ( $event['name'] ?? '' ) );
        return $name ? $name . ' Speaker' : 'TechCon SoCal 2026 Speaker';
    }

    private static function render_profile( array $speaker ): void {
        status_header( 200 );
        global $wp_query;
        if ( $wp_query ) {
            $wp_query->is_404  = false;
            $wp_query->is_page = true;
        }

        $speaker_name = trim( (string) ( $speaker['name'] ?? '' ) );
        $event_label  = trim( (string) ( $speaker['profile_tag'] ?? '' ) ) ?: self::speaker_event_label( (int) ( $speaker['id'] ?? 0 ) );
        $page_title   = trim( $speaker_name . ' — ' . $event_label );
        add_filter( 'pre_get_document_title', static function() use ( $page_title ) { return $page_title; }, 99 );
        add_filter( 'document_title_parts', static function( $parts ) use ( $page_title ) { $parts['title'] = $page_title; return $parts; }, 99 );

        $is_speaker = is_user_logged_in() && in_array( 'tc_speaker', (array) wp_get_current_user()->roles, true );
        $title_line = trim( ( $speaker['position'] ?? '' ) . ( ! empty( $speaker['company'] ) ? ' · ' . $speaker['company'] : '' ) );
        ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo esc_html( $page_title ); ?></title>
<?php wp_head(); ?>
</head>
<body class="tc-system-body tc-speaker-profile-body">
<?php echo function_exists( 'TCB\\Frontend\\tcb_system_navigation_render' ) ? \TCB\Frontend\tcb_system_navigation_render() : ( class_exists( '\\TCB\\Frontend\\SystemNavigation' ) ? \TCB\Frontend\SystemNavigation::render() : '' ); ?>
        <main class="tc-speaker-public" style="min-height:70vh;background:radial-gradient(circle at 18% 8%,rgba(230,26,132,.18),transparent 32%),radial-gradient(circle at 88% 12%,rgba(78,36,192,.22),transparent 36%),linear-gradient(180deg,#050507 0%,#090711 52%,#050507 100%);padding:48px 18px 58px;color:#fff;font-family:Inter,Arial,sans-serif;">
            <style>
                .tcsp-card{max-width:1040px;margin:0 auto;background:linear-gradient(135deg,rgba(255,255,255,.07),rgba(255,255,255,.022));border:1px solid rgba(255,255,255,.10);border-radius:28px;overflow:hidden;box-shadow:0 28px 90px rgba(0,0,0,.45)}
                .tcsp-hero{display:grid;grid-template-columns:190px 1fr;gap:32px;padding:40px;background:radial-gradient(circle at 10% 10%,rgba(230,26,132,.22),transparent 35%),radial-gradient(circle at 90% 20%,rgba(78,36,192,.30),transparent 42%)}
                .tcsp-photo,.tcsp-initials{width:170px;height:170px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,.18);box-shadow:0 18px 45px rgba(0,0,0,.42),0 0 0 6px rgba(230,26,132,.10)}
                .tcsp-initials{display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#e61a84,#4e24c0);font-size:48px;font-weight:900}
                .tcsp-badge{display:inline-flex;padding:7px 13px;border-radius:999px;border:1px solid rgba(230,26,132,.45);color:#ff9bd1;background:rgba(230,26,132,.12);font-size:11px;font-weight:850;letter-spacing:.08em;text-transform:uppercase}
                .tcsp-name{font-size:clamp(32px,4.6vw,56px);line-height:1;margin:18px 0 10px;font-weight:900;letter-spacing:-.04em}.tcsp-title{font-size:16px;color:rgba(255,255,255,.72);margin:0 0 14px}.tcsp-bio{padding:32px 40px;font-size:15.5px;line-height:1.75;color:rgba(255,255,255,.78);background:rgba(0,0,0,.12);border-top:1px solid rgba(255,255,255,.08)}
                .tcsp-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:20px}.tcsp-btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 15px;border-radius:999px;text-decoration:none;font-weight:800;font-size:14px;line-height:1.1}.tcsp-primary{background:linear-gradient(135deg,#e61a84,#4e24c0);color:#fff;box-shadow:0 10px 26px rgba(230,26,132,.22)}.tcsp-ghost{border:1px solid rgba(255,255,255,.2);color:#fff;background:rgba(255,255,255,.035)}.tcsp-back{max-width:1040px;margin:0 auto 18px}.tcsp-back a{color:rgba(255,255,255,.7);text-decoration:none;font-size:14px}.tcsp-meta{display:flex;flex-wrap:wrap;gap:8px;margin:16px 0 0}.tcsp-meta-chip{display:inline-flex;align-items:center;padding:7px 11px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.045);border-radius:999px;color:rgba(255,255,255,.76);font-size:12.5px}
                @media(max-width:760px){.tcsp-hero{grid-template-columns:1fr;padding:28px;text-align:center}.tcsp-photo,.tcsp-initials{width:140px;height:140px;margin:0 auto}.tcsp-bio{padding:26px}.tcsp-actions,.tcsp-meta{justify-content:center}.tcsp-name{font-size:34px}}
            </style>
            
            <section class="tcsp-card">
                <div class="tcsp-hero">
                    <div><?php if ( ! empty( $speaker['image_url'] ) ) : ?><img class="tcsp-photo" src="<?php echo esc_url( $speaker['image_url'] ); ?>" alt="<?php echo esc_attr( $speaker_name ); ?>"><?php else : ?><div class="tcsp-initials"><?php echo esc_html( self::initials( $speaker_name ) ); ?></div><?php endif; ?></div>
                    <div>
                        <span class="tcsp-badge"><?php echo esc_html( $event_label ); ?></span>
                        <h1 class="tcsp-name"><?php echo esc_html( $speaker_name ); ?></h1>
                        <?php if ( $title_line ) : ?><p class="tcsp-title"><?php echo esc_html( $title_line ); ?></p><?php endif; ?>
                        <div class="tcsp-meta" aria-label="Speaker profile details">
                            <?php if ( ! empty( $speaker['position'] ) ) : ?><span class="tcsp-meta-chip"><?php echo esc_html( $speaker['position'] ); ?></span><?php endif; ?>
                            <?php if ( ! empty( $speaker['company'] ) ) : ?><span class="tcsp-meta-chip"><?php echo esc_html( $speaker['company'] ); ?></span><?php endif; ?>
                            <?php if ( ! empty( $event_label ) ) : ?><span class="tcsp-meta-chip"><?php echo esc_html( $event_label ); ?></span><?php endif; ?>
                        </div>
                        <div class="tcsp-actions">
                            <?php if ( ! empty( $speaker['linkedin_url'] ) ) : ?><a class="tcsp-btn tcsp-ghost" href="<?php echo esc_url( $speaker['linkedin_url'] ); ?>" target="_blank" rel="noopener">LinkedIn</a><?php endif; ?>
                            <?php if ( $is_speaker ) : ?><a class="tcsp-btn tcsp-primary" href="<?php echo esc_url( home_url('/booking/') ); ?>">Book Interviews</a><?php else : ?><a class="tcsp-btn tcsp-primary" href="<?php echo esc_url( home_url('/speaker-login/') ); ?>">Login to Book</a><?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php if ( ! empty( $speaker['bio'] ) ) : ?><div class="tcsp-bio"><strong>About</strong><?php echo wpautop( wp_kses_post( $speaker['bio'] ) ); ?></div><?php endif; ?>
            </section>
        </main>
        <?php wp_footer(); ?>
</body></html><?php
    }
}
