<?php
// AI_TERCİH_NEW_PROGRAM_EMSAL_TBS_20260724
// AI_TERCİH_NEW_PROGRAM_BURS_UYUMLU_EMSAL_TBS_20260724
// AI_TERCİH_CHAT_CHATGPT_SIDEBAR_20260724
// AI_TERCİH_CHAT_OWNER_MULTI_SESSION_RESET_20260723
declare(strict_types=1);
session_start();

/*
 |--------------------------------------------------------------------------
 | SAHİP / YÖNETİCİ SINIRSIZ TEST ERİŞİMİ
 |--------------------------------------------------------------------------
 | Gizli bağlantı doğru anahtarla açıldığında bu tarayıcıya 1 yıl boyunca
 | ücretsiz ve sınırsız PDF yükleme yetkisi verilir.
 | Müşterilerin normal PayTR ödeme akışı bundan etkilenmez.
 */
const AI_OWNER_ACCESS_TOKEN_HASH = 'cee9481dd15945cd09478857a2ad60846f97a28a3c41ef7407efd2f992dc26c6';
const AI_OWNER_COOKIE_NAME = 'tr_ai_owner_unlimited';
const AI_OWNER_BROWSER_COOKIE_NAME = 'tr_ai_owner_browser_id';

function ai_owner_cookie_expected_value(): string {
    return hash_hmac('sha256', 'tercih-robotu-owner-unlimited-v1', AI_OWNER_ACCESS_TOKEN_HASH);
}

function ai_owner_request_is_https(): bool {
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
}

function ai_owner_browser_id(): string {
    $browserId = strtolower(trim((string)($_COOKIE[AI_OWNER_BROWSER_COOKIE_NAME] ?? '')));
    if (!preg_match('/^[a-f0-9]{64}$/', $browserId)) {
        try {
            $browserId = bin2hex(random_bytes(32));
        } catch (Throwable $e) {
            $browserId = hash('sha256', uniqid('owner-browser-', true) . '|' . microtime(true));
        }

        setcookie(AI_OWNER_BROWSER_COOKIE_NAME, $browserId, [
            'expires' => time() + (86400 * 365),
            'path' => '/',
            'secure' => ai_owner_request_is_https(),
            'httponly' => true,
            'samesite' => 'Strict',
        ]);
        $_COOKIE[AI_OWNER_BROWSER_COOKIE_NAME] = $browserId;
    }

    return $browserId;
}

function ai_owner_customer_key(string $browserId): string {
    return hash(
        'sha256',
        'tercih-robotu-owner-browser-account-v1|'
        . $browserId
        . '|'
        . AI_OWNER_ACCESS_TOKEN_HASH
    );
}

if (isset($_GET['owner_exit'])) {
    unset($_SESSION['ai_owner_unlimited']);
    setcookie(AI_OWNER_COOKIE_NAME, '', [
        'expires' => time() - 3600,
        'path' => '/',
        'secure' => ai_owner_request_is_https(),
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    unset($_COOKIE[AI_OWNER_COOKIE_NAME]);
    header('Location: /ia-step1.php');
    exit;
}

$ownerAccessKey = trim((string)($_GET['owner_key'] ?? ''));
if ($ownerAccessKey !== ''
    && hash_equals(AI_OWNER_ACCESS_TOKEN_HASH, hash('sha256', $ownerAccessKey))) {

    $_SESSION['ai_owner_unlimited'] = true;
    ai_owner_browser_id();

    $ownerCookieValue = ai_owner_cookie_expected_value();
    setcookie(AI_OWNER_COOKIE_NAME, $ownerCookieValue, [
        'expires' => time() + (86400 * 365),
        'path' => '/',
        'secure' => ai_owner_request_is_https(),
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    $_COOKIE[AI_OWNER_COOKIE_NAME] = $ownerCookieValue;

    // Gizli anahtar tarayıcı adres çubuğunda ve geçmişte kalmasın.
    header('Location: /ia-step1.php?owner=active');
    exit;
}

$ownerCookieValue = trim((string)($_COOKIE[AI_OWNER_COOKIE_NAME] ?? ''));
$ownerCookieValid = $ownerCookieValue !== ''
    && hash_equals(ai_owner_cookie_expected_value(), $ownerCookieValue);

$ownerUnlimited = !empty($_SESSION['ai_owner_unlimited']) || $ownerCookieValid;
if ($ownerUnlimited) {
    $_SESSION['ai_owner_unlimited'] = true;
    ai_owner_browser_id();
}

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

/*
 |--------------------------------------------------------------------------
 | YAPAY ZEKA KULLANIM MODU
 |--------------------------------------------------------------------------
 | Test sırasında sınırsız ve ücretsiz kullanım için: 'bedava'
 | Sonuç belgesi paketi kontrolünü açmak için:          'ucretli'
 */
$aiKullanimModu = 'ucretli';
$aiKullanimModu = strtolower(trim($aiKullanimModu));
if (!in_array($aiKullanimModu, ['bedava', 'ucretli'], true)) {
    $aiKullanimModu = 'ucretli';
}
$ucretsizSinirsizMod = $aiKullanimModu === 'bedava' || $ownerUnlimited;

$paymentUrl = '/paytr_odeme.php';
$pdfUploadUrl = '/ia-step1.php';

$paytrConfigCandidates = [
    __DIR__ . '/../paytr_config.php',
    __DIR__ . '/paytr_config.php',
];
foreach ($paytrConfigCandidates as $candidate) {
    if (is_file($candidate)) {
        require_once $candidate;
        break;
    }
}

$pdfPackages = [
    'pdf_1'   => ['price' => 200.00, 'pdf_rights' => 1, 'name' => '1 Sonuç Belgesi'],
    'pdf_50'  => ['price' => 2500.00, 'pdf_rights' => 50, 'name' => '50 Sonuç Belgesi'],
    'pdf_200' => ['price' => 7500.00, 'pdf_rights' => 200, 'name' => '200 Sonuç Belgesi'],
    'pdf_500' => ['price' => 12500.00, 'pdf_rights' => 500, 'name' => '500 Sonuç Belgesi'],
];

if (!isset($_SESSION['paytr_activation_csrf'])
    || !is_string($_SESSION['paytr_activation_csrf'])
    || strlen($_SESSION['paytr_activation_csrf']) < 32) {
    $_SESSION['paytr_activation_csrf'] = bin2hex(random_bytes(24));
}

$activationFlashError = trim((string)($_SESSION['paytr_activation_flash_error'] ?? ''));
$activationFlashSuccess = trim((string)($_SESSION['paytr_activation_flash_success'] ?? ''));
unset($_SESSION['paytr_activation_flash_error'], $_SESSION['paytr_activation_flash_success']);

if ((string)($_GET['activation_logout'] ?? '') === '1') {
    if (function_exists('paytr_activation_forget_browser')) {
        paytr_activation_forget_browser();
    }

    $ownerFlag = $_SESSION['ai_owner_unlimited'] ?? null;
    foreach (array_keys($_SESSION) as $sessionKey) {
        if (str_starts_with((string)$sessionKey, 'ai_')
            || in_array($sessionKey, [
                'step1','step2','step3','step4','step4_program','step5',
                'pdflog_id','pdflog_pdf_path','pdflog_pdf_original',
            ], true)) {
            unset($_SESSION[$sessionKey]);
        }
    }
    if ($ownerFlag !== null) $_SESSION['ai_owner_unlimited'] = $ownerFlag;

    header('Location: /ia-tercih-robotu/');
    exit;
}

if ((string)($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST'
    && (string)($_POST['activation_action'] ?? '') === 'login') {

    $postedCsrf = (string)($_POST['activation_csrf'] ?? '');
    $sessionCsrf = (string)($_SESSION['paytr_activation_csrf'] ?? '');

    if ($postedCsrf === '' || $sessionCsrf === '' || !hash_equals($sessionCsrf, $postedCsrf)) {
        $_SESSION['paytr_activation_flash_error'] = 'Güvenlik doğrulaması başarısız. Tekrar deneyin.';
        header('Location: /ia-tercih-robotu/');
        exit;
    }

    try {
        if (!function_exists('paytr_activation_authenticate')) {
            throw new RuntimeException('Aktivasyon sistemi dosyası bulunamadı.');
        }

        $activationAccount = paytr_activation_authenticate(
            trim((string)($_POST['activation_code'] ?? ''))
        );

        if (!is_array($activationAccount)) {
            throw new RuntimeException('Aktivasyon kodu hatalı veya kullanıma kapatılmış.');
        }

        $ownerFlag = $_SESSION['ai_owner_unlimited'] ?? null;
        foreach (array_keys($_SESSION) as $sessionKey) {
            if (str_starts_with((string)$sessionKey, 'ai_')
                || in_array($sessionKey, [
                    'step1','step2','step3','step4','step4_program','step5',
                    'pdflog_id','pdflog_pdf_path','pdflog_pdf_original',
                ], true)) {
                unset($_SESSION[$sessionKey]);
            }
        }
        if ($ownerFlag !== null) $_SESSION['ai_owner_unlimited'] = $ownerFlag;

        paytr_activation_bind_browser($activationAccount);
        $activationCustomerKey = (string)$activationAccount['customer_key'];

        if (function_exists('paytr_sync_pdf_rights_to_session')) {
            paytr_sync_pdf_rights_to_session($activationCustomerKey);
        }

        $_SESSION['paytr_activation_flash_success']
            = 'Aktivasyon koduyla giriş yapıldı. Kalan haklarınız ve sohbetleriniz yüklendi.';

        $loginProfiles = function_exists('paytr_list_pdf_profiles')
            ? paytr_list_pdf_profiles($activationCustomerKey)
            : [];

        if ($loginProfiles && !empty($loginProfiles[0]['pdf_key'])) {
            header(
                'Location: /ia-tercih-robotu/?pdf='
                . rawurlencode((string)$loginProfiles[0]['pdf_key'])
                . '&aktivasyon=basarili'
            );
        } else {
            header('Location: /ia-tercih-robotu/?aktivasyon=basarili');
        }
        exit;
    } catch (Throwable $e) {
        $_SESSION['paytr_activation_flash_error'] = $e->getMessage();
        header('Location: /ia-tercih-robotu/');
        exit;
    }
}

$paymentCustomerKey = $ownerUnlimited
    ? ai_owner_customer_key(ai_owner_browser_id())
    : (function_exists('paytr_customer_key')
        ? paytr_customer_key(true)
        : trim((string)($_SESSION['tr_pdf_customer'] ?? $_COOKIE['tr_pdf_customer'] ?? '')));

/*
 |--------------------------------------------------------------------------
 | YÖNETİCİYE ÖZEL SOHBET OTURUMU YÖNETİMİ
 |--------------------------------------------------------------------------
 | Bu işlemler yalnız owner_key ile açılmış mevcut tarayıcı oturumunda çalışır.
 | Kalıcı kayıtta sadece bu tarayıcıya ait customer_key değiştirilir; başka
 | ödeme yapan kullanıcıların hesaplarına veya PDF oturumlarına dokunulmaz.
 */
if ($ownerUnlimited
    && (!isset($_SESSION['ai_owner_session_csrf'])
        || !is_string($_SESSION['ai_owner_session_csrf'])
        || strlen($_SESSION['ai_owner_session_csrf']) < 32)) {
    $_SESSION['ai_owner_session_csrf'] = bin2hex(random_bytes(24));
}

function ai_owner_clear_active_runtime_session(?string $pdfKey = null, bool $clearAll = false): void {
    $preserveAiKeys = ['ai_owner_unlimited', 'ai_owner_session_csrf'];

    if ($clearAll) {
        foreach (array_keys($_SESSION) as $sessionKey) {
            $sessionKey = (string)$sessionKey;
            if (str_starts_with($sessionKey, 'ai_')
                && !in_array($sessionKey, $preserveAiKeys, true)) {
                unset($_SESSION[$sessionKey]);
            }
        }

        unset(
            $_SESSION['step1'],
            $_SESSION['step2'],
            $_SESSION['step3'],
            $_SESSION['step4'],
            $_SESSION['step4_program'],
            $_SESSION['step5'],
            $_SESSION['pdflog_id'],
            $_SESSION['pdflog_pdf_path'],
            $_SESSION['pdflog_pdf_original'],
            $_SESSION['pdflog_full_name']
        );
        return;
    }

    $pdfKey = trim((string)$pdfKey);
    if ($pdfKey === '') return;

    if (isset($_SESSION['ai_pdf_chat_states']) && is_array($_SESSION['ai_pdf_chat_states'])) {
        unset($_SESSION['ai_pdf_chat_states'][$pdfKey]);
    }
    if (isset($_SESSION['ai_authorized_pdf_keys']) && is_array($_SESSION['ai_authorized_pdf_keys'])) {
        unset($_SESSION['ai_authorized_pdf_keys'][$pdfKey]);
    }

    $currentKey = trim((string)(
        $_SESSION['ai_current_pdf_key']
        ?? ($_SESSION['step1']['ai_pdf_access_key'] ?? '')
    ));

    if ($currentKey !== $pdfKey) return;

    foreach (array_keys($_SESSION) as $sessionKey) {
        $sessionKey = (string)$sessionKey;
        if (str_starts_with($sessionKey, 'ai_')
            && !in_array($sessionKey, $preserveAiKeys, true)) {
            unset($_SESSION[$sessionKey]);
        }
    }

    unset(
        $_SESSION['step1'],
        $_SESSION['step2'],
        $_SESSION['step3'],
        $_SESSION['step4'],
        $_SESSION['step4_program'],
        $_SESSION['step5'],
        $_SESSION['pdflog_id'],
        $_SESSION['pdflog_pdf_path'],
        $_SESSION['pdflog_pdf_original'],
        $_SESSION['pdflog_full_name']
    );
}

if ((string)($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST'
    && isset($_POST['owner_session_action'])) {

    if (!$ownerUnlimited) {
        http_response_code(403);
        exit('Bu işlem yalnız yönetici test girişinde kullanılabilir.');
    }

    $postedCsrf = (string)($_POST['owner_session_csrf'] ?? '');
    $sessionCsrf = (string)($_SESSION['ai_owner_session_csrf'] ?? '');
    if ($postedCsrf === '' || $sessionCsrf === '' || !hash_equals($sessionCsrf, $postedCsrf)) {
        http_response_code(403);
        exit('Güvenlik doğrulaması başarısız.');
    }

    $ownerAction = (string)($_POST['owner_session_action'] ?? '');
    $targetPdfKey = trim((string)($_POST['pdf_key'] ?? ''));
    $clearAllOwnerSessions = $ownerAction === 'clear_all';

    if (!$clearAllOwnerSessions
        && ($ownerAction !== 'delete_one'
            || !preg_match('/^[a-f0-9]{64}$/', $targetPdfKey))) {
        http_response_code(400);
        exit('Geçersiz yönetici oturum işlemi.');
    }

    if ($paymentCustomerKey === ''
        || !function_exists('paytr_mutate_pdf_rights')
        || !function_exists('paytr_normalize_pdf_account')) {
        http_response_code(500);
        exit('Oturum kayıt sistemi kullanılamıyor.');
    }

    try {
        paytr_mutate_pdf_rights(
            function (&$accounts) use (
                $paymentCustomerKey,
                $clearAllOwnerSessions,
                $targetPdfKey
            ) {
                $account = paytr_normalize_pdf_account(
                    $accounts[$paymentCustomerKey] ?? []
                );

                if (!isset($account['authorized_pdfs'])
                    || !is_array($account['authorized_pdfs'])) {
                    $account['authorized_pdfs'] = [];
                }

                if ($clearAllOwnerSessions) {
                    $account['authorized_pdfs'] = [];
                } else {
                    unset($account['authorized_pdfs'][$targetPdfKey]);
                }

                $account['updated_at'] = date('Y-m-d H:i:s');
                $accounts[$paymentCustomerKey] = $account;
                return true;
            },
            false
        );
    } catch (Throwable $e) {
        @error_log('[OWNER-SESSION-RESET] ' . $e->getMessage());
        http_response_code(500);
        exit('Yönetici oturumları temizlenemedi.');
    }

    ai_owner_clear_active_runtime_session(
        $clearAllOwnerSessions ? null : $targetPdfKey,
        $clearAllOwnerSessions
    );

    if ($clearAllOwnerSessions) {
        $_SESSION['ai_owner_reset_flash'] = 'Yalnız bu yönetici tarayıcısına ait tüm PDF ve sohbet oturumları temizlendi.';
        header('Location: /ia-tercih-robotu/?owner_reset=1');
    } else {
        $_SESSION['ai_owner_reset_flash'] = 'Seçili yönetici PDF/sohbet oturumu kaldırıldı.';
        header('Location: /ia-tercih-robotu/?owner_session_removed=1');
    }
    exit;
}

/*
 |--------------------------------------------------------------------------
 | TEK T.C. = TEK PDF / TEK SOHBET OTURUMU
 |--------------------------------------------------------------------------
 | Aynı T.C. için geçmişte yanlışlıkla oluşmuş birden fazla PDF anahtarı varsa
 | konuşma geçmişi en dolu olan profil korunur, diğerleri kaldırılır.
 */

function ai_single_tc_profile_tckn(array $profile): string {
    $step1 = isset($profile['step1']) && is_array($profile['step1'])
        ? $profile['step1']
        : [];

    $tckn = preg_replace('/\D+/', '', (string)(
        $step1['tckn']
        ?? $step1['tc']
        ?? $step1['tc_kimlik_no']
        ?? $step1['tcno']
        ?? ''
    ));

    return strlen($tckn) === 11 ? $tckn : '';
}

function ai_single_tc_profile_time(array $profile): int {
    foreach (['uploaded_at', 'authorized_at', 'created_at', 'updated_at'] as $field) {
        $value = trim((string)($profile[$field] ?? ''));
        if ($value === '') continue;

        $time = strtotime($value);
        if ($time !== false && $time > 0) return $time;
    }

    return PHP_INT_MAX;
}

function ai_candidate_first_name_from_step1(array $step1): string {
    $fullName = trim((string)(
        $step1['full_name']
        ?? $step1['ad_soyad']
        ?? $step1['adsoyad']
        ?? $step1['adi_soyadi']
        ?? ''
    ));

    if ($fullName === '') return 'Sayın aday';

    $parts = preg_split('/\s+/u', $fullName) ?: [];
    $firstName = trim((string)($parts[0] ?? ''), " \t\n\r\0\x0B,;:");
    return $firstName !== '' ? $firstName : 'Sayın aday';
}

function ai_candidate_initial_greeting(string $firstName): string {
    $firstName = trim($firstName) !== '' ? trim($firstName) : 'Sayın aday';

    return $firstName
        . ", sonuç belgene göre sorduğun sorulara cevap vererek en doğru tercihi yapmana yardımcı olabilirim.\n\n"
        . "İstersen mevcut filtreleri adım adım da kullanabilirsin.\n\n"
        . "Ne yapmak istersin?";
}

function ai_repair_candidate_greeting_context(array $step1): bool {
    $firstName = ai_candidate_first_name_from_step1($step1);
    $correctGreeting = ai_candidate_initial_greeting($firstName);
    $changed = false;

    $isInitialGreeting = static function (string $text): bool {
        $normalized = strtr(mb_strtoupper($text, 'UTF-8'), [
            'İ' => 'I',
            'Ş' => 'S',
            'Ğ' => 'G',
            'Ü' => 'U',
            'Ö' => 'O',
            'Ç' => 'C',
        ]);

        return strpos(
            $normalized,
            'SONUC BELGENE GORE SORDUGUN SORULARA CEVAP VEREREK EN DOGRU TERCIHI YAPMANA YARDIMCI OLABILIRIM'
        ) !== false
        && strpos($normalized, 'NE YAPMAK ISTERSIN') !== false;
    };

    if (isset($_SESSION['ai_ui_chat_history'])
        && is_array($_SESSION['ai_ui_chat_history'])) {
        foreach ($_SESSION['ai_ui_chat_history'] as &$event) {
            if (!is_array($event)
                || (string)($event['type'] ?? '') !== 'message'
                || (string)($event['role'] ?? '') !== 'bot') {
                continue;
            }

            $text = trim((string)($event['text'] ?? ''));
            if (!$isInitialGreeting($text)) continue;

            if ($text !== $correctGreeting) {
                $event['text'] = $correctGreeting;
                $changed = true;
            }
        }
        unset($event);
    }

    if (isset($_SESSION['ai_chat_history'])
        && is_array($_SESSION['ai_chat_history'])) {
        foreach ($_SESSION['ai_chat_history'] as &$message) {
            if (!is_array($message)
                || (string)($message['role'] ?? '') !== 'assistant') {
                continue;
            }

            $text = trim((string)($message['content'] ?? ''));
            if (!$isInitialGreeting($text)) continue;

            if ($text !== $correctGreeting) {
                $message['content'] = $correctGreeting;
                $changed = true;
            }
        }
        unset($message);
    }

    return $changed;
}

function ai_single_tc_context_score(
    string $customerKey,
    string $pdfKey
): int {
    $score = 0;

    $sessionState = $_SESSION['ai_pdf_chat_states'][$pdfKey] ?? [];
    if (is_array($sessionState)) {
        $score += count(
            is_array($sessionState['ai_ui_chat_history'] ?? null)
                ? $sessionState['ai_ui_chat_history']
                : []
        ) * 100;

        $score += count(
            is_array($sessionState['ai_chat_history'] ?? null)
                ? $sessionState['ai_chat_history']
                : []
        ) * 10;
    }

    if (function_exists('paytr_activation_load_pdf_context')
        && $customerKey !== '') {
        try {
            $dbState = paytr_activation_load_pdf_context(
                $customerKey,
                $pdfKey
            );

            if (is_array($dbState)) {
                $score = max(
                    $score,
                    count(
                        is_array($dbState['ai_ui_chat_history'] ?? null)
                            ? $dbState['ai_ui_chat_history']
                            : []
                    ) * 100
                    + count(
                        is_array($dbState['ai_chat_history'] ?? null)
                            ? $dbState['ai_chat_history']
                            : []
                    ) * 10
                );
            }
        } catch (Throwable $e) {
            // Kalıcı sohbet kaydı okunamazsa session puanı kullanılmaya devam eder.
        }
    }

    return $score;
}

function ai_single_tc_choose_canonical_profile(
    string $customerKey,
    array $profiles
): ?array {
    if (!$profiles) return null;

    usort($profiles, function (array $a, array $b) use ($customerKey): int {
        $aKey = (string)($a['pdf_key'] ?? '');
        $bKey = (string)($b['pdf_key'] ?? '');

        $aScore = ai_single_tc_context_score($customerKey, $aKey);
        $bScore = ai_single_tc_context_score($customerKey, $bKey);

        // Önce konuşma geçmişi en dolu oturumu koru.
        if ($aScore !== $bScore) return $bScore <=> $aScore;

        // Eşitse ilk yüklenen profil ana profil olsun.
        $timeCompare = ai_single_tc_profile_time($a)
            <=> ai_single_tc_profile_time($b);

        if ($timeCompare !== 0) return $timeCompare;

        return strcmp($aKey, $bKey);
    });

    return $profiles[0];
}

$aiSingleTcCanonicalMap = [];
$aiSingleTcDuplicateKeys = [];

if (!$ownerUnlimited
    && $paymentCustomerKey !== ''
    && function_exists('paytr_list_pdf_profiles')) {

    $profilesBeforeSingleTcCleanup = paytr_list_pdf_profiles(
        $paymentCustomerKey
    );

    $activeKeyBeforeCleanup = trim((string)(
        $_SESSION['ai_current_pdf_key']
        ?? ($_SESSION['step1']['ai_pdf_access_key'] ?? '')
    ));

    if ($activeKeyBeforeCleanup !== ''
        && function_exists('paytr_store_ai_context_for_pdf')) {
        paytr_store_ai_context_for_pdf($activeKeyBeforeCleanup);
    }

    $groupsByTckn = [];

    foreach ($profilesBeforeSingleTcCleanup as $profile) {
        if (!is_array($profile)) continue;

        $pdfKey = trim((string)($profile['pdf_key'] ?? ''));
        $tckn = ai_single_tc_profile_tckn($profile);

        if ($tckn === '' || !preg_match('/^[a-f0-9]{64}$/', $pdfKey)) {
            continue;
        }

        $groupsByTckn[$tckn][] = $profile;
    }

    foreach ($groupsByTckn as $tckn => $sameTcProfiles) {
        $canonical = ai_single_tc_choose_canonical_profile(
            $paymentCustomerKey,
            $sameTcProfiles
        );

        if (!is_array($canonical)) continue;

        $canonicalKey = trim((string)($canonical['pdf_key'] ?? ''));
        if (!preg_match('/^[a-f0-9]{64}$/', $canonicalKey)) continue;

        $aiSingleTcCanonicalMap[$tckn] = $canonicalKey;

        foreach ($sameTcProfiles as $oneProfile) {
            $oneKey = trim((string)($oneProfile['pdf_key'] ?? ''));
            if ($oneKey === '' || $oneKey === $canonicalKey) continue;

            $aiSingleTcDuplicateKeys[$oneKey] = $canonicalKey;
        }
    }

    /*
     | Eski mükerrer anahtarları kalıcı müşteri hesabından kaldır.
     | Bakiye artırılmaz veya azaltılmaz; yalnız aynı T.C.'ye ait fazla
     | sohbet/PDF profilleri temizlenir.
     */
    if ($aiSingleTcDuplicateKeys
        && function_exists('paytr_mutate_pdf_rights')
        && function_exists('paytr_normalize_pdf_account')) {

        try {
            $duplicateMapForCleanup = $aiSingleTcDuplicateKeys;

            paytr_mutate_pdf_rights(
                function (&$accounts) use (
                    $paymentCustomerKey,
                    $duplicateMapForCleanup
                ) {
                    $account = paytr_normalize_pdf_account(
                        $accounts[$paymentCustomerKey] ?? []
                    );

                    foreach ($duplicateMapForCleanup as $duplicateKey => $canonicalKey) {
                        if ($duplicateKey === $canonicalKey) continue;
                        unset($account['authorized_pdfs'][$duplicateKey]);
                    }

                    $account['updated_at'] = date('Y-m-d H:i:s');
                    $accounts[$paymentCustomerKey] = $account;

                    return true;
                },
                false
            );
        } catch (Throwable $e) {
            @error_log(
                'Tek T.C. tek oturum temizliği yapılamadı: '
                . $e->getMessage()
            );
        }
    }

    // Eski mükerrer URL ile gelinirse ana oturuma yönlendir.
    $requestedBeforeCleanup = trim((string)($_GET['pdf'] ?? ''));
    if (isset($aiSingleTcDuplicateKeys[$requestedBeforeCleanup])) {
        $_GET['pdf'] = $aiSingleTcDuplicateKeys[$requestedBeforeCleanup];
    }

    // Aktif session mükerrer anahtardaysa ana PDF oturumuna geçir.
    if (isset($aiSingleTcDuplicateKeys[$activeKeyBeforeCleanup])) {
        $canonicalActiveKey =
            $aiSingleTcDuplicateKeys[$activeKeyBeforeCleanup];

        $_SESSION['ai_current_pdf_key'] = $canonicalActiveKey;

        if (isset($_SESSION['step1'])
            && is_array($_SESSION['step1'])) {
            $_SESSION['step1']['ai_pdf_access_key'] =
                $canonicalActiveKey;
            $_SESSION['step1']['ai_pdf_customer_key'] =
                $paymentCustomerKey;
        }

        if (!isset($_SESSION['ai_authorized_pdf_keys'])
            || !is_array($_SESSION['ai_authorized_pdf_keys'])) {
            $_SESSION['ai_authorized_pdf_keys'] = [];
        }

        $_SESSION['ai_authorized_pdf_keys'][$canonicalActiveKey] = true;

        foreach ($aiSingleTcDuplicateKeys as $duplicateKey => $canonicalKey) {
            if ($canonicalKey === $canonicalActiveKey) {
                unset($_SESSION['ai_authorized_pdf_keys'][$duplicateKey]);
            }
        }

        if (function_exists('paytr_restore_ai_context_for_pdf')) {
            paytr_restore_ai_context_for_pdf($canonicalActiveKey);
        }
    }
}

/*
 | AKTİF PDF'NİN GÖRÜNÜR SOHBETİNİ KAYDET
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && (string)($_GET['chat_history'] ?? '') === 'save') {

    header('Content-Type: application/json; charset=utf-8');

    $payload = json_decode((string)file_get_contents('php://input'), true);
    if (!is_array($payload)) $payload = $_POST;

    $savePdfKey = trim((string)($payload['pdf_key'] ?? ''));
    $activePdfKey = trim((string)(
        $_SESSION['ai_current_pdf_key']
        ?? ($_SESSION['step1']['ai_pdf_access_key'] ?? '')
    ));

    if (!preg_match('/^[a-f0-9]{64}$/', $savePdfKey) || $savePdfKey !== $activePdfKey) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'aktif_pdf_eslesmedi'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $authorized = false;
    if ($paymentCustomerKey !== '' && function_exists('paytr_pdf_is_authorized')) {
        $authorized = paytr_pdf_is_authorized($paymentCustomerKey, $savePdfKey);
    } else {
        $authorized = !empty($_SESSION['ai_authorized_pdf_keys'][$savePdfKey]);
    }

    if (!$authorized) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'pdf_yetkili_degil'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $incoming = $payload['history'] ?? [];
    if (!is_array($incoming)) $incoming = [];

    $clean = [];
    $resultCount = 0;

    foreach (array_slice($incoming, -80) as $event) {
        if (!is_array($event)) continue;
        $type = (string)($event['type'] ?? '');

        if ($type === 'message') {
            $role = (string)($event['role'] ?? '');
            if (!in_array($role, ['user', 'bot'], true)) continue;

            $text = trim((string)($event['text'] ?? ''));
            if ($text === '') continue;
            $text = function_exists('mb_substr')
                ? mb_substr($text, 0, 30000, 'UTF-8')
                : substr($text, 0, 30000);

            $one = ['type' => 'message', 'role' => $role, 'text' => $text];
            if ($role === 'bot' && !empty($event['whatsapp_support'])) {
                $one['whatsapp_support'] = true;
            }
            $criterion = preg_replace('/[^A-Za-z0-9_]/', '', (string)($event['criterion'] ?? ''));
            if ($criterion !== '') $one['criterion'] = $criterion;
            $clean[] = $one;
            continue;
        }

        if ($type === 'result' && $resultCount < 15 && is_array($event['payload'] ?? null)) {
            $encoded = json_encode($event['payload'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            if (is_string($encoded) && strlen($encoded) <= 900000) {
                $decoded = json_decode($encoded, true);
                if (is_array($decoded)) {
                    $clean[] = ['type' => 'result', 'payload' => $decoded];
                    $resultCount++;
                }
            } else {
                $reply = trim((string)($event['payload']['reply'] ?? 'Sonuç listesi oluşturuldu.'));
                $clean[] = [
                    'type' => 'message',
                    'role' => 'bot',
                    'text' => $reply !== '' ? $reply : 'Sonuç listesi oluşturuldu.',
                ];
            }
        }
    }

    while (count($clean) > 1) {
        $all = json_encode($clean, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if (is_string($all) && strlen($all) <= 3500000) break;
        array_shift($clean);
    }

    $meta = is_array($payload['meta'] ?? null) ? $payload['meta'] : [];
    $_SESSION['ai_ui_chat_history'] = $clean;
    $_SESSION['ai_ui_chat_meta'] = [
        'initial_choice_made' => !empty($meta['initial_choice_made']),
        'active_criterion' => preg_replace('/[^A-Za-z0-9_]/', '', (string)($meta['active_criterion'] ?? '')),
        'updated_at' => date('Y-m-d H:i:s'),
    ];

    if (function_exists('paytr_store_ai_context_for_pdf')) {
        paytr_store_ai_context_for_pdf($savePdfKey);
    }

    echo json_encode(['ok' => true, 'saved' => count($clean)], JSON_UNESCAPED_UNICODE);
    exit;
}

/*
 | Eski tek-PDF kaydını ilk açılışta kütüphaneye taşır.
 | Böylece güncellemeden önce yüklenen aktif belge de listede kaybolmaz.
 */
$existingStep1 = (isset($_SESSION['step1']) && is_array($_SESSION['step1'])) ? $_SESSION['step1'] : [];
$existingPdfKey = trim((string)($existingStep1['ai_pdf_access_key'] ?? $_SESSION['ai_current_pdf_key'] ?? ''));
if ($existingPdfKey !== ''
    && $paymentCustomerKey !== ''
    && function_exists('paytr_pdf_is_authorized')
    && function_exists('paytr_save_pdf_profile')
    && paytr_pdf_is_authorized($paymentCustomerKey, $existingPdfKey)
    && function_exists('paytr_get_pdf_profile')
    && paytr_get_pdf_profile($paymentCustomerKey, $existingPdfKey) === null) {
    paytr_save_pdf_profile($paymentCustomerKey, $existingPdfKey, [
        'step1' => $existingStep1,
        'original_name' => (string)($existingStep1['pdflog_pdf_original'] ?? ''),
        'pdf_path' => (string)($existingStep1['pdflog_pdf_path'] ?? ''),
    ]);
}

/*
 | Belge bağlantısına tıklanınca eski PDF'nin konuşma bağlamını sakla,
 | seçilen PDF'nin step1 verisini ve kendi sohbet bağlamını etkinleştir.
 */
$requestedPdfKey = trim((string)($_GET['pdf'] ?? ''));
if ($requestedPdfKey !== ''
    && preg_match('/^[a-f0-9]{64}$/', $requestedPdfKey)
    && $paymentCustomerKey !== ''
    && function_exists('paytr_get_pdf_profile')) {

    $selectedProfile = paytr_get_pdf_profile($paymentCustomerKey, $requestedPdfKey);
    if (is_array($selectedProfile) && !empty($selectedProfile['step1']) && is_array($selectedProfile['step1'])) {
        /*
         | ia-step1.php hedef anahtarı session'a yazmadan önce gerçek eski PDF
         | anahtarını burada bırakır. Bu sayede Zeynep sohbeti Ali'nin anahtarına
         | kaydedilmez.
         */
        $previousPdfKeyFromContinue = trim((string)(
            $_SESSION['ai_previous_pdf_key_before_continue'] ?? ''
        ));
        unset($_SESSION['ai_previous_pdf_key_before_continue']);

        $oldPdfKey = $previousPdfKeyFromContinue !== ''
            ? $previousPdfKeyFromContinue
            : trim((string)(
                $_SESSION['ai_current_pdf_key']
                ?? ($existingStep1['ai_pdf_access_key'] ?? '')
            ));

        if ($oldPdfKey !== ''
            && $oldPdfKey !== $requestedPdfKey
            && function_exists('paytr_store_ai_context_for_pdf')) {
            paytr_store_ai_context_for_pdf($oldPdfKey);
        }

        if (function_exists('paytr_restore_ai_context_for_pdf')) {
            paytr_restore_ai_context_for_pdf($requestedPdfKey);
        }

        $_SESSION['step1'] = $selectedProfile['step1'];
        $_SESSION['step1']['ai_pdf_access_key'] = $requestedPdfKey;
        $_SESSION['step1']['ai_pdf_customer_key'] = $paymentCustomerKey;
        $_SESSION['ai_current_pdf_key'] = $requestedPdfKey;

        $selectedCandidateFullName = trim((string)(
            $_SESSION['step1']['full_name']
            ?? $_SESSION['step1']['ad_soyad']
            ?? $_SESSION['step1']['adsoyad']
            ?? $_SESSION['step1']['adi_soyadi']
            ?? ''
        ));

        if ($selectedCandidateFullName !== '') {
            $_SESSION['ai_student_name'] = $selectedCandidateFullName;
            $_SESSION['pdflog_full_name'] = $selectedCandidateFullName;
        }

        $candidateGreetingRepaired =
            ai_repair_candidate_greeting_context($_SESSION['step1']);

        if ($candidateGreetingRepaired
            && function_exists('paytr_store_ai_context_for_pdf')) {
            paytr_store_ai_context_for_pdf($requestedPdfKey);
        }

        if (!isset($_SESSION['ai_authorized_pdf_keys']) || !is_array($_SESSION['ai_authorized_pdf_keys'])) {
            $_SESSION['ai_authorized_pdf_keys'] = [];
        }
        $_SESSION['ai_authorized_pdf_keys'][$requestedPdfKey] = true;
        $_SESSION['ai_pdf_switch_notice'] = (string)($selectedProfile['label'] ?? 'Sonuç Belgesi');

        if (function_exists('paytr_touch_pdf_profile')) {
            paytr_touch_pdf_profile($paymentCustomerKey, $requestedPdfKey);
        }

        header('Location: /ia-tercih-robotu/?belge=secildi');
        exit;
    }
}

$step1 = (isset($_SESSION['step1']) && is_array($_SESSION['step1'])) ? $_SESSION['step1'] : [];

/*
 | Önceki hatalı sürümden kalmış "ALİ, ZEYNEP, sonuç belgene göre..."
 | mesajı varsa aktif PDF'nin gerçek aday adıyla düzelt.
 */
$activeGreetingRepaired = ai_repair_candidate_greeting_context($step1);

$name = trim((string)($step1['full_name'] ?? $step1['ad_soyad'] ?? $step1['adsoyad'] ?? $step1['adi_soyadi'] ?? ''));
$firstName = ai_candidate_first_name_from_step1($step1);

if ($activeGreetingRepaired) {
    $repairPdfKey = trim((string)(
        $step1['ai_pdf_access_key']
        ?? $_SESSION['ai_current_pdf_key']
        ?? ''
    ));

    if ($repairPdfKey !== ''
        && function_exists('paytr_store_ai_context_for_pdf')) {
        paytr_store_ai_context_for_pdf($repairPdfKey);
    }
}

$remainingPdfRights = 0;
if (!$ownerUnlimited) {
    $remainingPdfRights = function_exists('paytr_sync_pdf_rights_to_session') && $paymentCustomerKey !== ''
        ? paytr_sync_pdf_rights_to_session($paymentCustomerKey)
        : max(0, (int)($_SESSION['ai_pdf_upload_rights'] ?? 0));
    $_SESSION['ai_pdf_upload_rights'] = $remainingPdfRights;
}

$currentPdfKey = trim((string)($step1['ai_pdf_access_key'] ?? $_SESSION['ai_current_pdf_key'] ?? ''));
if (!isset($_SESSION['ai_authorized_pdf_keys']) || !is_array($_SESSION['ai_authorized_pdf_keys'])) {
    $_SESSION['ai_authorized_pdf_keys'] = [];
}

$currentPdfHasAccess = $ucretsizSinirsizMod;
if (!$currentPdfHasAccess && $currentPdfKey !== '') {
    if (function_exists('paytr_pdf_is_authorized') && $paymentCustomerKey !== '') {
        $currentPdfHasAccess = paytr_pdf_is_authorized($paymentCustomerKey, $currentPdfKey);
    } else {
        $currentPdfHasAccess = !empty($_SESSION['ai_authorized_pdf_keys'][$currentPdfKey]);
    }
}

if ($currentPdfKey !== '') $_SESSION['ai_current_pdf_key'] = $currentPdfKey;
$hasLoadedPdf = $currentPdfKey !== '' || !empty($step1['pdflog_pdf_path']) || !empty($step1['pdflog_id']);

// Açık olan sohbeti son kullanılanlar listesinde en üste taşı.
if ($currentPdfKey !== ''
    && $paymentCustomerKey !== ''
    && function_exists('paytr_touch_pdf_profile')) {
    paytr_touch_pdf_profile($paymentCustomerKey, $currentPdfKey);
}

$pdfProfiles = function_exists('paytr_list_pdf_profiles') && $paymentCustomerKey !== ''
    ? paytr_list_pdf_profiles($paymentCustomerKey)
    : [];

/*
 | Veritabanı temizliği geçici olarak başarısız olsa bile kullanıcıya aynı
 | T.C. için yalnızca tek PDF/sohbet göster.
 */
if (!$ownerUnlimited && $pdfProfiles) {
    $deduplicatedProfiles = [];
    $seenTckn = [];

    foreach ($pdfProfiles as $profile) {
        if (!is_array($profile)) continue;

        $profileKey = trim((string)($profile['pdf_key'] ?? ''));
        $profileTckn = ai_single_tc_profile_tckn($profile);

        if ($profileTckn === '') {
            $deduplicatedProfiles[] = $profile;
            continue;
        }

        $canonicalKey = $aiSingleTcCanonicalMap[$profileTckn]
            ?? $profileKey;

        if ($profileKey !== $canonicalKey) continue;
        if (isset($seenTckn[$profileTckn])) continue;

        $seenTckn[$profileTckn] = true;
        $deduplicatedProfiles[] = $profile;
    }

    $pdfProfiles = array_values($deduplicatedProfiles);
}

// Üst alanda yalnızca son kullanılan 5 sohbet gösterilir.
// Diğer belgeler T.C. kimlik numarası veya ad soyad ile aranabilir.
$recentPdfProfiles = array_slice($pdfProfiles, 0, 5);
$pdfSearchProfiles = [];

foreach ($pdfProfiles as $profile) {
    $profileStep1 = (isset($profile['step1']) && is_array($profile['step1'])) ? $profile['step1'] : [];

    $profileName = trim((string)(
        $profileStep1['full_name']
        ?? $profileStep1['ad_soyad']
        ?? $profileStep1['adsoyad']
        ?? $profileStep1['adi_soyadi']
        ?? ''
    ));

    $profileTckn = preg_replace('/\D+/', '', (string)(
        $profileStep1['tckn']
        ?? $profileStep1['tc']
        ?? $profileStep1['tc_kimlik_no']
        ?? $profileStep1['tcno']
        ?? ''
    ));

    if (strlen($profileTckn) > 11) $profileTckn = substr($profileTckn, 0, 11);

    $profileDate = (string)(
        $profile['last_opened_at']
        ?? $profile['uploaded_at']
        ?? $profile['authorized_at']
        ?? ''
    );

    $pdfSearchProfiles[] = [
        'pdf_key' => (string)($profile['pdf_key'] ?? ''),
        'label' => (string)($profile['label'] ?? 'Sonuç Belgesi'),
        'name' => $profileName,
        'tckn' => $profileTckn,
        'original_name' => (string)($profile['original_name'] ?? ''),
        'date' => $profileDate !== '' ? substr($profileDate, 0, 10) : '',
        'active' => (string)($profile['pdf_key'] ?? '') === $currentPdfKey,
    ];
}

$currentActivationAccount = function_exists('paytr_activation_current_account')
    ? paytr_activation_current_account()
    : null;
$activationLoggedIn = !$ownerUnlimited && is_array($currentActivationAccount);
$activationCodeHint = $activationLoggedIn
    ? (string)($currentActivationAccount['code_hint'] ?? '')
    : '';

$currentPdfProfile = null;
foreach ($pdfProfiles as $oneProfile) {
    if (($oneProfile['pdf_key'] ?? '') === $currentPdfKey) {
        $currentPdfProfile = $oneProfile;
        break;
    }
}
$currentPdfLabel = is_array($currentPdfProfile)
    ? (string)($currentPdfProfile['label'] ?? 'Sonuç Belgesi')
    : ($name !== '' ? $name . ' Sonuç Belgesi' : 'Sonuç Belgesi');

$pdfSwitchNotice = trim((string)($_SESSION['ai_pdf_switch_notice'] ?? ''));
unset($_SESSION['ai_pdf_switch_notice']);

$singleTcContinueNotice = !$ownerUnlimited
    && !empty($_SESSION['ai_single_tc_continue_notice']);
unset($_SESSION['ai_single_tc_continue_notice']);

$ownerResetFlash = trim((string)($_SESSION['ai_owner_reset_flash'] ?? ''));
unset($_SESSION['ai_owner_reset_flash']);

$uiChatHistory = $_SESSION['ai_ui_chat_history'] ?? [];
if (!is_array($uiChatHistory)) $uiChatHistory = [];

$uiChatMeta = $_SESSION['ai_ui_chat_meta'] ?? [];
if (!is_array($uiChatMeta)) $uiChatMeta = [];

$shortServerChatHistory = $_SESSION['ai_chat_history'] ?? [];
if (!is_array($shortServerChatHistory)) $shortServerChatHistory = [];

$hasRestoredServerContext = !empty($uiChatHistory)
    || !empty($shortServerChatHistory)
    || !empty($_SESSION['ai_filters'])
    || !empty($_SESSION['ai_last_program_query_filters']);

$accessStatusText = $ownerUnlimited
    ? 'Yönetici test erişimi · Sınırsız PDF'
    : ($ucretsizSinirsizMod
    ? 'Ücretsiz test modu · Sınırsız kullanım'
    : ($currentPdfHasAccess
        ? $currentPdfLabel . ' aktif · Kalan yeni PDF hakkı: ' . $remainingPdfRights
        : ($remainingPdfRights > 0
            ? 'PDF yükleme hakkınız: ' . $remainingPdfRights . ' · Sonuç belgesi bekleniyor'
            : 'Sonuç belgesi paketi gerekli')));

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Tercih Robotu Yapay Zeka</title>

  <link rel="preload" href="/css/logo.png" as="image">
  <link rel="stylesheet" href="/css/styles.css?v=12">
  <link rel="icon" href="https://www.tercihrobotu.com.tr/duyurular/wp-content/uploads/2026/01/ico.png" sizes="32x32">
  <link rel="icon" href="https://www.tercihrobotu.com.tr/duyurular/wp-content/uploads/2026/01/ico.png" sizes="192x192">
  <link rel="apple-touch-icon" href="https://www.tercihrobotu.com.tr/duyurular/wp-content/uploads/2026/01/ico.png">
  <meta name="msapplication-TileImage" content="https://www.tercihrobotu.com.tr/duyurular/wp-content/uploads/2026/01/ico.png">
  <script defer src="/css/main.js?v=8"></script>
  <!-- tercih-chat-step4-final-20260607-1225 | DUZELTILMIS_V8 -->
  <style>
    :root{
      --bg1:#eef3ff;
      --bg2:#f8fbff;
      --card:#ffffff;
      --text:#0f172a;
      --muted:#64748b;
      --line:#e2e8f0;
      --brand:#7c3aed;
      --brand2:#06b6d4;
      --brand3:#f97316;
      --soft:#f8fafc;
      --bot:#ffffff;
      --user:#6d28d9;
      --shadow:0 22px 70px rgba(15,23,42,.12);
    }
    *{box-sizing:border-box}
    html,body{height:100%}
    body{
      margin:0;
      font-family:Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
      background:
        radial-gradient(900px 420px at 12% -120px, rgba(124,58,237,.22), transparent 65%),
        radial-gradient(850px 420px at 88% -120px, rgba(6,182,212,.22), transparent 65%),
        linear-gradient(180deg,var(--bg1),var(--bg2));
      color:var(--text);
      overflow:hidden;
    }
    .page{
      height:100vh;
      height:100dvh;
      display:grid;
      grid-template-columns:320px minmax(0,1fr);
      gap:18px;
      padding:18px;
      max-width:1500px;
      margin:0 auto;
    }
    .side{
      min-height:0;
      border-radius:28px;
      background:linear-gradient(180deg, rgba(124,58,237,.96), rgba(6,182,212,.88));
      color:white;
      padding:24px;
      box-shadow:var(--shadow);
      display:flex;
      flex-direction:column;
      justify-content:space-between;
      overflow:hidden;
      position:relative;
    }
    .side:before{
      content:"";
      position:absolute;
      width:220px;height:220px;border-radius:999px;
      right:-80px;top:-80px;
      background:rgba(255,255,255,.16);
    }
    .side:after{
      content:"";
      position:absolute;
      width:180px;height:180px;border-radius:999px;
      left:-70px;bottom:80px;
      background:rgba(255,255,255,.10);
    }
    .side-inner{position:relative;z-index:1}
    .logo{
      width:58px;height:58px;border-radius:20px;
      display:flex;align-items:center;justify-content:center;
      background:rgba(255,255,255,.18);
      border:1px solid rgba(255,255,255,.28);
      font-size:30px;
      margin-bottom:18px;
    }
    h1{margin:0;font-size:30px;line-height:1.05;letter-spacing:-.8px}
    .lead{font-size:16px;line-height:1.55;opacity:.95;margin:14px 0 0}
    .side-card{
      margin-top:22px;
      background:rgba(255,255,255,.14);
      border:1px solid rgba(255,255,255,.22);
      border-radius:22px;
      padding:16px;
      backdrop-filter:blur(10px);
    }
    .side-card b{display:block;margin-bottom:7px;font-size:15px}
    .side-card p{margin:0;font-size:14px;line-height:1.45;opacity:.92}
    .back{
      position:relative;z-index:1;
      display:inline-flex;align-items:center;justify-content:center;
      color:white;text-decoration:none;
      border:1px solid rgba(255,255,255,.42);
      background:rgba(255,255,255,.10);
      padding:12px 14px;
      border-radius:16px;
      font-weight:900;
      font-size:14px;
    }
    .chat-shell{
      min-height:0;
      background:rgba(255,255,255,.78);
      border:1px solid rgba(226,232,240,.95);
      border-radius:28px;
      box-shadow:var(--shadow);
      overflow:hidden;
      backdrop-filter:blur(16px);
      display:flex;
      flex-direction:column;
    }
    .chat-head{
      padding:18px 22px;
      border-bottom:1px solid var(--line);
      background:rgba(255,255,255,.78);
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:14px;
    }
    .avatar-line{display:flex;align-items:center;gap:13px;min-width:0}
    .avatar{
      display:block;
      width:50px;height:50px;
      object-fit:contain;
      flex:0 0 50px;
      border:0;
      border-radius:0;
      background:transparent;
      box-shadow:none;
    }
    .chat-title{min-width:0}
    .chat-title h2{margin:0;font-size:22px;letter-spacing:-.35px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .chat-title p{margin:4px 0 0;color:var(--muted);font-size:14px}
    .status{
      display:flex;align-items:center;gap:8px;
      color:#166534;background:#dcfce7;border:1px solid #bbf7d0;
      border-radius:999px;padding:8px 12px;font-weight:900;font-size:13px;
      white-space:nowrap;
    }
    .dot-live{width:8px;height:8px;background:#22c55e;border-radius:999px;box-shadow:0 0 0 4px rgba(34,197,94,.14)}
    #messages{
      flex:1;
      min-height:0;
      overflow:auto;
      padding:24px;
      display:flex;
      flex-direction:column;
      gap:16px;
      scroll-behavior:smooth;
    }
    /* İlk açılışta karşılama mesajı ile hazır seçimler arasındaki büyük boşluğu kaldırır. */
    #messages.initial-question{
      flex:0 0 auto;
      overflow:visible;
      padding-bottom:8px;
    }
    .msg-row{display:flex;gap:10px;align-items:flex-end}
    .msg-row.user-row{justify-content:flex-end}
    .mini-avatar{
      width:32px;height:32px;
      display:flex;align-items:center;justify-content:center;
      flex:0 0 32px;
      background:transparent;
      border:0;
      border-radius:0;
    }
    .mini-avatar img{
      display:block;
      width:32px;height:32px;
      object-fit:contain;
    }
    .msg{
      max-width:74%;
      border-radius:22px;
      padding:15px 17px;
      line-height:1.58;
      font-size:17px;
      white-space:pre-wrap;
      word-break:break-word;
    }
    .bot{
      background:var(--bot);
      border:1px solid var(--line);
      box-shadow:0 10px 28px rgba(15,23,42,.06);
      border-bottom-left-radius:8px;
    }
    .user{
      background:linear-gradient(135deg,var(--user),#8b5cf6);
      color:white;
      border-bottom-right-radius:8px;
      box-shadow:0 12px 28px rgba(109,40,217,.18);
    }
    .msg b,.msg strong{font-weight:950}
    .whatsapp-support{
      margin-top:14px;
      padding-top:12px;
      border-top:1px solid #dcfce7;
      display:flex;
      flex-wrap:wrap;
      align-items:center;
      gap:8px;
      color:#475569;
      font-size:14px;
      line-height:1.45;
      white-space:normal;
    }
    .whatsapp-support-link{
      display:inline-flex;
      align-items:center;
      gap:7px;
      padding:8px 11px;
      border:1px solid #86efac;
      border-radius:999px;
      background:#f0fdf4;
      color:#15803d;
      font-weight:950;
      text-decoration:none;
      transition:.16s ease;
      box-shadow:0 5px 14px rgba(22,163,74,.08);
    }
    .whatsapp-support-link:hover{
      transform:translateY(-1px);
      border-color:#22c55e;
      background:#dcfce7;
      color:#166534;
      box-shadow:0 8px 18px rgba(22,163,74,.14);
    }
    .whatsapp-support-link svg{
      width:20px;
      height:20px;
      flex:0 0 20px;
      fill:currentColor;
    }
    .msg img{
      display:block;
      max-width:320px;
      width:100%;
      border-radius:18px;
      margin:10px 0 2px;
      border:1px solid var(--line);
      box-shadow:0 10px 24px rgba(15,23,42,.09);
    }
    .chips{
      display:flex;
      gap:10px;
      flex-wrap:wrap;
      padding:0 24px 16px;
      background:rgba(255,255,255,.60);
    }
    .chip{
      border:1px solid #ddd6fe;
      background:#fff;
      border-radius:999px;
      padding:10px 13px;
      font-size:14px;
      font-weight:900;
      cursor:pointer;
      color:#334155;
      transition:.18s ease;
      box-shadow:0 6px 18px rgba(15,23,42,.04);
    }
    .chip:hover{transform:translateY(-1px);border-color:#a78bfa;color:#5b21b6;box-shadow:0 10px 24px rgba(124,58,237,.10)}
    .quick-replies{
      display:flex;
      flex-wrap:wrap;
      gap:10px;
      padding:0 24px 12px;
      background:rgba(255,255,255,.60);
    }
    .quick-btn{
      border:1px solid #c4b5fd;
      background:linear-gradient(180deg,#fff,#faf5ff);
      color:#4c1d95;
      border-radius:999px;
      padding:11px 15px;
      font-size:15px;
      font-weight:950;
      cursor:pointer;
      box-shadow:0 8px 22px rgba(124,58,237,.08);
      transition:.16s ease;
    }
    .quick-btn:hover{transform:translateY(-1px);border-color:#8b5cf6;box-shadow:0 12px 28px rgba(124,58,237,.14)}
    .quick-btn:disabled{opacity:.55;cursor:not-allowed;transform:none}

    .result-card{
      max-width:96%;
      width:min(920px,96%);
      padding:0;
      overflow:hidden;
      background:#fff;
      border:1px solid #dbe4ff;
    }
    .result-hero{
      padding:18px 18px 14px;
      background:linear-gradient(135deg, rgba(124,58,237,.10), rgba(6,182,212,.10));
      border-bottom:1px solid var(--line);
    }
    .result-kicker{font-size:13px;font-weight:950;color:#6d28d9;letter-spacing:.2px;margin-bottom:6px}
    .result-hero h3{margin:0;font-size:22px;letter-spacing:-.4px}
    .result-hero p{margin:7px 0 0;color:var(--muted);font-size:14px;line-height:1.45}
    .result-stats{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}
    .result-stat{background:#fff;border:1px solid #e9d5ff;border-radius:999px;padding:8px 11px;font-size:13px;font-weight:950;color:#4c1d95}
    .result-tools{padding:12px 14px;border-bottom:1px solid var(--line);background:#fff;display:flex;gap:10px;align-items:center}
    .result-search{width:100%;border:1px solid var(--line);background:#f8fafc;border-radius:14px;padding:11px 13px;font-size:15px;outline:none}
    .result-search:focus{border-color:#a78bfa;background:#fff;box-shadow:0 0 0 4px rgba(124,58,237,.10)}
    .result-list{padding:8px 10px 4px;background:#fbfdff}
    .result-row{
      display:grid;
      grid-template-columns:minmax(0,1fr) 118px 78px;
      gap:10px;
      align-items:center;
      padding:12px 10px;
      border-bottom:1px solid #eef2f7;
      animation:rowIn .22s ease both;
    }
    @keyframes rowIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
    .result-row:last-child{border-bottom:0}
    .result-name{font-weight:900;color:#0f172a;line-height:1.3}
    .result-edu,.result-count{justify-self:start;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:950;white-space:nowrap}
    .result-edu{background:#eef2ff;color:#4338ca;border:1px solid #c7d2fe}
    .result-count{background:#ecfeff;color:#0e7490;border:1px solid #a5f3fc}
    .result-more{padding:12px 14px 16px;text-align:center;color:var(--muted);font-size:13px;font-weight:800;background:#fff}
    .result-empty{padding:18px;color:var(--muted);font-weight:850;text-align:center}

    .result-sub{grid-column:1/-1;color:#64748b;font-size:13px;font-weight:750;margin-top:3px;line-height:1.35}
    .result-row.program-row{grid-template-columns:1fr auto auto;align-items:center}
    .result-program-title{font-weight:950;color:#0f172a;line-height:1.32}
    .result-warning{margin-top:7px;padding:8px 10px;border-radius:12px;background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;font-size:12px;font-weight:850;line-height:1.35}
    .result-note{margin-top:10px;padding:9px 11px;border-radius:14px;background:#ecfeff;border:1px solid #a5f3fc;color:#155e75;font-size:13px;font-weight:900;line-height:1.35}
    .result-program-meta{grid-column:1/-1;color:#64748b;font-size:13px;font-weight:800;margin-top:4px;line-height:1.45}
    .result-badge{justify-self:start;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:950;white-space:nowrap;background:#fef3c7;color:#92400e;border:1px solid #fde68a}
    .quick-btn.selected{background:linear-gradient(135deg,#7c3aed,#06b6d4);color:#fff;border-color:transparent;box-shadow:0 12px 30px rgba(124,58,237,.24)}
    .quick-done{background:linear-gradient(135deg,#16a34a,#06b6d4);color:#fff;border-color:transparent}
    .quick-done:disabled{opacity:.45;cursor:not-allowed;transform:none}

    .typing-wrap{
      min-height:34px;
      padding:0 24px 10px;
      display:flex;
      align-items:center;
    }
    .typing{
      display:none;
      align-items:center;
      gap:9px;
      color:var(--muted);
      font-size:15px;
      font-weight:800;
      background:#fff;
      border:1px solid var(--line);
      border-radius:999px;
      padding:8px 12px;
      box-shadow:0 8px 20px rgba(15,23,42,.05);
    }
    .typing.show{display:inline-flex}
    .typing-dots{display:inline-flex;gap:4px;align-items:center}
    .typing-dots span{
      width:6px;height:6px;border-radius:999px;background:#94a3b8;
      animation:bounce 1.1s infinite ease-in-out;
    }
    .typing-dots span:nth-child(2){animation-delay:.15s}
    .typing-dots span:nth-child(3){animation-delay:.30s}
    @keyframes bounce{0%,80%,100%{transform:translateY(0);opacity:.45}40%{transform:translateY(-4px);opacity:1}}
    .composer{
      border-top:1px solid var(--line);
      background:#fff;
      padding:16px;
      display:flex;
      gap:12px;
      align-items:flex-end;
    }
    textarea{
      flex:1;
      resize:none;
      min-height:58px;
      max-height:170px;
      border:1px solid var(--line);
      border-radius:20px;
      padding:16px 17px;
      font-size:17px;
      line-height:1.45;
      outline:none;
      font-family:inherit;
      background:#f8fafc;
      color:var(--text);
    }
    textarea:focus{
      background:#fff;
      border-color:#a78bfa;
      box-shadow:0 0 0 4px rgba(124,58,237,.12);
    }
    .send,.reset,.mic{
      border:0;
      border-radius:18px;
      color:white;
      font-weight:950;
      min-height:58px;
      cursor:pointer;
      font-size:16px;
      transition:.18s ease;
      white-space:nowrap;
    }
    .send,.reset{padding:17px 20px}
    .send{background:linear-gradient(135deg,var(--brand),var(--brand2));box-shadow:0 12px 26px rgba(124,58,237,.20)}
    .reset{background:#64748b;padding-left:16px;padding-right:16px}
    .mic{
      width:58px;
      flex:0 0 58px;
      padding:0;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      background:#0f172a;
      box-shadow:0 12px 26px rgba(15,23,42,.16);
      font-size:23px;
    }
    .mic.listening{
      background:#dc2626;
      animation:micPulse 1.15s infinite ease-in-out;
    }
    @keyframes micPulse{
      0%,100%{box-shadow:0 0 0 0 rgba(220,38,38,.30)}
      50%{box-shadow:0 0 0 9px rgba(220,38,38,0)}
    }
    .send:hover,.reset:hover,.mic:hover{transform:translateY(-1px);filter:brightness(1.03)}
    .send:disabled,.reset:disabled,.mic:disabled{opacity:.55;cursor:not-allowed;transform:none;filter:none;box-shadow:none}
    .composer.is-locked{opacity:.48;filter:grayscale(.25);cursor:not-allowed}
    .composer.is-locked textarea,
    textarea:disabled{background:#e9edf3;color:#94a3b8;cursor:not-allowed;box-shadow:none;border-color:#d7dee8}
    .composer.is-locked .send,
    .composer.is-locked .mic{opacity:.45;cursor:not-allowed;box-shadow:none}
    .hint{
      padding:0 18px 14px;
      color:var(--muted);
      font-size:13px;
      background:#fff;
      text-align:center;
    }
    @media(max-width:980px){
      body{overflow:auto}
      .page{height:100dvh;grid-template-columns:1fr;padding:10px;gap:10px}
      .side{display:none}
      .chat-shell{border-radius:22px}
      .chat-head{padding:13px 14px}.chat-title h2{font-size:18px}.status{display:none}
      #messages{padding:15px;gap:13px}.msg{max-width:90%;font-size:15px;padding:12px 14px}
      .chips{padding:0 14px 12px}.chip{font-size:13px;padding:8px 10px}
      .composer{padding:10px;gap:8px;flex-wrap:wrap}
      .composer textarea{flex:0 0 100%;width:100%;font-size:15px;min-height:50px;border-radius:16px;padding:13px}
      .composer .mic{order:2;width:50px;flex:0 0 50px;min-height:50px;border-radius:16px;font-size:21px}
      .composer .send{order:3;flex:1 1 0;min-height:50px;padding:13px 15px;font-size:14px;border-radius:16px}
      .composer .reset{order:4;display:inline-flex;align-items:center;justify-content:center;flex:1 1 0;min-height:50px;padding:13px 12px;font-size:13px;border-radius:16px}
      .quick-replies{padding:0 14px 10px;gap:8px}.quick-btn{font-size:13px;padding:9px 11px}
  
    .result-card{
      max-width:96%;
      width:min(920px,96%);
      padding:0;
      overflow:hidden;
      background:#fff;
      border:1px solid #dbe4ff;
    }
    .result-hero{
      padding:18px 18px 14px;
      background:linear-gradient(135deg, rgba(124,58,237,.10), rgba(6,182,212,.10));
      border-bottom:1px solid var(--line);
    }
    .result-kicker{font-size:13px;font-weight:950;color:#6d28d9;letter-spacing:.2px;margin-bottom:6px}
    .result-hero h3{margin:0;font-size:22px;letter-spacing:-.4px}
    .result-hero p{margin:7px 0 0;color:var(--muted);font-size:14px;line-height:1.45}
    .result-stats{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}
    .result-stat{background:#fff;border:1px solid #e9d5ff;border-radius:999px;padding:8px 11px;font-size:13px;font-weight:950;color:#4c1d95}
    .result-tools{padding:12px 14px;border-bottom:1px solid var(--line);background:#fff;display:flex;gap:10px;align-items:center}
    .result-search{width:100%;border:1px solid var(--line);background:#f8fafc;border-radius:14px;padding:11px 13px;font-size:15px;outline:none}
    .result-search:focus{border-color:#a78bfa;background:#fff;box-shadow:0 0 0 4px rgba(124,58,237,.10)}
    .result-list{padding:8px 10px 4px;background:#fbfdff}
    .result-row{
      display:grid;
      grid-template-columns:minmax(0,1fr) 118px 78px;
      gap:10px;
      align-items:center;
      padding:12px 10px;
      border-bottom:1px solid #eef2f7;
      animation:rowIn .22s ease both;
    }
    @keyframes rowIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
    .result-row:last-child{border-bottom:0}
    .result-name{font-weight:900;color:#0f172a;line-height:1.3}
    .result-edu,.result-count{justify-self:start;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:950;white-space:nowrap}
    .result-edu{background:#eef2ff;color:#4338ca;border:1px solid #c7d2fe}
    .result-count{background:#ecfeff;color:#0e7490;border:1px solid #a5f3fc}
    .result-more{padding:12px 14px 16px;text-align:center;color:var(--muted);font-size:13px;font-weight:800;background:#fff}
    .result-empty{padding:18px;color:var(--muted);font-weight:850;text-align:center}

    .result-sub{grid-column:1/-1;color:#64748b;font-size:13px;font-weight:750;margin-top:3px;line-height:1.35}
    .result-row.program-row{grid-template-columns:1fr auto auto;align-items:center}
    .result-program-title{font-weight:950;color:#0f172a;line-height:1.32}
    .result-warning{margin-top:7px;padding:8px 10px;border-radius:12px;background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;font-size:12px;font-weight:850;line-height:1.35}
    .result-note{margin-top:10px;padding:9px 11px;border-radius:14px;background:#ecfeff;border:1px solid #a5f3fc;color:#155e75;font-size:13px;font-weight:900;line-height:1.35}
    .result-program-meta{grid-column:1/-1;color:#64748b;font-size:13px;font-weight:800;margin-top:4px;line-height:1.45}
    .result-badge{justify-self:start;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:950;white-space:nowrap;background:#fef3c7;color:#92400e;border:1px solid #fde68a}
    .quick-btn.selected{background:linear-gradient(135deg,#7c3aed,#06b6d4);color:#fff;border-color:transparent;box-shadow:0 12px 30px rgba(124,58,237,.24)}
    .quick-done{background:linear-gradient(135deg,#16a34a,#06b6d4);color:#fff;border-color:transparent}
    .quick-done:disabled{opacity:.45;cursor:not-allowed;transform:none}

    .typing-wrap{padding:0 14px 8px}.typing{font-size:13px}
    }
  </style>
<style>

  /* Index sayfasıyla aynı üst/alt kurumsal görünüm. */
  .site-chrome,
  .site-footer-frame{
    --tr-brand:#0A2540;
    --tr-brand2:#123B6B;
    --tr-ink:#0b1220;
    --tr-muted:#475569;
    --tr-section:#F3F4F6;
    --tr-line:rgba(10,37,64,.12);
    --tr-shadow2:0 8px 22px rgba(15,23,42,.08);
    --tr-container:1180px;
    color:var(--tr-ink);
    font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Arial,"Noto Sans","Helvetica Neue",sans-serif;
  }
  .site-chrome *, .site-footer-frame *{box-sizing:border-box}
  .site-chrome a, .site-footer-frame a{color:inherit;text-decoration:none}
  .site-chrome img{max-width:100%;height:auto}
  .site-chrome .container, .site-footer-frame .container{width:min(var(--tr-container),calc(100% - 32px));margin:0 auto}
  .site-chrome .topbar{position:relative;z-index:50;backdrop-filter:blur(12px);background:rgba(255,255,255,.92);border-bottom:1px solid var(--tr-line)}
  .site-chrome .topbar-inner{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 0}
  .site-chrome .brand{display:flex;align-items:center;gap:12px;min-width:220px}
  .site-chrome .brand-logo{display:block;width:250px;height:100px;object-fit:contain;filter:drop-shadow(0 10px 18px rgba(11,42,91,.18))}
  .site-chrome .social{margin-left:auto;display:flex;align-items:center;gap:10px}
  .site-chrome .social a{width:38px;height:38px;border-radius:999px;display:grid;place-items:center;border:1px solid var(--tr-line);background:rgba(255,255,255,.75);box-shadow:0 8px 18px rgba(15,23,42,.06);transition:transform .18s ease,box-shadow .18s ease,border-color .18s ease}
  .site-chrome .social a:hover{transform:translateY(-2px);border-color:rgba(11,42,91,.25);box-shadow:0 12px 28px rgba(15,23,42,.10)}
  .site-chrome .social svg{width:18px;height:18px;fill:var(--tr-ink);opacity:.9}
  .site-chrome .nav{position:relative;z-index:40;background:rgba(255,255,255,.96);backdrop-filter:blur(10px);border-bottom:1px solid var(--tr-line)}
  .site-chrome .nav-inner{display:flex;align-items:center;justify-content:flex-start;padding:10px 0}
  .site-chrome .hamburger{display:none;border:1px solid var(--tr-line);background:rgba(255,255,255,.9);border-radius:12px;padding:10px 12px;font-weight:700;color:var(--tr-ink);cursor:pointer}
  .site-chrome .menu{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
  .site-chrome .menu a{padding:10px 12px;border-radius:999px;color:var(--tr-muted);border:1px solid transparent;transition:all .18s ease;font-weight:600}
  .site-chrome .menu a:hover{color:var(--tr-ink);background:rgba(11,42,91,.06);border-color:rgba(11,42,91,.18)}
  .site-chrome .mobile-cta{display:none}
  .site-chrome .mobile-cta-inner{display:grid;grid-template-columns:1fr;gap:10px}
  .site-chrome .btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;padding:12px 16px;border-radius:14px;border:1px solid transparent;font-weight:900;letter-spacing:.2px;cursor:pointer;transition:transform .18s ease,box-shadow .18s ease;user-select:none}
  .site-chrome .btn:hover{transform:translateY(-2px)}
  .site-chrome .btn-orange{display:flex!important;flex-direction:column!important;justify-content:center!important;align-items:center!important;text-align:center!important;line-height:1.15!important;gap:4px;background:linear-gradient(135deg,#d97706,#b45309);color:#fff;border:1px solid rgba(255,255,255,.14);box-shadow:0 16px 34px rgba(217,119,6,.22)}
  .site-chrome .btn-sub{font-size:12px;opacity:.92}
  .site-chrome .mobile-whatsapp{display:flex;justify-content:center;margin:10px 0 6px}
  .site-chrome .mobile-whatsapp .whatsapp-card{display:block;width:100%;max-width:560px}
  .site-chrome .mobile-whatsapp img{display:block;width:100%;border-radius:16px;border:1px solid var(--tr-line);box-shadow:var(--tr-shadow2)}
  footer.site-footer-frame{margin-top:26px;padding:22px 0 26px;background:var(--tr-section);border-top:1px solid var(--tr-line)}
  .site-footer-frame .footer-links{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:center;justify-content:center;padding-bottom:14px;border-bottom:1px solid var(--tr-line)}
  .site-footer-frame .footer-links a{color:rgba(10,37,64,.86);font-weight:800;font-size:13px;padding:8px 10px;border-radius:12px;border:1px solid transparent}
  .site-footer-frame .footer-links a:hover{background:rgba(255,255,255,.80);border-color:var(--tr-line)}
  .site-footer-frame .footer-meta{padding-top:14px;text-align:center}
  .site-footer-frame .footer-brand{font-weight:900;color:rgba(10,37,64,.88);margin-bottom:6px}
  .site-footer-frame .copyright{color:rgba(11,18,32,.60);font-weight:800;font-size:12px}
  .to-top{position:fixed;right:16px;bottom:16px;z-index:99990;width:48px;height:48px;border-radius:999px;border:1px solid rgba(11,42,91,.22);background:rgba(255,255,255,.92);box-shadow:0 16px 34px rgba(15,23,42,.14);display:none;cursor:pointer;font-size:18px;color:#0A2540}
  .to-top.show{display:grid;place-items:center}
  .floating-whatsapp{position:fixed;right:18px;bottom:92px;z-index:99999;width:64px;height:64px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:#25D366;box-shadow:0 10px 25px rgba(0,0,0,.25);transition:transform .2s ease,box-shadow .2s ease;text-decoration:none}
  .floating-whatsapp:hover{transform:translateY(-2px) scale(1.04);box-shadow:0 14px 30px rgba(0,0,0,.30)}
  .floating-whatsapp svg{width:34px;height:34px;fill:#fff;display:block}
  @media(max-width:820px){
    .site-chrome .topbar-inner{flex-wrap:nowrap!important;gap:10px}
    .site-chrome .brand{min-width:0;flex:0 1 auto}
    .site-chrome .brand-logo{width:170px;height:auto;max-height:72px}
    .site-chrome .social{flex:0 0 auto;gap:6px}
    .site-chrome .social a{width:34px;height:34px}
    .site-chrome .social svg{width:16px;height:16px}
    .site-chrome .hamburger{display:inline-flex}
    .site-chrome .menu{display:none;width:100%;padding:10px 0 4px}
    .site-chrome .menu.open{display:flex}
    .site-chrome .nav-inner{flex-wrap:wrap}
    .site-chrome .mobile-cta{display:block;padding:12px 0 0;background:#fff}
  }
  @media(max-width:480px){
    .site-chrome .container,.site-footer-frame .container{width:min(var(--tr-container),calc(100% - 20px))}
    .site-chrome .brand-logo{width:142px}
    .site-chrome .social{gap:4px}
    .site-chrome .social a{width:30px;height:30px}
    .site-chrome .social svg{width:14px;height:14px}
    .floating-whatsapp{width:58px;height:58px;right:14px;bottom:84px}
    .floating-whatsapp svg{width:30px;height:30px}
  }

  body.tr-ai-page{overflow:auto;min-height:100%;background:#fff}
  .tr-ai-page>.page{height:calc(100dvh - 180px);min-height:700px;margin-top:0}
  .side-brand-logo{display:block;width:100%;max-width:210px;height:auto;max-height:92px;object-fit:contain;margin:0 0 18px;padding:10px 14px;border-radius:20px;background:rgba(255,255,255,.94);border:1px solid rgba(255,255,255,.55);box-shadow:0 14px 30px rgba(15,23,42,.14)}
  .side-card.side-card-how p+p{margin-top:10px}
  .side-card.side-card-how strong{font-weight:950}
  @media(max-width:980px){.tr-ai-page>.page{height:calc(100dvh - 125px);min-height:650px}}

  /* 2026-07-11: index ile birebir üst reklam/menü birleşimi düzeltmesi */
  .site-chrome{
    display:block!important;
    width:100%!important;
    margin:0!important;
    padding:0!important;
    background:#fff!important;
  }
  .site-chrome .topbar{
    margin:0!important;
    padding:0!important;
    border:0!important;
    box-shadow:none!important;
    background:#fff!important;
  }
  .site-chrome .topbar-inner{
    display:grid!important;
    grid-template-columns:250px minmax(320px, 1fr) auto!important;
    align-items:center!important;
    gap:18px!important;
    min-height:110px!important;
    padding:8px 0!important;
  }
  .site-chrome .brand{
    min-width:0!important;
    margin:0!important;
    padding:0!important;
  }
  .site-chrome .brand-logo{
    width:250px!important;
    height:100px!important;
    max-width:100%!important;
    object-fit:contain!important;
  }
  .site-chrome .topbar-ad{
    display:flex!important;
    align-items:center!important;
    justify-content:center!important;
    min-width:0!important;
    margin:0!important;
    padding:0!important;
  }
  .site-chrome .topbar-ad-link{
    display:block!important;
    width:100%!important;
    max-width:728px!important;
    line-height:0!important;
  }
  .site-chrome .topbar-ad-img{
    display:block!important;
    width:100%!important;
    height:auto!important;
    max-height:90px!important;
    object-fit:contain!important;
    margin:0!important;
    padding:0!important;
  }
  .site-chrome .mobile-top-ad{display:none!important}
  .site-chrome .nav{
    display:block!important;
    margin:0!important;
    padding:0!important;
    border:0!important;
    box-shadow:none!important;
    background:#fff!important;
  }
  .site-chrome .nav-inner{
    min-height:50px!important;
    margin:0!important;
    padding:0!important;
  }
  .site-chrome .menu{
    margin:0!important;
    padding:0!important;
  }
  .site-chrome .menu a{
    margin:0!important;
  }
  footer.site-footer-frame{
    display:block!important;
    visibility:visible!important;
    opacity:1!important;
    clear:both!important;
    position:relative!important;
    z-index:20!important;
    margin-top:0!important;
    background:#f3f4f6!important;
    color:#0a2540!important;
  }
  .site-footer-frame .footer-meta,
  .site-footer-frame .footer-brand,
  .site-footer-frame .copyright{
    display:block!important;
    visibility:visible!important;
    opacity:1!important;
  }
  .site-footer-frame .footer-brand{
    color:#0a2540!important;
    font-weight:900!important;
  }
  .site-footer-frame .copyright{color:#475569!important}

  /* Menüden sonra içerik doğrudan başlasın. */
  .tr-ai-page>.page{
    margin-top:0!important;
    padding-top:0!important;
  }
  .tr-step-page>.wrap{
    margin-top:0!important;
    padding-top:0!important;
  }
  .tr-step-page>.wrap>.topbar,
  .tr-step-page>.logo-center{
    display:none!important;
    height:0!important;
    min-height:0!important;
    margin:0!important;
    padding:0!important;
    border:0!important;
  }
  /* Sabit Devam Et çubuğu footer marka yazısını kapatmasın. */
  .tr-step-page footer.site-footer-frame{padding-bottom:120px!important}

  @media(max-width:820px){
    .site-chrome .topbar-inner{
      display:flex!important;
      min-height:0!important;
      padding:6px 0!important;
      gap:8px!important;
    }
    .site-chrome .brand-logo{
      width:170px!important;
      height:auto!important;
      max-height:72px!important;
    }
    .site-chrome .topbar-ad{display:none!important}
    .site-chrome .mobile-top-ad{
      display:block!important;
      width:100%!important;
      margin:0!important;
      padding:0!important;
      background:#fff!important;
      border:0!important;
    }
    .site-chrome .mobile-top-ad-inner{
      display:flex!important;
      justify-content:center!important;
      align-items:center!important;
      margin:0!important;
      padding:0!important;
      line-height:0!important;
    }
    .site-chrome .mobile-top-ad-link{
      display:block!important;
      width:100%!important;
      max-width:728px!important;
      line-height:0!important;
    }
    .site-chrome .mobile-top-ad-img{
      display:block!important;
      width:100%!important;
      height:auto!important;
      margin:0!important;
      padding:0!important;
      object-fit:contain!important;
    }
    .site-chrome .nav-inner{min-height:46px!important}
    .site-chrome .mobile-cta{padding-top:0!important;margin-top:0!important;border:0!important}
    .tr-ai-page>.page{padding-top:0!important}
    .tr-step-page footer.site-footer-frame{padding-bottom:140px!important}
  }

</style>

<style id="tercih-v4-layout-fix">
/* Sohbet uzadığında sol panelin aşağı doğru büyümesini engeller. */
body.tr-ai-page{
  overflow-x:hidden!important;
}
.tr-ai-page .site-chrome{
  position:relative!important;
  z-index:auto!important;
  display:block!important;
  width:100%!important;
}
.tr-ai-page .site-chrome .topbar,
.tr-ai-page .site-chrome .nav,
.tr-ai-page .site-chrome .nav-inner{
  position:static!important;
  inset:auto!important;
  transform:none!important;
}
.tr-ai-page .site-chrome .nav{
  z-index:auto!important;
}

/* Masaüstü: sohbet sabit yükseklikte kalır; sol panel kendi içeriği kadar olur ve asla sohbetle birlikte uzamaz. */
.tr-ai-page > .page{
  position:relative!important;
  z-index:1!important;
  margin-top:16px!important;
  padding-top:0!important;
  height:auto!important;
  min-height:830px!important;
  max-height:none!important;
  align-items:start!important;
}
.tr-ai-page > .page > .side{
  height:auto!important;
  min-height:0!important;
  max-height:none!important;
  overflow:visible!important;
  justify-content:flex-start!important;
  gap:0!important;
  align-self:start!important;
}
.tr-ai-page > .page > .side .side-inner{
  flex:0 0 auto!important;
  min-height:0!important;
  overflow:visible!important;
  padding-right:0!important;
}
.tr-ai-page > .page > .side .back{
  position:relative!important;
  display:flex!important;
  width:100%!important;
  margin-top:32px!important;
  margin-bottom:18px!important;
  flex:0 0 auto!important;
  clear:both!important;
}
.tr-ai-page > .page > .chat-shell{
  height:830px!important;
  min-height:830px!important;
  max-height:830px!important;
  align-self:start!important;
}
.tr-ai-page > .page > .chat-shell #messages{
  min-height:0!important;
  overflow-y:auto!important;
  overflow-x:hidden!important;
}

/* Mobil: sohbet üstte, mavi bilgilendirme alanı sohbetin altında görünür. */
@media (max-width:980px){
  .tr-ai-page > .page{
    display:grid!important;
    grid-template-columns:1fr!important;
    gap:12px!important;
    height:auto!important;
    min-height:0!important;
    max-height:none!important;
    margin-top:10px!important;
    padding-bottom:10px!important;
  }
  .tr-ai-page > .page > .chat-shell{
    display:flex!important;
    order:1!important;
    width:100%!important;
    height:calc(100dvh - 150px)!important;
    min-height:650px!important;
    max-height:none!important;
  }
  .tr-ai-page > .page > .side{
    display:flex!important;
    order:2!important;
    width:100%!important;
    height:auto!important;
    min-height:0!important;
    max-height:none!important;
    overflow:hidden!important;
    margin:0!important;
    padding:22px!important;
    border-radius:22px!important;
    justify-content:flex-start!important;
  }
  .tr-ai-page > .page > .side .side-inner{
    width:100%!important;
    overflow:visible!important;
    padding-right:0!important;
  }
  .tr-ai-page > .page > .side .back{
    width:100%!important;
    margin-top:28px!important;
    margin-bottom:14px!important;
  }
  .tr-ai-page > .page > .side .side-brand-logo{
    max-width:180px!important;
  }
}

@media (max-width:560px){
  .tr-ai-page > .page > .chat-shell{
    height:calc(100dvh - 125px)!important;
    min-height:600px!important;
  }
  .tr-ai-page > .page > .side{
    padding:18px!important;
  }
  .tr-ai-page > .page > .side h1{
    font-size:26px!important;
  }
}
</style>
<!-- TERCIH ROBOTU V6 INDEX-NAV-EXACT -->
<style id="tercih-v6-index-nav-exact">
/* Index sayfasındaki menünün görünümü: iki ince ayırıcı çizgi ve aktif Ana Sayfa kapsülü. */
.site-chrome .nav{
  position:static!important; /* Formların üzerine binmemesi için normal akış korunur. */
  top:auto!important;
  z-index:auto!important;
  margin:0!important;
  padding:0!important;
  background:rgba(255,255,255,.78)!important;
  backdrop-filter:blur(10px)!important;
  -webkit-backdrop-filter:blur(10px)!important;
  border-top:1px solid rgba(10,37,64,.12)!important;
  border-bottom:1px solid rgba(10,37,64,.12)!important;
  box-shadow:none!important;
}
.site-chrome .nav-inner{
  display:flex!important;
  align-items:center!important;
  justify-content:flex-start!important;
  min-height:0!important;
  margin:0!important;
  padding:10px 0!important;
}
.site-chrome .menu{
  display:flex;
  align-items:center;
  flex-wrap:wrap;
  gap:10px!important;
  margin:0!important;
  padding:0!important;
}
.site-chrome .menu a{
  margin:0!important;
  padding:10px 12px!important;
  border:1px solid transparent!important;
  border-radius:999px!important;
  color:#475569!important;
  background:transparent!important;
  box-shadow:none!important;
  font-weight:600!important;
  transition:all .18s ease!important;
}
.site-chrome .menu a:hover{
  color:#0b1220!important;
  background:rgba(11,42,91,.06)!important;
  border-color:rgba(11,42,91,.18)!important;
}
.site-chrome .menu a[aria-current="page"]{
  color:#fff!important;
  background:linear-gradient(135deg,#0A2540,#123B6B)!important;
  border-color:transparent!important;
  box-shadow:0 10px 22px rgba(11,42,91,.18)!important;
}
@media(max-width:820px){
  .site-chrome .nav-inner{
    padding:10px 0!important;
    flex-wrap:wrap!important;
  }
  .site-chrome .menu{
    display:none!important;
    width:100%!important;
    padding:10px 0 4px!important;
  }
  .site-chrome .menu.open{
    display:flex!important;
  }
}
</style>

  <style>
    .user-message-stack{
      display:flex;
      flex-direction:column;
      align-items:flex-end;
      max-width:74%;
      min-width:0;
    }
    .user-message-stack .msg{max-width:100%}
    .answer-edit-inline{
      margin:5px 9px 0 0;
      padding:0;
      border:0;
      background:transparent;
      color:#6d28d9;
      font-size:12px;
      line-height:1.25;
      font-weight:900;
      text-decoration:underline;
      text-underline-offset:3px;
      cursor:pointer;
    }
    .answer-edit-inline:hover{color:#4c1d95}
    .answer-edit-inline:disabled{opacity:.45;cursor:not-allowed}

    .result-tools{flex-wrap:wrap}.result-search{flex:1;min-width:220px}
    .preference-row{grid-template-columns:46px minmax(0,1fr) auto!important;border:1px solid transparent;border-radius:16px;margin:7px 0;padding:13px 12px!important;box-shadow:0 5px 15px rgba(15,23,42,.035)}
    .preference-row.risk-yellow{background:#fff8cc;border-color:#facc15}.preference-row.safe-green{background:#ecfdf5;border-color:#86efac}.preference-row.balanced-blue{background:#eff6ff;border-color:#bfdbfe}.preference-row.unknown-gray{background:#f8fafc;border-color:#e2e8f0}
    .preference-number{width:36px;height:36px;border-radius:12px;display:flex;align-items:center;justify-content:center;background:#fff;border:1px solid rgba(148,163,184,.35);font-weight:1000;color:#334155;font-size:15px;align-self:start}
    .program-main{min-width:0}.program-tags{display:flex;gap:7px;flex-wrap:wrap;margin-top:8px}.program-tag{border-radius:999px;padding:5px 8px;font-size:11px;font-weight:950;background:rgba(255,255,255,.78);border:1px solid rgba(148,163,184,.30);color:#334155}
    .list-controls{display:flex;gap:5px;align-self:start}.list-control{width:34px;height:34px;border:1px solid #cbd5e1;background:#fff;border-radius:10px;font-weight:1000;cursor:pointer;color:#334155}.list-control.delete{color:#b91c1c;border-color:#fecaca;background:#fff7f7}.list-control:disabled{opacity:.35;cursor:not-allowed}
    .preference-row .result-program-meta,.preference-row .result-warning{grid-column:2/-1}
    .result-final-panel{display:none;padding:14px;background:#fff;border-top:1px solid var(--line)}.result-final-panel.show{display:block}
    .risk-alert{padding:13px 14px;border-radius:15px;background:#fff8cc;border:1px solid #facc15;color:#713f12;font-size:13px;font-weight:950;line-height:1.55;text-transform:uppercase}
    .source-alert{display:none;margin-top:11px;padding:12px 14px;border-radius:14px;background:#eef2ff;border:1px solid #c7d2fe;color:#312e81;font-size:13px;font-weight:900;line-height:1.5}.source-alert.show{display:block}
    .final-actions{display:flex;gap:9px;flex-wrap:wrap;margin-top:12px}.final-action{border:0;border-radius:13px;padding:11px 14px;font-weight:950;cursor:pointer}.finalize-list{background:linear-gradient(135deg,#16a34a,#0d9488);color:#fff}.save-pdf{background:linear-gradient(135deg,#7c3aed,#2563eb);color:#fff}.save-pdf:disabled{opacity:.45;cursor:not-allowed}.final-status{margin-top:9px;color:#475569;font-size:13px;font-weight:850}
    .result-more{cursor:pointer}.result-more.end{cursor:default;font-size:15px;font-weight:950;color:#166534}
    /* PDF: masaüstünde yatay, mobilde okunaklı dikey A4. Tüm metinler siyah; başlık alanları turuncu. */
    .pdf-export-root{position:fixed;left:-20000px;top:0;width:1123px;background:#fff;z-index:-99999;font-family:Arial,"Segoe UI",sans-serif;color:#000}
    .pdf-export-root,.pdf-export-root *{color:#000!important;-webkit-text-fill-color:#000!important;text-shadow:none!important}
    .pdf-export-page{position:relative;width:1123px;height:794px;box-sizing:border-box;padding:25px 28px 24px;background:#fff;overflow:hidden}
    .pdf-export-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:8px;padding:8px 10px;border-left:8px solid #f28c28;border-bottom:2px solid #f28c28;background:#fff7ed}
    .pdf-export-heading h1{margin:0;font-size:24px;line-height:1.1;color:#000;letter-spacing:-.25px}
    .pdf-export-brand{font-size:11px;font-weight:900;color:#000;letter-spacing:.7px;text-transform:uppercase}
    .pdf-export-info{border:1px solid #555;margin-bottom:10px;background:#fff}
    .pdf-export-info-row{min-height:23px;display:flex;align-items:center;padding:3px 8px;border-bottom:1px solid #aaa;font-size:10px;line-height:1.25;color:#000}
    .pdf-export-info-row:last-child{border-bottom:0}.pdf-export-info-row b{min-width:106px;color:#000}
    .pdf-export-table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:9px;line-height:1.16;color:#000}
    .pdf-export-table th,.pdf-export-table td{border:1px solid #555;padding:4px 5px;vertical-align:middle;box-sizing:border-box;color:#000}.pdf-export-table td{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .pdf-export-table th{height:29px;background:#f28c28!important;color:#000!important;font-size:9px;font-weight:900;text-align:center}
    .pdf-export-table tbody tr{height:31px}.pdf-export-table tbody tr:nth-child(even) td{background:#fff1df}
    .pdf-export-table td.c{text-align:center}.pdf-export-table td.r{text-align:right}
    .pdf-export-program-main{font-size:9px;font-weight:900;color:#000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .pdf-export-program-sub{margin-top:2px;font-size:8px;color:#000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .pdf-export-program-meta{margin-top:3px;font-size:8px;line-height:1.3;color:#000;white-space:normal}
    .pdf-export-table td.pdf-risk-cell{background:#d6a900!important;color:#000!important;font-weight:900;border-color:#7a5b00!important}
    .pdf-export-notes{margin-top:10px;border:1px solid #555;padding:9px 11px;background:#fff;font-size:9px;line-height:1.42;color:#000}
    .pdf-export-notes-title{display:inline-block;font-size:11px;font-weight:900;margin-bottom:5px;padding:4px 8px;background:#f28c28;color:#000}.pdf-export-notes p{margin:5px 0;color:#000}
    .pdf-export-risk-note,.pdf-export-source-note{font-weight:900;color:#000}
    .pdf-export-footer{position:absolute;left:28px;right:28px;bottom:8px;display:flex;justify-content:space-between;align-items:center;border-top:1px solid #555;padding-top:4px;font-size:8px;color:#000}

    /* Mobil PDF: her tercih tek geniş sütunda gösterilir. Böylece bölüm ve üniversite metni telefonda daha büyük okunur. */
    .pdf-export-root.pdf-mobile{width:794px}
    .pdf-export-root.pdf-mobile .pdf-export-page{width:794px;height:1123px;padding:22px 22px 28px}
    .pdf-export-root.pdf-mobile .pdf-export-heading{margin-bottom:8px;padding:9px 11px}
    .pdf-export-root.pdf-mobile .pdf-export-heading h1{font-size:26px}
    .pdf-export-root.pdf-mobile .pdf-export-brand{font-size:12px}
    .pdf-export-root.pdf-mobile .pdf-export-info{margin-bottom:8px}
    .pdf-export-root.pdf-mobile .pdf-export-info-row{min-height:27px;padding:4px 9px;font-size:12px;line-height:1.25}
    .pdf-export-root.pdf-mobile .pdf-export-info-row b{min-width:118px}
    .pdf-export-root.pdf-mobile .pdf-export-table{font-size:12px;line-height:1.32}
    .pdf-export-root.pdf-mobile .pdf-export-table th{height:36px;font-size:12.5px;padding:6px 8px;text-align:left}
    .pdf-export-root.pdf-mobile .pdf-export-table td{padding:10px 11px;white-space:normal;overflow:visible;text-overflow:clip;vertical-align:top}
    .pdf-export-root.pdf-mobile .pdf-export-table tbody tr{height:auto;min-height:78px}
    .pdf-export-root.pdf-mobile .pdf-export-program-main{display:flex;align-items:flex-start;gap:8px;font-size:15px;line-height:1.26;white-space:normal;overflow:visible;text-overflow:clip}
    .pdf-export-root.pdf-mobile .pdf-mobile-order{display:inline-flex;align-items:center;justify-content:center;flex:0 0 28px;width:28px;height:28px;border-radius:8px;background:#f28c28!important;border:1px solid #b85d00;font-size:13px;font-weight:900;color:#000!important}
    .pdf-export-root.pdf-mobile .pdf-mobile-program-text{display:block;flex:1;min-width:0;font-weight:900}
    .pdf-export-root.pdf-mobile .pdf-export-program-sub{margin:5px 0 0 36px;font-size:12.5px;line-height:1.3;white-space:normal;overflow:visible;text-overflow:clip;font-weight:700}
    .pdf-export-root.pdf-mobile .pdf-export-program-meta{display:flex;flex-wrap:wrap;gap:5px 10px;margin:7px 0 0 36px;font-size:11px;line-height:1.35;font-weight:800}
    .pdf-export-root.pdf-mobile .pdf-mobile-meta-item{display:inline-block;white-space:nowrap}
    .pdf-export-root.pdf-mobile .pdf-mobile-meta-label{font-weight:900}
    .pdf-export-root.pdf-mobile .pdf-mobile-rank-risk{display:inline-block;padding:1px 5px;background:#d6a900!important;border:1px solid #7a5b00!important;border-radius:3px;font-weight:900;color:#000!important}
    .pdf-export-root.pdf-mobile .pdf-export-notes{font-size:10.5px;line-height:1.42;padding:10px 11px}
    .pdf-export-root.pdf-mobile .pdf-export-notes-title{font-size:12px}
    .pdf-export-root.pdf-mobile .pdf-export-footer{left:22px;right:22px;bottom:9px;font-size:9px}

    /* Yalnızca sonuç kartının üst özetini sıkıştırır; program etiketi, arama ve liste eski görünümünde kalır. */
    .result-card{
      white-space:normal!important; /* .msg içindeki pre-wrap kaynaklı büyük boşlukları engeller */
    }
    .result-hero.result-hero-compact{
      padding:10px 14px 12px!important;
    }
    .result-hero-compact>.result-kicker{
      margin:0 0 2px!important;
      line-height:1.15!important;
    }
    .result-hero-compact>h3{
      margin:0!important;
      font-size:20px!important;
      line-height:1.12!important;
    }
    .result-hero-compact>p{
      margin:3px 0 0!important;
      line-height:1.28!important;
      white-space:normal!important;
    }
    .result-hero-compact>.result-note{
      margin:5px 0 0!important;
      padding:6px 9px!important;
      border-radius:11px!important;
      line-height:1.28!important;
    }
    .result-count-compact{
      display:flex;
      flex-wrap:wrap;
      gap:6px;
      margin:5px 0 0!important;
      padding:0!important;
    }
    .result-count-compact>.result-stat{
      padding:5px 8px!important;
      font-size:12px!important;
      line-height:1.2!important;
    }
    /* Bu noktadan sonrası eski sonuç tasarımıdır. */
    .result-hero-compact>.result-stats{
      margin-top:12px!important;
      gap:10px!important;
    }
    .result-hero-compact>.result-stats>.result-stat{
      padding:8px 11px!important;
      font-size:13px!important;
      line-height:normal!important;
    }
    .result-card>.result-tools{
      padding:12px 14px!important;
      gap:10px!important;
    }
    .result-card>.result-tools>.result-search{
      padding:11px 13px!important;
      border-radius:14px!important;
      font-size:15px!important;
    }

    @media(max-width:980px){
      .user-message-stack{max-width:88%}
      .preference-row{grid-template-columns:38px minmax(0,1fr)!important}
      .list-controls{grid-column:2/-1;justify-content:flex-end}
      .preference-row .result-program-meta,.preference-row .result-warning{grid-column:1/-1}
      .result-search{min-width:100%}
      .result-hero.result-hero-compact{padding:9px 11px 11px!important}
    }
  </style>

<style id="ai-payment-gate-style">
  .payment-required-card{
    border-color:#fed7aa!important;
    background:linear-gradient(180deg,#fff,#fff7ed)!important;
  }
  .payment-required-title{
    display:flex;
    align-items:center;
    gap:9px;
    margin-bottom:8px;
    color:#9a3412;
    font-size:17px;
    font-weight:950;
  }
  .payment-required-text{
    color:#431407;
    line-height:1.55;
  }
  .payment-required-button{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    margin-top:14px;
    padding:12px 17px;
    border-radius:14px;
    background:linear-gradient(135deg,#f97316,#ea580c);
    color:#fff!important;
    -webkit-text-fill-color:#fff!important;
    text-decoration:none;
    font-size:15px;
    font-weight:950;
    box-shadow:0 10px 24px rgba(234,88,12,.22);
    transition:transform .18s ease,filter .18s ease;
  }
  .payment-required-button:hover{transform:translateY(-1px);filter:brightness(1.03)}
  .activation-login-box{margin-top:14px;padding-top:14px;border-top:1px solid rgba(15,23,42,.12)}
  .activation-login-title{margin-bottom:8px;font-size:14px;font-weight:900;color:#312e81}
  .activation-login-form{display:flex;gap:8px;flex-wrap:wrap}
  .activation-code-input{flex:1 1 240px;min-width:0;min-height:43px;border:1px solid #cbd5e1;border-radius:11px;padding:10px 12px;font:inherit;font-weight:800;text-transform:uppercase;outline:none}
  .activation-code-input:focus{border-color:#7c3aed;box-shadow:0 0 0 4px rgba(124,58,237,.12)}
  .activation-login-button{border:0;border-radius:11px;background:#7c3aed;color:#fff;min-height:43px;padding:10px 15px;font-weight:900;cursor:pointer}
  .activation-login-error{margin-top:9px;padding:9px 11px;border-radius:10px;background:#fff1f2;color:#9f1239;font-size:13px;font-weight:800}
  .activation-login-help{margin-top:7px;color:#64748b;font-size:12px;line-height:1.45}
  .activation-account-badge{display:inline-flex;align-items:center;gap:7px;margin-left:auto;font-size:12px;font-weight:900;color:#4c1d95}
  .activation-account-badge a{color:#9f1239;text-decoration:underline}
  @media(max-width:980px){
    .payment-required-button{display:flex;width:100%;text-align:center}
  }

  .pdf-library{
    padding:13px 18px;
    border-bottom:1px solid var(--line);
    background:rgba(248,250,252,.94);
  }
  .pdf-library-head{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:10px;
  }
  .pdf-library-title{
    font-size:14px;
    font-weight:950;
    color:#0f172a;
  }
  .pdf-library-rights{
    color:#475569;
    font-size:12px;
    font-weight:800;
    white-space:nowrap;
  }
  .pdf-library-tools{
    display:flex;
    align-items:center;
    gap:10px;
    padding:0 14px 11px;
  }
  .pdf-library-search-wrap{
    position:relative;
    flex:1;
    min-width:0;
  }
  .pdf-library-search{
    width:100%;
    min-height:42px;
    border:1px solid #cbd5e1;
    border-radius:13px;
    background:#fff;
    color:#0f172a;
    padding:10px 42px 10px 40px;
    font:inherit;
    font-size:14px;
    font-weight:700;
    outline:none;
    transition:border-color .15s ease, box-shadow .15s ease;
  }
  .pdf-library-search:focus{
    border-color:#7c3aed;
    box-shadow:0 0 0 4px rgba(124,58,237,.12);
  }
  .pdf-library-search-icon{
    position:absolute;
    left:13px;
    top:50%;
    transform:translateY(-50%);
    color:#64748b;
    pointer-events:none;
    font-size:17px;
  }
  .owner-session-controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-left:auto}
  .owner-session-controls form{margin:0}
  .owner-session-btn{border:1px solid #93c5fd;background:#eff6ff;color:#1d4ed8;border-radius:10px;padding:8px 11px;font-weight:800;cursor:pointer}
  .owner-session-btn-danger{border-color:#fecaca;background:#fff1f2;color:#b91c1c}
  .owner-session-btn:disabled{opacity:.45;cursor:not-allowed}
  @media(max-width:820px){.owner-session-controls{width:100%;margin-left:0}.owner-session-controls form{flex:1 1 100%}.owner-session-btn{width:100%}}

  .pdf-library-search-clear{
    position:absolute;
    right:7px;
    top:50%;
    transform:translateY(-50%);
    width:30px;
    height:30px;
    border:0;
    border-radius:9px;
    background:#f1f5f9;
    color:#475569;
    cursor:pointer;
    font-size:17px;
    font-weight:900;
  }
  .pdf-library-search-clear[hidden]{display:none}
  .pdf-library-search-note{
    flex:0 0 auto;
    color:#64748b;
    font-size:12px;
    font-weight:800;
    white-space:nowrap;
  }
  .pdf-search-results{
    display:flex;
    flex-wrap:wrap;
    gap:9px;
    padding:0 14px 12px;
  }
  .pdf-search-results[hidden]{display:none}
  .pdf-search-status{
    width:100%;
    padding:2px 2px 0;
    color:#64748b;
    font-size:12px;
    font-weight:800;
  }
  .pdf-search-empty{
    width:100%;
    padding:12px 14px;
    border:1px dashed #cbd5e1;
    border-radius:12px;
    background:#f8fafc;
    color:#64748b;
    text-align:center;
    font-size:13px;
    font-weight:800;
  }
  .pdf-library-more-note{
    display:inline-flex;
    align-items:center;
    min-height:42px;
    padding:8px 11px;
    border:1px dashed #cbd5e1;
    border-radius:12px;
    color:#64748b;
    background:#f8fafc;
    font-size:12px;
    font-weight:800;
  }

  .pdf-library-list{
    display:flex;
    gap:9px;
    overflow-x:auto;
    padding:2px 2px 5px;
    scrollbar-width:thin;
  }
  .pdf-document-link{
    flex:0 0 auto;
    min-width:180px;
    max-width:250px;
    padding:10px 12px;
    border:1px solid #cbd5e1;
    border-radius:14px;
    background:#fff;
    color:#0f172a;
    text-decoration:none;
    box-shadow:0 5px 14px rgba(15,23,42,.05);
  }
  .pdf-document-link:hover{
    border-color:#7c3aed;
    transform:translateY(-1px);
  }
  .pdf-document-link.active{
    color:#fff;
    border-color:#6d28d9;
    background:linear-gradient(135deg,#6d28d9,#8b5cf6);
    box-shadow:0 10px 22px rgba(109,40,217,.20);
  }
  .pdf-document-name{
    display:block;
    font-size:13px;
    line-height:1.25;
    font-weight:950;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
  .pdf-document-meta{
    display:block;
    margin-top:4px;
    font-size:11px;
    line-height:1.2;
    opacity:.78;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
  .pdf-library-empty{
    color:#64748b;
    font-size:13px;
    font-weight:700;
  }
  .pdf-add-link{
    flex:0 0 auto;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:10px 13px;
    border-radius:14px;
    background:#f97316;
    color:#fff;
    text-decoration:none;
    font-size:13px;
    font-weight:950;
  }
  .pdf-switch-notice{
    margin:12px 18px 0;
    padding:10px 13px;
    border:1px solid #86efac;
    border-radius:12px;
    background:#f0fdf4;
    color:#166534;
    font-size:13px;
    font-weight:850;
  }
  @media(max-width:640px){
    .pdf-library{padding:11px 12px}
    .pdf-library-head{align-items:flex-start}
    .pdf-library-tools{
      padding:0 0 10px;
      flex-direction:column;
      align-items:stretch;
      gap:7px;
    }
    .pdf-library-search-note{
      white-space:normal;
      text-align:left;
    }
    .pdf-search-results{padding:0 0 10px}
    .pdf-library-rights{white-space:normal;text-align:right}
    .pdf-document-link{min-width:155px;max-width:205px}
    .pdf-add-link{padding:9px 11px}
  }
</style>

<!-- AI MOBIL SOHBET BUTONLARI GORUNURLUK DUZELTMESI BASLA -->
<style id="ai-mobile-composer-visibility-fix">
/*
 * Eski mobil kural, masaüstü sol bilgi panelini tekrar görünür yapıyor ve
 * sohbet kutusuna en az 600/650 px yükseklik zorluyordu. Kısa ekranlarda
 * bunun sonucu Gönder / Sıfırla alanının ekranın dışında kalmasıydı.
 */
@media (max-width:980px){
  body.tr-ai-page{
    overflow-x:hidden!important;
    overflow-y:auto!important;
  }

  .tr-ai-page > .page{
    display:block!important;
    width:100%!important;
    height:auto!important;
    min-height:0!important;
    max-height:none!important;
    margin-top:8px!important;
    padding:0 10px 10px!important;
  }

  /* Başlık ve uzun açıklamanın bulunduğu mavi panel mobilde sohbeti kapatmasın. */
  .tr-ai-page > .page > .side{
    display:none!important;
  }

  .tr-ai-page > .page > .chat-shell{
    display:flex!important;
    width:100%!important;
    height:var(--ai-mobile-chat-height, calc(100svh - 145px))!important;
    min-height:340px!important;
    max-height:var(--ai-mobile-chat-height, calc(100svh - 145px))!important;
    overflow:hidden!important;
    border-radius:20px!important;
  }

  .tr-ai-page > .page > .chat-shell #messages{
    flex:1 1 auto!important;
    min-height:0!important;
    overflow-y:auto!important;
    overscroll-behavior:contain;
  }

  .tr-ai-page > .page > .chat-shell .typing-wrap,
  .tr-ai-page > .page > .chat-shell .quick-replies,
  .tr-ai-page > .page > .chat-shell .composer,
  .tr-ai-page > .page > .chat-shell .hint{
    flex:0 0 auto!important;
  }

  .tr-ai-page > .page > .chat-shell .composer{
    position:relative!important;
    z-index:30!important;
    padding-bottom:max(10px, env(safe-area-inset-bottom))!important;
  }
}

/* Yatay kullanım ve yüksekliği kısa telefonlarda üst alanı da sıkıştır. */
@media (max-width:980px) and (max-height:720px){
  .tr-ai-page > .page > .chat-shell{
    min-height:300px!important;
  }
  .tr-ai-page .chat-head{
    padding:8px 10px!important;
  }
  .tr-ai-page .chat-head .avatar{
    width:38px!important;
    height:38px!important;
    flex-basis:38px!important;
  }
  .tr-ai-page .chat-title h2{
    font-size:16px!important;
  }
  .tr-ai-page .chat-title p,
  .tr-ai-page .hint{
    display:none!important;
  }
  .tr-ai-page .pdf-library{
    padding:8px 10px!important;
  }
  .tr-ai-page .pdf-library-head{
    margin-bottom:6px!important;
  }
  .tr-ai-page #messages{
    padding:10px!important;
  }
}
</style>
<!-- AI MOBIL SOHBET BUTONLARI GORUNURLUK DUZELTMESI BITIR -->



<!-- AI TAM EKRAN SOHBET DUZENI BASLA -->
<style id="ai-full-screen-chat-layout">
  html,
  body{
    width:100%;
    height:100%;
    min-height:100%;
    margin:0;
    overflow:hidden!important;
  }

  body.tr-ai-page{
    width:100%;
    height:100%;
    min-height:100%;
    overflow:hidden!important;
    background:
      radial-gradient(900px 420px at 12% -120px, rgba(124,58,237,.16), transparent 65%),
      radial-gradient(850px 420px at 88% -120px, rgba(6,182,212,.16), transparent 65%),
      linear-gradient(180deg,var(--bg1),var(--bg2));
  }

  .tr-ai-page > .page{
    display:block!important;
    width:100%!important;
    max-width:none!important;
    height:100vh!important;
    height:100dvh!important;
    min-height:0!important;
    max-height:none!important;
    margin:0!important;
    padding:0!important;
  }

  .tr-ai-page > .page > .side{
    display:none!important;
  }

  .tr-ai-page > .page > .chat-shell{
    width:100%!important;
    height:100%!important;
    min-height:0!important;
    max-height:none!important;
    margin:0!important;
    border:0!important;
    border-radius:0!important;
    box-shadow:none!important;
    overflow:hidden!important;
  }

  .tr-ai-page .chat-head{
    flex:0 0 auto;
  }

  .tr-ai-page #messages{
    flex:1 1 auto!important;
    min-height:0!important;
  }

  .tr-ai-page .composer{
    padding-bottom:max(12px, env(safe-area-inset-bottom))!important;
  }

  @media (max-width:980px){
    .tr-ai-page > .page{
      height:var(--ai-mobile-chat-height, 100dvh)!important;
    }

    .tr-ai-page > .page > .chat-shell{
      height:100%!important;
      min-height:0!important;
      max-height:none!important;
      border-radius:0!important;
    }

    .tr-ai-page .chat-head{
      padding-left:12px!important;
      padding-right:12px!important;
    }

    .tr-ai-page #messages{
      padding-left:12px!important;
      padding-right:12px!important;
    }
  }

  @media (max-width:560px){
    .tr-ai-page .chat-title p{
      display:none!important;
    }

    .tr-ai-page .chat-title h2{
      font-size:18px!important;
    }

    .tr-ai-page .status{
      padding:7px 9px!important;
      font-size:11px!important;
      max-width:42vw;
      overflow:hidden;
      text-overflow:ellipsis;
    }
  }
</style>
<!-- AI TAM EKRAN SOHBET DUZENI BITIR -->


<!-- CHATGPT BENZERI ACILIR SOL MENU BASLA -->
<style id="ai-chatgpt-sidebar-layout">
  :root{--ai-sidebar-width:340px}

  body.tr-ai-page{overflow:hidden!important}

  .tr-ai-page > .page{
    display:flex!important;
    width:100%!important;
    height:100vh!important;
    height:100dvh!important;
    min-height:0!important;
    margin:0!important;
    padding:0!important;
    overflow:hidden!important;
  }

  .tr-ai-page > .page > .ai-sidebar{
    position:relative;
    z-index:90;
    display:flex!important;
    flex:0 0 var(--ai-sidebar-width);
    width:var(--ai-sidebar-width);
    min-width:0;
    height:100%;
    overflow:hidden;
    color:#0f172a;
    background:#f7f7f8;
    border-right:1px solid #e5e7eb;
    box-shadow:8px 0 28px rgba(15,23,42,.05);
    transition:flex-basis .22s ease,width .22s ease,transform .22s ease,opacity .18s ease;
  }

  .tr-ai-page > .page.sidebar-desktop-collapsed > .ai-sidebar{
    flex-basis:0;
    width:0;
    border-right:0;
    box-shadow:none;
    transform:translateX(-100%);
    opacity:0;
    pointer-events:none;
  }

  .ai-sidebar{
    flex-direction:column;
  }

  .ai-sidebar-head{
    flex:0 0 auto;
    min-height:70px;
    display:flex;
    align-items:center;
    gap:10px;
    padding:11px 12px 10px 16px;
    border-bottom:1px solid #e5e7eb;
    background:rgba(247,247,248,.94);
    backdrop-filter:blur(12px);
  }

  .ai-sidebar-logo-link{display:flex;align-items:center;min-width:0;flex:1;text-decoration:none}
  .ai-sidebar-logo{display:block;width:188px;max-width:100%;height:48px;object-fit:contain;object-position:left center}
  .ai-sidebar-close{
    width:38px;height:38px;display:grid;place-items:center;flex:0 0 38px;
    border:1px solid #d1d5db;border-radius:11px;background:#fff;color:#475569;
    font-size:25px;line-height:1;cursor:pointer;
  }
  .ai-sidebar-close:hover{background:#eef2ff;color:#5b21b6;border-color:#c4b5fd}

  .ai-sidebar-scroll{
    flex:1 1 auto;
    min-height:0;
    overflow-y:auto;
    overflow-x:hidden;
    padding:12px;
    scrollbar-width:thin;
  }

  .ai-sidebar-intro{
    display:flex;flex-direction:column;gap:5px;margin-bottom:14px;padding:13px 14px;
    border:1px solid #ddd6fe;border-radius:15px;
    background:linear-gradient(135deg,#f5f3ff,#ecfeff);
  }
  .ai-sidebar-intro strong{font-size:14px;color:#4c1d95}
  .ai-sidebar-intro span{font-size:12px;line-height:1.45;color:#64748b;font-weight:700}

  .ai-sidebar-section-title{
    margin:0 8px 7px;
    color:#64748b;
    font-size:11px;
    font-weight:950;
    letter-spacing:.08em;
    text-transform:uppercase;
  }
  .ai-sidebar-section-spaced{margin-top:18px}

  .ai-sidebar-nav{display:block;margin-bottom:16px}
  .ai-sidebar-nav-link{
    display:flex;align-items:center;gap:11px;width:100%;min-height:43px;
    margin:2px 0;padding:9px 11px;border:1px solid transparent;border-radius:11px;
    color:#334155;text-decoration:none;font-size:14px;font-weight:800;
    transition:background .15s ease,border-color .15s ease,color .15s ease,transform .15s ease;
  }
  .ai-sidebar-nav-link > span:first-child{
    display:grid;place-items:center;flex:0 0 24px;width:24px;height:24px;
    color:#64748b;font-size:15px;font-weight:950;
  }
  .ai-sidebar-nav-link:hover{background:#ececf1;border-color:#e2e8f0;color:#111827;transform:translateX(1px)}
  .ai-sidebar-nav-link.active{background:#e9e7ff;border-color:#d8b4fe;color:#4c1d95}
  .ai-sidebar-nav-link.active > span:first-child{color:#7c3aed}

  .ai-sidebar-account{
    margin:0 0 14px;padding:13px;border:1px solid #e2e8f0;border-radius:15px;background:#fff;
  }
  .ai-sidebar-account .ai-sidebar-section-title{margin-left:1px;margin-right:1px}
  .ai-sidebar .status.ai-sidebar-status{
    display:flex!important;align-items:flex-start!important;gap:8px;width:100%;max-width:none!important;
    margin:0 0 10px;padding:10px 11px;border-radius:12px;white-space:normal!important;
    font-size:12px!important;line-height:1.38;text-overflow:clip!important;overflow:visible!important;
  }
  .ai-sidebar .status.ai-sidebar-status .dot-live{margin-top:4px;flex:0 0 8px}
  .ai-sidebar-action-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
  .ai-sidebar-action{
    display:flex;align-items:center;justify-content:center;min-height:40px;padding:9px 8px;
    border:1px solid #d1d5db;border-radius:11px;background:#fff;color:#334155;
    text-align:center;text-decoration:none;font-size:12px;font-weight:900;
  }
  .ai-sidebar-action:hover{border-color:#a78bfa;color:#5b21b6;background:#faf5ff}
  .ai-sidebar-action.primary{border-color:#7c3aed;background:#7c3aed;color:#fff}
  .ai-sidebar-action.primary:hover{background:#6d28d9;color:#fff}

  .ai-sidebar .pdf-library{
    margin:0 0 14px;padding:13px!important;border:1px solid #e2e8f0!important;border-radius:15px;
    background:#fff!important;
  }
  .ai-sidebar .pdf-library-head{display:flex;align-items:flex-start;gap:7px;flex-wrap:wrap;margin-bottom:10px}
  .ai-sidebar .pdf-library-title{width:100%;font-size:14px}
  .ai-sidebar .pdf-library-rights{font-size:11px;white-space:normal;text-align:left}
  .ai-sidebar .activation-account-badge{width:100%;margin-left:0;justify-content:space-between;padding:8px 9px;border-radius:10px;background:#f5f3ff}
  .ai-sidebar .owner-session-controls{width:100%;margin-left:0;display:grid;grid-template-columns:1fr;gap:7px}
  .ai-sidebar .owner-session-controls form{width:100%}
  .ai-sidebar .owner-session-btn{width:100%;font-size:11px;padding:8px 9px}
  .ai-sidebar .pdf-library-tools{display:block;padding:0 0 10px!important}
  .ai-sidebar .pdf-library-search-wrap{width:100%}
  .ai-sidebar .pdf-library-search{min-height:40px;font-size:12px;padding-left:36px}
  .ai-sidebar .pdf-library-search-note{display:block;margin-top:6px;white-space:normal;font-size:11px}
  .ai-sidebar .pdf-library-list{display:flex;flex-direction:column;gap:7px;overflow:visible;padding:0}
  .ai-sidebar .pdf-document-link{display:block;width:100%;min-width:0!important;max-width:none!important;padding:10px 11px}
  .ai-sidebar .pdf-library-more-note{width:100%;min-height:0;padding:9px 10px;font-size:11px}
  .ai-sidebar .pdf-add-link{display:flex;width:100%;min-height:40px;padding:9px 11px}
  .ai-sidebar .pdf-search-results{display:flex;flex-direction:column;flex-wrap:nowrap;gap:7px;padding:0 0 5px}
  .ai-sidebar .pdf-search-results[hidden]{display:none}
  .ai-sidebar .pdf-search-empty{font-size:12px}

  .ai-sidebar-notices{display:flex;flex-direction:column;gap:8px}
  .ai-sidebar-notices .pdf-switch-notice{margin:0!important;padding:10px 11px;font-size:12px;line-height:1.4}

  .ai-sidebar-footer{
    flex:0 0 auto;display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:11px 15px;border-top:1px solid #e5e7eb;background:#f7f7f8;
    color:#64748b;font-size:11px;font-weight:800;
  }
  .ai-sidebar-footer a{color:#5b21b6;text-decoration:none}

  .ai-sidebar-backdrop{display:none;border:0;padding:0;background:rgba(15,23,42,.48)}

  .tr-ai-page > .page > .chat-shell{
    flex:1 1 auto!important;
    width:auto!important;
    min-width:0!important;
    height:100%!important;
    min-height:0!important;
    max-height:none!important;
    border:0!important;
    border-radius:0!important;
    box-shadow:none!important;
  }

  .tr-ai-page .chat-head.ai-compact-chat-head{
    min-height:64px;
    padding:9px 14px!important;
    justify-content:flex-start;
    gap:10px;
    background:rgba(255,255,255,.92);
    backdrop-filter:blur(14px);
  }
  .ai-sidebar-toggle{
    display:grid;place-items:center;flex:0 0 42px;width:42px;height:42px;
    border:1px solid #dbe3ee;border-radius:12px;background:#fff;color:#334155;
    font-size:21px;cursor:pointer;box-shadow:0 4px 12px rgba(15,23,42,.04);
  }
  .ai-sidebar-toggle:hover{background:#f5f3ff;border-color:#c4b5fd;color:#6d28d9}
  .ai-compact-chat-head .avatar-line{flex:1;gap:9px}
  .ai-compact-chat-head .avatar{width:42px;height:42px;flex-basis:42px}
  .ai-compact-chat-head .chat-title h2{font-size:18px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .ai-compact-upload{
    display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;
    min-height:40px;padding:9px 12px;border:1px solid #ddd6fe;border-radius:12px;
    background:#f5f3ff;color:#5b21b6;text-decoration:none;font-size:13px;font-weight:950;
  }
  .ai-compact-upload:hover{background:#ede9fe;border-color:#c4b5fd}

  @media (max-width:980px){
    :root{--ai-sidebar-width:min(88vw,360px)}
    .tr-ai-page > .page{display:block!important}
    .tr-ai-page > .page > .ai-sidebar{
      position:fixed!important;inset:0 auto 0 0!important;z-index:1002!important;
      width:var(--ai-sidebar-width)!important;max-width:360px;flex-basis:auto!important;
      transform:translateX(-102%);opacity:1;pointer-events:none;
      box-shadow:18px 0 50px rgba(15,23,42,.22);
    }
    .tr-ai-page > .page.sidebar-mobile-open > .ai-sidebar{transform:translateX(0);pointer-events:auto}
    .tr-ai-page > .page.sidebar-desktop-collapsed > .ai-sidebar{width:var(--ai-sidebar-width)!important;opacity:1}
    .tr-ai-page > .page > .ai-sidebar-backdrop{
      position:fixed;inset:0;z-index:1001;display:block;opacity:0;visibility:hidden;
      transition:opacity .2s ease,visibility .2s ease;
    }
    .tr-ai-page > .page.sidebar-mobile-open > .ai-sidebar-backdrop{opacity:1;visibility:visible}
    .tr-ai-page > .page > .chat-shell{width:100%!important;height:100%!important}
    .tr-ai-page .chat-head.ai-compact-chat-head{min-height:58px;padding:7px 9px!important}
    .ai-sidebar-toggle{width:40px;height:40px;flex-basis:40px}
    .ai-compact-chat-head .avatar{width:38px;height:38px;flex-basis:38px}
    .ai-compact-chat-head .chat-title h2{font-size:16px!important}
    .ai-compact-upload{min-height:38px;padding:8px 10px;font-size:12px}
    .ai-sidebar .status.ai-sidebar-status{display:flex!important}
  }

  @media (max-width:480px){
    .ai-compact-chat-head .avatar{display:none}
    .ai-compact-chat-head .chat-title h2{font-size:15px!important}
    .ai-compact-upload{padding:8px 9px}
    .ai-sidebar-action-grid{grid-template-columns:1fr}
  }
</style>
<!-- CHATGPT BENZERI ACILIR SOL MENU BITIR -->

<!-- MOBIL TAM GENISLIK SONUC VE CHATGPT TIPI MESAJ KUTUSU BASLA -->
<style id="ai-mobile-full-width-results-and-inline-composer">
@media (max-width:980px){
  /* Sonuç kartları robot avatarı için solda boşluk bırakmadan tüm sohbet genişliğini kullansın. */
  .tr-ai-page #messages{
    padding-left:8px!important;
    padding-right:8px!important;
  }
  .tr-ai-page #messages > .result-message-row{
    display:block!important;
    width:100%!important;
    max-width:none!important;
    margin:0!important;
    padding:0!important;
  }
  .tr-ai-page #messages > .result-message-row > .mini-avatar{
    display:none!important;
  }
  .tr-ai-page #messages > .result-message-row > .result-card{
    display:block!important;
    width:100%!important;
    max-width:none!important;
    min-width:0!important;
    margin:0!important;
    border-radius:15px!important;
  }
  .tr-ai-page .result-card .result-list{
    padding-left:4px!important;
    padding-right:4px!important;
  }
  .tr-ai-page .result-card .result-row{
    width:100%!important;
    min-width:0!important;
  }

  /* Mesaj alanı ChatGPT benzeri tek kutu olur; üç işlem düğmesi kutunun içinde görünür. */
  .tr-ai-page .composer{
    position:relative!important;
    display:block!important;
    flex-wrap:nowrap!important;
    padding:8px!important;
    padding-bottom:max(8px, env(safe-area-inset-bottom))!important;
    gap:0!important;
    background:#fff!important;
  }
  .tr-ai-page .composer textarea{
    display:block!important;
    width:100%!important;
    min-height:56px!important;
    max-height:150px!important;
    margin:0!important;
    padding:15px 142px 15px 15px!important;
    border-radius:22px!important;
    border:1px solid #cbd5e1!important;
    background:#f8fafc!important;
    font-size:15px!important;
    line-height:1.42!important;
    box-shadow:0 5px 18px rgba(15,23,42,.06)!important;
  }
  .tr-ai-page .composer textarea:focus{
    background:#fff!important;
    border-color:#a78bfa!important;
    box-shadow:0 0 0 3px rgba(124,58,237,.10),0 6px 20px rgba(15,23,42,.07)!important;
  }
  .tr-ai-page .composer .reset,
  .tr-ai-page .composer .mic,
  .tr-ai-page .composer .send{
    position:absolute!important;
    z-index:3!important;
    bottom:calc(max(8px, env(safe-area-inset-bottom)) + 8px)!important;
    display:inline-grid!important;
    place-items:center!important;
    width:38px!important;
    height:38px!important;
    min-height:38px!important;
    max-height:38px!important;
    flex:none!important;
    margin:0!important;
    padding:0!important;
    border-radius:13px!important;
    font-size:0!important;
    line-height:1!important;
    box-shadow:none!important;
  }
  .tr-ai-page .composer .reset{right:98px!important;background:#eef2f7!important;color:#475569!important;border:1px solid #dbe3ee!important}
  .tr-ai-page .composer .mic{right:54px!important;background:#0f172a!important;color:#fff!important;border:1px solid #0f172a!important}
  .tr-ai-page .composer .send{right:10px!important;background:linear-gradient(135deg,var(--brand),var(--brand2))!important;color:#fff!important;border:0!important}

  /* Emoji yerine her cihazda aynı görünen keskin SVG ikonlar kullanılır. */
  .tr-ai-page .composer .reset,
  .tr-ai-page .composer .mic,
  .tr-ai-page .composer .send{
    border-radius:999px!important;
    transition:transform .14s ease, background-color .14s ease, border-color .14s ease, box-shadow .14s ease!important;
  }
  .tr-ai-page .composer .reset::before,
  .tr-ai-page .composer .mic::before,
  .tr-ai-page .composer .send::before{
    content:"";
    display:block;
    width:19px;
    height:19px;
    background:currentColor;
    -webkit-mask-repeat:no-repeat;
    mask-repeat:no-repeat;
    -webkit-mask-position:center;
    mask-position:center;
    -webkit-mask-size:contain;
    mask-size:contain;
  }
  .tr-ai-page .composer .reset::before{
    -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 6h18M8 6V4h8v2M7 6l1 14h8l1-14M10 11v5M14 11v5'/%3E%3C/svg%3E");
    mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 6h18M8 6V4h8v2M7 6l1 14h8l1-14M10 11v5M14 11v5'/%3E%3C/svg%3E");
  }
  .tr-ai-page .composer .mic::before{
    -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 15a3 3 0 0 0 3-3V7a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3ZM12 15v4M8 19h8M19 12a7 7 0 0 1-14 0'/%3E%3C/svg%3E");
    mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 15a3 3 0 0 0 3-3V7a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3ZM12 15v4M8 19h8M19 12a7 7 0 0 1-14 0'/%3E%3C/svg%3E");
  }
  .tr-ai-page .composer .send::before{
    -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 19V5M6 11l6-6 6 6'/%3E%3C/svg%3E");
    mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 19V5M6 11l6-6 6 6'/%3E%3C/svg%3E");
  }
  .tr-ai-page .composer .mic.listening{background:#dc2626!important;border-color:#dc2626!important}
  .tr-ai-page .composer .mic.listening::before{
    -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect x='6' y='6' width='12' height='12' rx='2'/%3E%3C/svg%3E");
    mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect x='6' y='6' width='12' height='12' rx='2'/%3E%3C/svg%3E");
  }
  .tr-ai-page .composer .reset:active,
  .tr-ai-page .composer .mic:active,
  .tr-ai-page .composer .send:active{transform:scale(.92)!important}

  /* Mobilde artık butonların açıklaması ikonların aria-label değerlerinde bulunuyor. */
  .tr-ai-page #composerHint{
    display:none!important;
  }
}

/* Son mesajın üst kenarına hizalanabilmesi için kaydırma alanının sonunda kontrollü boşluk bırakılır. */
.tr-ai-page #messages:not(.initial-question)::after{
  content:"";
  display:block;
  flex:0 0 calc(100% - 86px);
  width:1px;
  min-height:24px;
  pointer-events:none;
}

@media (max-width:480px){
  .tr-ai-page .composer textarea{
    padding-right:132px!important;
  }
  .tr-ai-page .composer .reset,
  .tr-ai-page .composer .mic,
  .tr-ai-page .composer .send{
    width:36px!important;
    height:36px!important;
    min-height:36px!important;
    max-height:36px!important;
    bottom:calc(max(8px, env(safe-area-inset-bottom)) + 10px)!important;
  }
  .tr-ai-page .composer .reset{right:92px!important}
  .tr-ai-page .composer .mic{right:51px!important}
  .tr-ai-page .composer .send{right:10px!important}
}
</style>
<!-- MOBIL TAM GENISLIK SONUC VE CHATGPT TIPI MESAJ KUTUSU BITIR -->



<!-- SON MOBIL KLAVYE / BOSLUK VE GENIS SONUC DUZELTMELERI BASLA -->
<style id="ai-final-mobile-keyboard-and-result-width-fix">
/* Masaüstünde genişleyen sohbet alanını sonuç listeleri de tamamen kullansın. */
@media (min-width:981px){
  .tr-ai-page #messages > .result-message-row{
    width:100%!important;
    max-width:none!important;
    align-items:flex-start!important;
  }
  .tr-ai-page #messages > .result-message-row > .result-card{
    flex:1 1 auto!important;
    width:auto!important;
    max-width:none!important;
    min-width:0!important;
    margin-right:0!important;
  }
}

@media (max-width:980px){
  /* Boş hızlı cevap ve yazıyor alanları mesaj kutusunun üstünde beyaz şerit oluşturmasın. */
  .tr-ai-page .quick-replies:empty{
    display:none!important;
    padding:0!important;
    min-height:0!important;
  }
  .tr-ai-page .typing-wrap{
    height:0!important;
    min-height:0!important;
    padding:0!important;
    overflow:hidden!important;
  }
  .tr-ai-page .typing-wrap.show{
    height:auto!important;
    min-height:30px!important;
    padding:0 6px 5px!important;
    overflow:visible!important;
  }

  /* Önceki kaydırma yardımcısının oluşturduğu büyük beyaz alt boşluğu mobilde kaldır. */
  .tr-ai-page #messages:not(.initial-question)::after{
    content:none!important;
    display:none!important;
    min-height:0!important;
    flex-basis:0!important;
  }

  /* Mesaj kutusunu kenarlara yaklaştırıp sohbet için daha fazla alan bırak. */
  .tr-ai-page .composer{
    border-top:0!important;
    padding:0 4px max(4px, env(safe-area-inset-bottom))!important;
    background:#fff!important;
  }
  .tr-ai-page .composer textarea{
    min-height:54px!important;
    padding-left:14px!important;
    border-radius:20px!important;
  }
  .tr-ai-page .composer .reset,
  .tr-ai-page .composer .mic,
  .tr-ai-page .composer .send{
    bottom:calc(max(4px, env(safe-area-inset-bottom)) + 8px)!important;
  }

  /* Bölüm/program sonuçları mobil sohbetin gerçek tam genişliğini kullansın. */
  .tr-ai-page #messages{
    padding-left:4px!important;
    padding-right:4px!important;
    padding-bottom:4px!important;
  }
  .tr-ai-page #messages > .result-message-row,
  .tr-ai-page #messages > .result-message-row > .result-card{
    width:100%!important;
    max-width:none!important;
    margin-left:0!important;
    margin-right:0!important;
  }

  /* Liste büyürken mobil tarayıcının eski alt konumu korumasını engelle. */
  .tr-ai-page #messages,
  .tr-ai-page #messages > .result-message-row,
  .tr-ai-page #messages .result-card,
  .tr-ai-page #messages .result-list,
  .tr-ai-page #messages .result-row{
    overflow-anchor:none!important;
  }
}
</style>
<!-- SON MOBIL KLAVYE / BOSLUK VE GENIS SONUC DUZELTMELERI BITIR -->

</head>
<body class="tr-ai-page">
<div class="page">
  <aside class="ai-sidebar" id="aiSidebar" aria-label="Tercih Robotu yan menüsü">
    <div class="ai-sidebar-head">
      <a class="ai-sidebar-logo-link" href="/" aria-label="Tercih Robotu ana sayfa">
        <img class="ai-sidebar-logo" src="/css/logo.png" alt="Tercih Robotu">
      </a>
      <button class="ai-sidebar-close" id="aiSidebarClose" type="button" aria-label="Menüyü kapat">×</button>
    </div>

    <div class="ai-sidebar-scroll">
      <div class="ai-sidebar-intro">
        <strong>Yapay Zeka Tercih Robotu</strong>
      </div>

      <nav class="ai-sidebar-nav" aria-label="Site bağlantıları">
        <div class="ai-sidebar-section-title">Site Menüsü</div>
        <a href="/" class="ai-sidebar-nav-link"><span aria-hidden="true">⌂</span><span>Ana Sayfa</span></a>
        <a href="/universiteler/" class="ai-sidebar-nav-link"><span aria-hidden="true">🏛</span><span>Üniversiteler</span></a>
        <a href="/bolumler/" class="ai-sidebar-nav-link"><span aria-hidden="true">▦</span><span>Bölümler</span></a>
        <a href="/meslekler/" class="ai-sidebar-nav-link"><span aria-hidden="true">💼</span><span>Meslekler</span></a>
        <a href="/tercihte-12-kural/" class="ai-sidebar-nav-link"><span aria-hidden="true">✓</span><span>Tercihte 12 Kural</span></a>

        <div class="ai-sidebar-section-title ai-sidebar-section-spaced">Robotlar</div>
        <a href="/ia-tercih-robotu/" class="ai-sidebar-nav-link active" aria-current="page"><span aria-hidden="true">✦</span><span>Yapay Zeka Tercih Robotu</span></a>
        <a href="/yks-puan-hesaplama/" class="ai-sidebar-nav-link"><span aria-hidden="true">∑</span><span>Net Hesap Robotu</span></a>
        <a href="/kpss-tercih-robotu/" class="ai-sidebar-nav-link"><span aria-hidden="true">K</span><span>KPSS Tercih</span></a>
      </nav>

      <section class="ai-sidebar-account" aria-label="Kullanım durumu">
        <div class="ai-sidebar-section-title">Hesap ve Kullanım</div>
        <div class="status ai-sidebar-status" id="pdfAccessStatus">
          <span class="dot-live"></span>
          <span id="pdfAccessStatusText"><?= h($accessStatusText) ?></span>
        </div>
        <div class="ai-sidebar-action-grid">
          <a class="ai-sidebar-action primary" href="/ia-step1.php">＋ Yeni PDF yükle</a>
          <a class="ai-sidebar-action" href="<?= h($paymentUrl) ?>">Paket satın al</a>
        </div>
      </section>

    <section class="pdf-library" aria-label="Sonuç belgelerim">
      <div class="pdf-library-head">
        <div class="pdf-library-title">📄 Sonuç Belgelerim (<?= count($pdfProfiles) ?>)</div>
        <div class="pdf-library-rights">Yeni belge hakkı: <?= $ownerUnlimited ? 'Sınırsız' : (int)$remainingPdfRights ?></div>
        <?php if ($ownerUnlimited): ?>
          <div class="owner-session-controls" aria-label="Yönetici oturum işlemleri">
            <form method="post" action="/ia-tercih-robotu/" onsubmit="return confirm('Aktif yönetici PDF ve sohbet oturumu kaldırılsın mı?');">
              <input type="hidden" name="owner_session_csrf" value="<?= h((string)($_SESSION['ai_owner_session_csrf'] ?? '')) ?>">
              <input type="hidden" name="owner_session_action" value="delete_one">
              <input type="hidden" name="pdf_key" value="<?= h($currentPdfKey) ?>">
              <button class="owner-session-btn" type="submit" <?= $currentPdfKey === '' ? 'disabled' : '' ?>>Aktif oturumu kaldır</button>
            </form>
            <form method="post" action="/ia-tercih-robotu/" onsubmit="return confirm('Yalnız bu yönetici tarayıcısına ait TÜM PDF ve sohbet oturumları silinsin mi? Bu işlem diğer kullanıcıları etkilemez.');">
              <input type="hidden" name="owner_session_csrf" value="<?= h((string)($_SESSION['ai_owner_session_csrf'] ?? '')) ?>">
              <input type="hidden" name="owner_session_action" value="clear_all">
              <button class="owner-session-btn owner-session-btn-danger" type="submit">Tüm yönetici oturumlarını temizle</button>
            </form>
          </div>
        <?php endif; ?>
        <?php if ($activationLoggedIn): ?>
          <div class="activation-account-badge">
            🔑 Aktivasyon hesabı <?= h($activationCodeHint) ?>
            <a href="/ia-tercih-robotu/?activation_logout=1">Çıkış</a>
          </div>
        <?php endif; ?>
      </div>

      <?php if ($pdfProfiles): ?>
        <div class="pdf-library-tools">
          <div class="pdf-library-search-wrap">
            <span class="pdf-library-search-icon" aria-hidden="true">⌕</span>
            <input
              class="pdf-library-search"
              id="pdfLibrarySearch"
              type="search"
              inputmode="search"
              autocomplete="off"
              placeholder="Ad soyad veya T.C. kimlik no ile ara"
              aria-label="Sonuç belgelerinde ara">
            <button
              class="pdf-library-search-clear"
              id="pdfLibrarySearchClear"
              type="button"
              aria-label="Aramayı temizle"
              hidden>×</button>
          </div>
          <div class="pdf-library-search-note">Son 5 sohbet gösteriliyor</div>
        </div>
      <?php endif; ?>

      <div class="pdf-library-list" id="recentPdfList">
        <?php foreach ($recentPdfProfiles as $profile): ?>
          <?php
            $profileKey = (string)($profile['pdf_key'] ?? '');
            $profileLabel = (string)($profile['label'] ?? 'Sonuç Belgesi');
            $profileOriginal = (string)($profile['original_name'] ?? '');
            $profileDate = (string)($profile['last_opened_at'] ?? $profile['uploaded_at'] ?? $profile['authorized_at'] ?? '');
            $profileMeta = trim($profileOriginal . ($profileDate !== '' ? ' · ' . substr($profileDate, 0, 10) : ''));
          ?>
          <a class="pdf-document-link <?= $profileKey === $currentPdfKey ? 'active' : '' ?>"
             href="/ia-tercih-robotu/?pdf=<?= rawurlencode($profileKey) ?>"
             title="<?= h($profileLabel) ?>">
            <span class="pdf-document-name"><?= $profileKey === $currentPdfKey ? '✓ ' : '' ?><?= h($profileLabel) ?></span>
            <?php if ($profileMeta !== ''): ?><span class="pdf-document-meta"><?= h($profileMeta) ?></span><?php endif; ?>
          </a>
        <?php endforeach; ?>

        <?php if (!$pdfProfiles): ?>
          <span class="pdf-library-empty">Henüz yüklenmiş bir sonuç belgesi yok.</span>
        <?php elseif (count($pdfProfiles) > 5): ?>
          <span class="pdf-library-more-note">Diğer <?= count($pdfProfiles) - 5 ?> belgeyi yukarıdaki arama kutusundan bulabilirsiniz.</span>
        <?php endif; ?>

        <?php if ($ownerUnlimited || $remainingPdfRights > 0): ?>
          <a class="pdf-add-link" href="/ia-step1.php">＋ Yeni PDF yükle</a>
        <?php endif; ?>
      </div>

      <div class="pdf-search-results" id="pdfSearchResults" hidden></div>
    </section>

      <div class="ai-sidebar-notices" aria-live="polite">
    <?php if ($ownerResetFlash !== ''): ?>
      <div class="pdf-switch-notice" style="background:#ecfdf3;border-color:#abefc6;color:#05603a">
        <?= h($ownerResetFlash) ?>
      </div>
    <?php endif; ?>

    <?php if ($pdfSwitchNotice !== ''): ?>
      <div class="pdf-switch-notice">Aktif belge değiştirildi: <?= h($pdfSwitchNotice) ?></div>
    <?php endif; ?>

    <?php if ($singleTcContinueNotice): ?>
      <div class="pdf-switch-notice" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af">
        Bu T.C. kimlik numarasına ait mevcut tek sohbet oturumu açıldı.
      </div>
    <?php endif; ?>

    <?php if ($activationFlashSuccess !== ''): ?>
      <div class="pdf-switch-notice" style="background:#ecfdf3;border-color:#abefc6;color:#05603a">
        <?= h($activationFlashSuccess) ?>
      </div>
    <?php endif; ?>
      </div>
    </div>

    <div class="ai-sidebar-footer">
      <span>Tercih Robotu · 2026</span>
      <a href="/duyurular/">Duyurular</a>
    </div>
  </aside>
  <button class="ai-sidebar-backdrop" id="aiSidebarBackdrop" type="button" aria-label="Menüyü kapat" tabindex="-1"></button>
  <main class="chat-shell">
    <header class="chat-head ai-compact-chat-head">
      <button
        class="ai-sidebar-toggle"
        id="aiSidebarToggle"
        type="button"
        aria-label="Menüyü aç veya kapat"
        aria-controls="aiSidebar"
        aria-expanded="true">
        <span aria-hidden="true">☰</span>
      </button>
      <div class="avatar-line">
        <img class="avatar" src="/robot.png" alt="Robot" width="44" height="44">
        <div class="chat-title">
          <h2>Tercih Robotu Yapay Zeka</h2>
        </div>
      </div>
      <a class="ai-compact-upload" href="/ia-step1.php" aria-label="Yeni sonuç belgesi yükle" title="Yeni sonuç belgesi yükle">＋ PDF</a>
    </header>





    <section id="messages" aria-live="polite"></section>

    <div id="quickReplies" class="quick-replies" aria-label="Hızlı cevaplar"></div>

    <div class="typing-wrap">
      <div id="typing" class="typing">
        <span>Yazıyor...</span>
        <span class="typing-dots"><span></span><span></span><span></span></span>
      </div>
    </div>

    <form id="composer" class="composer">
      <textarea id="msg" placeholder="Örnek: İstanbul’da devlet üniversitesinde hangi bölümlere yerleşebilirim?" rows="1"></textarea>
      <button id="micBtn" class="mic" type="button" aria-label="Mikrofonla yaz" title="Mikrofonla yaz">🎤</button>
      <button id="sendBtn" class="send" type="submit" aria-label="Mesajı gönder" title="Gönder">Gönder</button>
      <button id="resetBtn" class="reset" type="button" aria-label="Sohbeti temizle" title="Sohbeti temizle">Sıfırla</button>
    </form>
    <div id="composerHint" class="hint">Enter gönderir · Shift + Enter alt satıra geçer · 🎤 konuşmayı yazıya çevirir</div>
  </main>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/jspdf@4.2.1/dist/jspdf.umd.min.js" defer></script>
<script>
const messages = document.getElementById('messages');
const form = document.getElementById('composer');
const input = document.getElementById('msg');
const micBtn = document.getElementById('micBtn');
const sendBtn = document.getElementById('sendBtn');
const resetBtn = document.getElementById('resetBtn');
const composerHint = document.getElementById('composerHint');
const typing = document.getElementById('typing');
const SpeechRecognitionAPI = window.SpeechRecognition || window.webkitSpeechRecognition || null;
const SPEECH_RECOGNITION_SUPPORTED = !!SpeechRecognitionAPI;
let speechRecognition = null;
let speechRecognitionActive = false;
let speechRecognitionStarting = false;
let speechBaseText = '';
let speechRecognitionHadError = false;
let microphonePermissionState = 'prompt';
const DEFAULT_COMPOSER_HINT = 'Enter gönderir · Shift + Enter alt satıra geçer · 🎤 düğmesine basıp konuşun';
const MICROPHONE_READY_HINT = 'Sesli sormak istersen mikrofona tıkla kırmızı kayıt butonu geldikten sonra konuşmaya başla';
const quickReplies = document.getElementById('quickReplies');
const STUDENT_NAME = <?= json_encode($firstName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const STUDENT_FULL_NAME = <?= json_encode($name !== '' ? $name : $firstName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const AI_USAGE_MODE = <?= json_encode($aiKullanimModu, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const FREE_UNLIMITED_MODE = AI_USAGE_MODE === 'bedava';
let remainingPdfRights = <?= $remainingPdfRights ?>;
let currentPdfHasAccess = <?= $currentPdfHasAccess ? 'true' : 'false' ?>;
const AI_PAYMENT_URL = <?= json_encode($paymentUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const PDF_UPLOAD_URL = <?= json_encode($pdfUploadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const HAS_LOADED_PDF = <?= $hasLoadedPdf ? 'true' : 'false' ?>;
const PDF_PACKAGES = <?= json_encode($pdfPackages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const CURRENT_PDF_KEY = <?= json_encode($currentPdfKey, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const SERVER_UI_CHAT_HISTORY = <?= json_encode($uiChatHistory, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const SERVER_UI_CHAT_META = <?= json_encode($uiChatMeta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const SERVER_SHORT_CHAT_HISTORY = <?= json_encode($shortServerChatHistory, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const HAS_RESTORED_SERVER_CONTEXT = <?= $hasRestoredServerContext ? 'true' : 'false' ?>;
const OWNER_UNLIMITED_MODE = <?= $ownerUnlimited ? 'true' : 'false' ?>;
const ACTIVATION_CSRF = <?= json_encode((string)$_SESSION['paytr_activation_csrf'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const ACTIVATION_FLASH_ERROR = <?= json_encode($activationFlashError, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const PDF_SEARCH_PROFILES = <?= json_encode($pdfSearchProfiles, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const pdfAccessStatusText = document.getElementById('pdfAccessStatusText');

let uiChatHistory = Array.isArray(SERVER_UI_CHAT_HISTORY) ? SERVER_UI_CHAT_HISTORY.slice() : [];
let uiChatMeta = SERVER_UI_CHAT_META && typeof SERVER_UI_CHAT_META === 'object' ? {...SERVER_UI_CHAT_META} : {};
let restoringUiChat = false;
let chatSaveTimer = null;
let pendingMessageScrollFrame = 0;
let activeMobilePinnedResult = null;
let activeMobilePinUntil = 0;

if('scrollRestoration' in window.history){
  window.history.scrollRestoration = 'manual';
}


const MOBILE_CHAT_VIEWPORT = window.matchMedia('(max-width: 980px)');
function isMobileChatViewport(){
  return !!MOBILE_CHAT_VIEWPORT.matches;
}
function dismissMobileKeyboard(){
  if(!isMobileChatViewport()) return;
  try{
    if(input && typeof input.blur === 'function') input.blur();
    const active = document.activeElement;
    if(active && active !== document.body && typeof active.blur === 'function') active.blur();
  }catch(e){}
}
function focusComposerOnDesktop(){
  if(!isMobileChatViewport() && input && !input.disabled){
    input.focus();
  }
}

function cancelPendingMessageScroll(){
  if(pendingMessageScrollFrame){
    cancelAnimationFrame(pendingMessageScrollFrame);
    pendingMessageScrollFrame = 0;
  }
}

function scrollMessagesToTop(behavior = 'auto'){
  cancelPendingMessageScroll();
  pendingMessageScrollFrame = requestAnimationFrame(() => {
    pendingMessageScrollFrame = 0;
    messages.scrollTo({top:0, behavior});
  });
}

function alignMessageStartNow(element, behavior = 'auto'){
  if(!element || !element.isConnected) return;
  const messageRect = element.getBoundingClientRect();
  const containerRect = messages.getBoundingClientRect();
  const targetTop = messages.scrollTop + messageRect.top - containerRect.top - 2;
  messages.scrollTo({top:Math.max(0, targetTop), behavior});
}

function scrollMessageToStart(element, behavior = 'smooth'){
  if(!element || restoringUiChat) return;
  cancelPendingMessageScroll();
  pendingMessageScrollFrame = requestAnimationFrame(() => {
    pendingMessageScrollFrame = requestAnimationFrame(() => {
      pendingMessageScrollFrame = 0;
      alignMessageStartNow(element, behavior);
    });
  });
}

/*
 | Mobil tarayıcı klavyeyi kapatırken visual viewport birkaç kez yeniden boyutlanır.
 | Sonuç kartı da ilk satırlarını eklerken yüksekliği değişir. Bu nedenle liste başı
 | tek sefer değil, yerleşim tamamlanana kadar kısa aralıklarla yeniden sabitlenir.
 */
function pinResultMessageToTop(element){
  if(!element || restoringUiChat) return;

  if(!isMobileChatViewport()){
    scrollMessageToStart(element, 'smooth');
    return;
  }

  dismissMobileKeyboard();
  activeMobilePinnedResult = element;
  activeMobilePinUntil = performance.now() + 1900;
  cancelPendingMessageScroll();

  const align = () => {
    if(activeMobilePinnedResult !== element || performance.now() > activeMobilePinUntil) return;
    alignMessageStartNow(element, 'auto');
  };

  requestAnimationFrame(() => requestAnimationFrame(align));
  [60, 140, 260, 420, 650, 900, 1250, 1650].forEach(delay => {
    window.setTimeout(align, delay);
  });
}

if(window.visualViewport){
  window.visualViewport.addEventListener('resize', () => {
    if(!activeMobilePinnedResult || performance.now() > activeMobilePinUntil) return;
    requestAnimationFrame(() => alignMessageStartNow(activeMobilePinnedResult, 'auto'));
  }, {passive:true});
}

let lastHitap = '';
let lastUserQuestion = '';
let activePreferenceList = null;
let activeCriterion = '';
let initialChoiceMade = false;

function cleanUiEventForClient(event){
  if(!event || typeof event !== 'object') return null;

  if(event.type === 'message'){
    const text = String(event.text || '').trim();
    if(!text) return null;
    const one = {
      type:'message',
      role:event.role === 'user' ? 'user' : 'bot',
      text
    };
    if(event.criterion) one.criterion = String(event.criterion);
    return one;
  }

  if(event.type === 'result' && event.payload && typeof event.payload === 'object'){
    return {type:'result', payload:event.payload};
  }

  return null;
}

function recordUiEvent(event){
  if(restoringUiChat) return;
  const clean = cleanUiEventForClient(event);
  if(!clean) return;

  uiChatHistory.push(clean);
  if(uiChatHistory.length > 80) uiChatHistory = uiChatHistory.slice(-80);
  uiChatMeta.initial_choice_made = !!initialChoiceMade;
  uiChatMeta.active_criterion = String(activeCriterion || '');
  scheduleChatSave();
}

function scheduleChatSave(delay = 220){
  if(!CURRENT_PDF_KEY) return;
  if(chatSaveTimer) clearTimeout(chatSaveTimer);
  chatSaveTimer = setTimeout(()=>persistUiChat(false), delay);
}

async function persistUiChat(keepalive = false){
  if(!CURRENT_PDF_KEY) return false;

  if(chatSaveTimer){
    clearTimeout(chatSaveTimer);
    chatSaveTimer = null;
  }

  try{
    const response = await fetch('/ia-tercih-robotu/?chat_history=save', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      credentials:'same-origin',
      keepalive:!!keepalive,
      body:JSON.stringify({
        pdf_key:CURRENT_PDF_KEY,
        history:uiChatHistory,
        meta:{
          initial_choice_made:!!initialChoiceMade,
          active_criterion:String(activeCriterion || '')
        }
      })
    });
    return response.ok;
  }catch(error){
    return false;
  }
}

function fallbackHistoryFromServer(){
  if(uiChatHistory.length || !Array.isArray(SERVER_SHORT_CHAT_HISTORY)) return;

  uiChatHistory = SERVER_SHORT_CHAT_HISTORY.map(item=>{
    if(!item || typeof item !== 'object') return null;
    const text = String(item.content || '').trim();
    if(!text) return null;
    return {
      type:'message',
      role:item.role === 'user' ? 'user' : 'bot',
      text
    };
  }).filter(Boolean);
}

function restoreUiChatHistory(){
  fallbackHistoryFromServer();
  if(!Array.isArray(uiChatHistory) || !uiChatHistory.length) return false;

  restoringUiChat = true;
  messages.innerHTML = '';
  clearQuickReplies();
  activePreferenceList = null;

  let lastBotText = '';
  let lastType = '';
  let repairedRestoredGreeting = false;

  for(const event of uiChatHistory){
    if(!event || typeof event !== 'object') continue;

    if(event.type === 'message'){
      let restoredText = String(event.text || '');

      if(event.role !== 'user' && isCandidateInitialGreeting(restoredText)){
        const correctGreeting = firstQuestion();
        if(restoredText !== correctGreeting){
          restoredText = correctGreeting;
          event.text = correctGreeting;
          repairedRestoredGreeting = true;
        }
      }

      const row = addMsg(
        event.role === 'user' ? 'user' : 'bot',
        restoredText,
        true,
        event.role !== 'user' && event.whatsapp_support === true
      );

      if(event.role === 'user' && event.criterion){
        addAnswerEditLink(row, String(event.criterion));
      }
      if(event.role !== 'user') lastBotText = restoredText;
      lastType = 'message';
      continue;
    }

    if(event.type === 'result' && event.payload && typeof event.payload === 'object'){
      addResultCard(event.payload, true);
      lastBotText = '';
      lastType = 'result';
    }
  }

  restoringUiChat = false;
  messages.classList.remove('initial-question');

  initialChoiceMade = uiChatMeta.initial_choice_made !== false;
  if(uiChatHistory.some(event=>event && event.type === 'message' && event.role === 'user')){
    initialChoiceMade = true;
  }

  activeCriterion = String(uiChatMeta.active_criterion || '');
  setComposerLocked(!initialChoiceMade);

  if(lastType === 'message' && lastBotText){
    renderQuickReplies(lastBotText);
  }else{
    clearQuickReplies();
  }

  scrollMessagesToTop('auto');

  if(repairedRestoredGreeting){
    scheduleChatSave(60);
  }

  return true;
}

function normalizePdfSearch(value){
  return String(value || '')
    .toLocaleUpperCase('tr-TR')
    .replace(/İ/g, 'I')
    .replace(/İ/g, 'I')
    .replace(/Ş/g, 'S')
    .replace(/Ğ/g, 'G')
    .replace(/Ü/g, 'U')
    .replace(/Ö/g, 'O')
    .replace(/Ç/g, 'C')
    .replace(/\s+/g, ' ')
    .trim();
}

function maskTcknForDisplay(tckn){
  const digits = String(tckn || '').replace(/\D+/g, '');
  if(digits.length !== 11) return '';
  return 'T.C. •••••••' + digits.slice(-4);
}

function createPdfSearchLink(profile){
  const link = document.createElement('a');
  link.className = 'pdf-document-link' + (profile.active ? ' active' : '');
  link.href = '/ia-tercih-robotu/?pdf=' + encodeURIComponent(profile.pdf_key || '');
  link.title = String(profile.label || profile.name || 'Sonuç Belgesi');

  const name = document.createElement('span');
  name.className = 'pdf-document-name';
  name.textContent = (profile.active ? '✓ ' : '') + String(profile.label || profile.name || 'Sonuç Belgesi');
  link.appendChild(name);

  const metaParts = [];
  const maskedTckn = maskTcknForDisplay(profile.tckn);
  if(maskedTckn) metaParts.push(maskedTckn);
  if(profile.date) metaParts.push(String(profile.date));

  if(metaParts.length){
    const meta = document.createElement('span');
    meta.className = 'pdf-document-meta';
    meta.textContent = metaParts.join(' · ');
    link.appendChild(meta);
  }

  return link;
}

function setupPdfLibrarySearch(){
  const input = document.getElementById('pdfLibrarySearch');
  const clear = document.getElementById('pdfLibrarySearchClear');
  const recent = document.getElementById('recentPdfList');
  const results = document.getElementById('pdfSearchResults');

  if(!input || !clear || !recent || !results || !Array.isArray(PDF_SEARCH_PROFILES)) return;

  const render = ()=>{
    const raw = input.value.trim();
    const normalized = normalizePdfSearch(raw);
    const digitQuery = raw.replace(/\D+/g, '');

    clear.hidden = raw === '';

    if(raw === ''){
      recent.hidden = false;
      results.hidden = true;
      results.innerHTML = '';
      return;
    }

    recent.hidden = true;
    results.hidden = false;
    results.innerHTML = '';

    const matches = PDF_SEARCH_PROFILES.filter(profile=>{
      const nameHaystack = normalizePdfSearch(
        String(profile.name || '') + ' ' +
        String(profile.label || '') + ' ' +
        String(profile.original_name || '')
      );
      const tckn = String(profile.tckn || '').replace(/\D+/g, '');

      const nameMatch = normalized !== '' && nameHaystack.includes(normalized);
      const tcMatch = digitQuery.length >= 3 && tckn.includes(digitQuery);
      return nameMatch || tcMatch;
    });

    const status = document.createElement('div');
    status.className = 'pdf-search-status';
    status.textContent = matches.length
      ? matches.length + ' sonuç bulundu'
      : 'Sonuç bulunamadı';
    results.appendChild(status);

    if(!matches.length){
      const empty = document.createElement('div');
      empty.className = 'pdf-search-empty';
      empty.textContent = 'Bu ad soyad veya T.C. kimlik numarasıyla kayıtlı sonuç belgesi bulunamadı.';
      results.appendChild(empty);
      return;
    }

    matches.slice(0, 20).forEach(profile=>{
      results.appendChild(createPdfSearchLink(profile));
    });

    if(matches.length > 20){
      const more = document.createElement('div');
      more.className = 'pdf-search-status';
      more.textContent = 'İlk 20 sonuç gösteriliyor. Aramayı biraz daha ayrıntılı yazabilirsiniz.';
      results.appendChild(more);
    }
  };

  input.addEventListener('input', render);

  clear.addEventListener('click', ()=>{
    input.value = '';
    render();
    input.focus();
  });

  input.addEventListener('keydown', event=>{
    if(event.key === 'Escape'){
      input.value = '';
      render();
      input.blur();
    }
  });
}

setupPdfLibrarySearch();

document.addEventListener('click', async event=>{
  const link = event.target.closest('.pdf-document-link');
  if(!link || link.classList.contains('active')) return;
  if(event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;

  event.preventDefault();
  await persistUiChat(true);
  window.location.href = link.href;
});

window.addEventListener('pagehide', ()=>persistUiChat(true));

function isInitialChoiceText(text){
  const t = String(text || '').trim();
  return t === 'Hazır adımları kullanacağım' || t === 'Soru soracağım';
}

function setComposerLocked(locked){
  const isLocked = !!locked;
  form.classList.toggle('is-locked', isLocked);
  input.disabled = isLocked;
  sendBtn.disabled = isLocked;
  micBtn.disabled = isLocked || !SPEECH_RECOGNITION_SUPPORTED;
  input.setAttribute('aria-disabled', isLocked ? 'true' : 'false');
  sendBtn.setAttribute('aria-disabled', isLocked ? 'true' : 'false');
  micBtn.setAttribute('aria-disabled', micBtn.disabled ? 'true' : 'false');
  input.placeholder = isLocked
    ? 'Devam etmek için yukarıdaki iki seçenekten birini seçin.'
    : 'Örnek: İstanbul’da devlet üniversitesinde hangi bölümlere yerleşebilirim?';
}

function currentComposerHint(){
  return microphonePermissionState === 'granted' ? MICROPHONE_READY_HINT : DEFAULT_COMPOSER_HINT;
}

function setComposerHint(text){
  if(composerHint) composerHint.textContent = text || currentComposerHint();
}

async function refreshMicrophonePermissionState(){
  if(!navigator.permissions || typeof navigator.permissions.query !== 'function') return;
  try{
    const permission = await navigator.permissions.query({name:'microphone'});
    microphonePermissionState = String(permission.state || 'prompt');
    permission.onchange = () => {
      microphonePermissionState = String(permission.state || 'prompt');
      if(!speechRecognitionActive && !speechRecognitionStarting){
        setComposerHint(currentComposerHint());
      }
    };
    if(!speechRecognitionActive && !speechRecognitionStarting){
      setComposerHint(currentComposerHint());
    }
  }catch(error){
    // Bazı tarayıcılar microphone izin sorgusunu desteklemez; getUserMedia ile devam edilir.
  }
}

async function ensureMicrophoneAccess(){
  if(!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia !== 'function'){
    return true;
  }

  let stream = null;
  try{
    stream = await navigator.mediaDevices.getUserMedia({
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        autoGainControl: true
      }
    });
    microphonePermissionState = 'granted';
    return true;
  }catch(error){
    const errorName = String(error?.name || '');
    if(errorName === 'NotAllowedError' || errorName === 'SecurityError'){
      microphonePermissionState = 'denied';
      setComposerHint('Mikrofon izni engellendi. Adres çubuğundaki kilit simgesinden mikrofonu İzin ver yapın.');
    }else if(errorName === 'NotFoundError' || errorName === 'DevicesNotFoundError'){
      setComposerHint('Bilgisayarda kullanılabilir mikrofon bulunamadı. Windows ses giriş aygıtını kontrol edin.');
    }else if(errorName === 'NotReadableError' || errorName === 'TrackStartError'){
      setComposerHint('Mikrofon başka bir uygulama tarafından kullanılıyor olabilir. Diğer uygulamaları kapatıp tekrar deneyin.');
    }else{
      setComposerHint('Mikrofona erişilemedi. Chrome ve Windows mikrofon ayarlarını kontrol edin.');
    }
    return false;
  }finally{
    if(stream){
      stream.getTracks().forEach(track => track.stop());
    }
  }
}

function resizeComposerInput(){
  input.style.height = 'auto';
  input.style.height = Math.min(input.scrollHeight, 170) + 'px';
}

function setSpeechRecognitionActive(active){
  speechRecognitionActive = !!active;
  micBtn.classList.toggle('listening', speechRecognitionActive);
  micBtn.setAttribute('aria-pressed', speechRecognitionActive ? 'true' : 'false');
  micBtn.setAttribute('aria-label', speechRecognitionActive ? 'Dinlemeyi durdur' : 'Mikrofonla yaz');
  micBtn.title = speechRecognitionActive ? 'Dinlemeyi durdur' : 'Mikrofonla yaz';
  micBtn.textContent = speechRecognitionActive ? '■' : '🎤';
  if(speechRecognitionActive) setComposerHint('Dinliyorum… Konuşmanız yazı alanına aktarılıyor.');
  else setComposerHint(currentComposerHint());
}

function speechRecognitionErrorMessage(errorCode){
  switch(String(errorCode || '')){
    case 'not-allowed':
    case 'service-not-allowed':
      return 'Mikrofon izni verilmedi. Tarayıcı adres çubuğundan mikrofon iznini açın.';
    case 'no-speech':
      return 'Ses algılanmadı. Mikrofon düğmesine basıp tekrar konuşun.';
    case 'audio-capture':
      return 'Mikrofona erişilemedi. Cihazın mikrofon ayarlarını kontrol edin.';
    case 'network':
      return 'Ses tanıma bağlantısı kurulamadı. İnternet bağlantısını kontrol edin.';
    default:
      return 'Konuşma yazıya çevrilemedi. Tekrar deneyin.';
  }
}

if(SPEECH_RECOGNITION_SUPPORTED){
  speechRecognition = new SpeechRecognitionAPI();
  speechRecognition.lang = 'tr-TR';
  speechRecognition.continuous = false;
  speechRecognition.interimResults = true;
  speechRecognition.maxAlternatives = 1;

  speechRecognition.onstart = () => {
    speechRecognitionStarting = false;
    micBtn.disabled = false;
    speechRecognitionHadError = false;
    speechBaseText = input.value.trim();
    setSpeechRecognitionActive(true);
  };

  speechRecognition.onresult = (event) => {
    let spokenText = '';
    for(let i = 0; i < event.results.length; i++){
      spokenText += String(event.results[i][0]?.transcript || '');
    }
    spokenText = spokenText.trim();
    input.value = [speechBaseText, spokenText].filter(Boolean).join(speechBaseText && spokenText ? ' ' : '');
    resizeComposerInput();
    input.focus();
  };

  speechRecognition.onerror = (event) => {
    speechRecognitionStarting = false;
    micBtn.disabled = !initialChoiceMade || !SPEECH_RECOGNITION_SUPPORTED;
    speechRecognitionHadError = true;
    setSpeechRecognitionActive(false);
    setComposerHint(speechRecognitionErrorMessage(event.error));
    window.setTimeout(() => setComposerHint(currentComposerHint()), 4500);
  };

  speechRecognition.onend = () => {
    speechRecognitionStarting = false;
    micBtn.disabled = !initialChoiceMade || !SPEECH_RECOGNITION_SUPPORTED;
    speechRecognitionActive = false;
    micBtn.classList.remove('listening');
    micBtn.setAttribute('aria-pressed', 'false');
    micBtn.setAttribute('aria-label', 'Mikrofonla yaz');
    micBtn.title = 'Mikrofonla yaz';
    micBtn.textContent = '🎤';
    if(!speechRecognitionHadError) setComposerHint(currentComposerHint());
    input.focus();
  };
}else{
  micBtn.disabled = true;
  micBtn.title = 'Bu tarayıcı konuşmayı yazıya çevirme özelliğini desteklemiyor.';
  micBtn.setAttribute('aria-label', micBtn.title);
}

micBtn.addEventListener('click', async () => {
  if(micBtn.disabled || !speechRecognition || speechRecognitionStarting) return;

  if(speechRecognitionActive){
    speechRecognition.stop();
    return;
  }

  speechRecognitionStarting = true;
  micBtn.disabled = true;
  setComposerHint('Mikrofon hazırlanıyor…');

  const accessGranted = await ensureMicrophoneAccess();
  if(!accessGranted){
    speechRecognitionStarting = false;
    micBtn.disabled = !initialChoiceMade || !SPEECH_RECOGNITION_SUPPORTED;
    window.setTimeout(() => {
      if(microphonePermissionState !== 'denied') setComposerHint(currentComposerHint());
    }, 5000);
    return;
  }

  setComposerHint('Dinleme başlatılıyor…');
  try{
    speechRecognition.start();
  }catch(error){
    speechRecognitionStarting = false;
    micBtn.disabled = !initialChoiceMade || !SPEECH_RECOGNITION_SUPPORTED;
    setSpeechRecognitionActive(false);
    setComposerHint('Mikrofon başlatılamadı. Sayfayı yenileyip tekrar deneyin.');
    window.setTimeout(() => setComposerHint(currentComposerHint()), 4000);
  }
});

refreshMicrophonePermissionState();

const RISK_WARNING = 'SARIYLA RENKLENDİRİLEN BÖLÜMLER YERLEŞMENİZİN RİSKLİ OLDUĞU BÖLÜMLERDİR. ANCAK ÇOK İSTİYORSANIZ TERCİH LİSTENİZE YAZMANIZDA YARAR VARDIR. SIRALAMAYI DEĞİŞTİRMEK İSTERSENİZ TERCİH ROBOTU\'NUN SİZİN VERİLERİNİZE EN UYGUN SIRALAMAYLA LİSTENİZİ OLUŞTURDUĞUNU UNUTMAYINIZ.';
const SOURCE_WARNING = 'Tüm veriler ÖSYM ve YÖK kaynaklıdır. Tercihlerinizi ÖSYM’ye bildirirken bölüm kodlarını kontrol etmeyi unutmayın.';

function pickHitap(){
  const n = String(STUDENT_NAME || '').trim();
  if(n && !['sayın aday','sayın aday','sayın aday','arkadasim','aday'].includes(n.toLocaleLowerCase('tr-TR'))){
    return n;
  }
  return 'Sayın aday';
}

function isCandidateInitialGreeting(text){
  const normalized = normalizeTR(String(text || ''));
  return normalized.includes('SONUC BELGENE GORE SORDUGUN SORULARA CEVAP VEREREK EN DOGRU TERCIHI YAPMANA YARDIMCI OLABILIRIM')
    && normalized.includes('NE YAPMAK ISTERSIN');
}

function varyHitap(text){
  let t = String(text || '').trim();
  const h = pickHitap();

  /*
   | Daha önce yanlış PDF bağlamına kaydedilmiş başlangıç mesajında başka
   | aday adı bulunabilir. Bu özel mesaj her zaman aktif aday için yeniden
   | oluşturulur; "ALİ, ZEYNEP, ..." birleşmesi oluşmaz.
   */
  if(isCandidateInitialGreeting(t)){
    return firstQuestion();
  }

  // API cevapları çoğu zaman "SILA," diye başlıyor. Başındaki hitabı değiştir.
  const names = [STUDENT_NAME, 'Sayın aday', 'sayın aday', 'sayın aday', 'Sayın aday', 'sayın aday', 'Sayın aday', 'sayın aday', 'Sayın aday', 'arkadasim', 'Arkadasim']
    .filter(Boolean)
    .map(x => String(x).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));

  if(names.length){
    const re = new RegExp('^\\s*(?:' + names.join('|') + ')\\s*,', 'iu');
    if(re.test(t)) return t.replace(re, h + ',');
  }

  return `${h}, ${t}`;
}

function firstQuestion(){
  return `${pickHitap()}, sonuç belgene göre sorduğun sorulara cevap vererek en doğru tercihi yapmana yardımcı olabilirim.

İstersen mevcut filtreleri adım adım da kullanabilirsin.

Ne yapmak istersin?`;
}

function sleep(ms){ return new Promise(resolve => setTimeout(resolve, ms)); }
function minDelay(){ return 1700 + Math.floor(Math.random() * 1100); }
function escapeHtml(s){return String(s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));}

function paymentCandidateLabel(){
  const n = String(STUDENT_NAME || '').trim();
  if(!n || n.toLocaleLowerCase('tr-TR') === 'sayın aday') return 'Sayın aday';
  return `Sayın ${n}`;
}

function hasCurrentPdfAccess(){
  return FREE_UNLIMITED_MODE || currentPdfHasAccess === true;
}

function updatePdfAccessStatus(){
  if(!pdfAccessStatusText) return;
  if(OWNER_UNLIMITED_MODE){
    pdfAccessStatusText.textContent = 'Yönetici test erişimi · Sınırsız PDF';
    return;
  }
  if(FREE_UNLIMITED_MODE){
    pdfAccessStatusText.textContent = 'Ücretsiz test modu · Sınırsız kullanım';
    return;
  }
  if(hasCurrentPdfAccess()){
    pdfAccessStatusText.textContent = `Bu sonuç belgesi aktif · Kalan yeni PDF hakkı: ${remainingPdfRights}`;
  }else if(remainingPdfRights > 0){
    pdfAccessStatusText.textContent = `PDF yükleme hakkınız: ${remainingPdfRights} · Sonuç belgesi bekleniyor`;
  }else{
    pdfAccessStatusText.textContent = 'Sonuç belgesi paketi gerekli';
  }
}

function addPaymentRequiredMsg(){
  const row = document.createElement('div');
  row.className = 'msg-row bot-row';

  const av = document.createElement('div');
  av.className = 'mini-avatar';
  const avImg = document.createElement('img');
  avImg.src = '/robot.png';
  avImg.alt = 'Robot';
  av.appendChild(avImg);
  row.appendChild(av);

  const card = document.createElement('div');
  card.className = 'msg bot payment-required-card';

  const title = document.createElement('div');
  title.className = 'payment-required-title';

  const text = document.createElement('div');
  text.className = 'payment-required-text';

  const link = document.createElement('a');
  link.className = 'payment-required-button';

  if(remainingPdfRights > 0){
    title.textContent = '📄 Sonuç Belgenizi Yükleyiniz';
    text.textContent = `${paymentCandidateLabel()}, ${remainingPdfRights} adet Sonuç Belgesi yükleme hakkınız var. Yapay Zeka Tercih Robotunu kullanmak için önce ÖSYM Sonuç Belgenizi yükleyin. Yüklediğiniz belge üzerinde sınırsız soru sorabilir ve tercih listesi hazırlayabilirsiniz.`;
    link.href = PDF_UPLOAD_URL;
    link.textContent = 'PDF Yükleme Alanına Git';
    link.setAttribute('aria-label', 'ÖSYM Sonuç Belgesi PDF yükleme alanına git');
  }else{
    title.textContent = '🔒 Kullanım Hakkı Alınız';
    text.textContent = `${paymentCandidateLabel()}, Yapay Zeka Tercih Robotunu kullanabilmeniz için önce Sonuç Belgesi paketi satın almalı, ardından PDF belgenizi yüklemelisiniz. Satın aldığınız her Sonuç Belgesi üzerinde sınırsız soru sorabilir ve tercih listesi hazırlayabilirsiniz.`;
    link.href = AI_PAYMENT_URL;
    link.textContent = 'Sonuç Belgesi Satın Al';
    link.setAttribute('aria-label', 'Yapay Zeka Tercih Robotu Sonuç Belgesi paketi satın al');
  }

  card.appendChild(title);
  card.appendChild(text);
  card.appendChild(link);

  if(!OWNER_UNLIMITED_MODE){
    const activationBox = document.createElement('div');
    activationBox.className = 'activation-login-box';

    const activationTitle = document.createElement('div');
    activationTitle.className = 'activation-login-title';
    activationTitle.textContent = 'Başka cihazda aldığınız hakkı kullanın';

    const activationForm = document.createElement('form');
    activationForm.className = 'activation-login-form';
    activationForm.method = 'post';
    activationForm.action = '/ia-tercih-robotu/';

    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = 'activation_action';
    actionInput.value = 'login';

    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'activation_csrf';
    csrfInput.value = ACTIVATION_CSRF;

    const codeInput = document.createElement('input');
    codeInput.className = 'activation-code-input';
    codeInput.type = 'text';
    codeInput.name = 'activation_code';
    codeInput.placeholder = 'TR26-XXXX-XXXX-XXXX-XXXX';
    codeInput.autocomplete = 'one-time-code';
    codeInput.maxLength = 32;
    codeInput.required = true;

    const loginButton = document.createElement('button');
    loginButton.className = 'activation-login-button';
    loginButton.type = 'submit';
    loginButton.textContent = 'Aktivasyon Kodu ile Giriş Yap';

    activationForm.appendChild(actionInput);
    activationForm.appendChild(csrfInput);
    activationForm.appendChild(codeInput);
    activationForm.appendChild(loginButton);

    activationBox.appendChild(activationTitle);
    activationBox.appendChild(activationForm);

    const help = document.createElement('div');
    help.className = 'activation-login-help';
    help.textContent = 'Doğru kodla giriş yaptığınızda kalan PDF haklarınız, yüklediğiniz belgeler ve geçmiş sohbetleriniz bu cihazda açılır.';
    activationBox.appendChild(help);

    if(ACTIVATION_FLASH_ERROR){
      const errorBox = document.createElement('div');
      errorBox.className = 'activation-login-error';
      errorBox.textContent = ACTIVATION_FLASH_ERROR;
      activationBox.appendChild(errorBox);
    }

    card.appendChild(activationBox);
  }

  row.appendChild(card);
  messages.appendChild(row);
  scrollMessageToStart(row, 'auto');
  return row;
}

function renderMarkdown(s){
  let html = escapeHtml(s);
  html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" loading="lazy">');
  html = html.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');
  return html;
}
function appendWhatsappSupport(messageElement){
  if(!messageElement || messageElement.querySelector('.whatsapp-support')) return;

  const support = document.createElement('div');
  support.className = 'whatsapp-support';

  const prefix = document.createElement('span');
  prefix.textContent = 'Eğer sorduğun sorunun cevabından emin değilsen';

  const link = document.createElement('a');
  link.className = 'whatsapp-support-link';
  link.href = 'https://wa.me/905368955095';
  link.target = '_blank';
  link.rel = 'noopener noreferrer';
  link.setAttribute('aria-label', 'WhatsApp hattımızdan bize ulaşın');
  link.innerHTML = `
    <svg viewBox="0 0 32 32" aria-hidden="true" focusable="false">
      <path d="M19.11 17.21c-.42-.21-2.47-1.22-2.85-1.36-.38-.14-.66-.21-.94.21-.28.42-1.08 1.36-1.33 1.64-.24.28-.49.31-.91.1-.42-.21-1.77-.65-3.37-2.08-1.24-1.11-2.08-2.48-2.32-2.9-.24-.42-.03-.65.18-.86.19-.19.42-.49.63-.73.21-.24.28-.42.42-.7.14-.28.07-.52-.03-.73-.1-.21-.94-2.26-1.29-3.1-.34-.82-.68-.71-.94-.72h-.8c-.28 0-.73.1-1.12.52-.38.42-1.46 1.43-1.46 3.48s1.5 4.03 1.7 4.31c.21.28 2.94 4.49 7.12 6.3.99.43 1.77.69 2.38.88 1 .32 1.91.27 2.63.16.8-.12 2.47-1.01 2.82-1.98.35-.98.35-1.81.24-1.98-.1-.17-.38-.28-.8-.49z"/>
      <path d="M16.04 2.67c-7.34 0-13.3 5.95-13.3 13.29 0 2.34.61 4.64 1.76 6.66L2.63 29.5l7.04-1.85a13.23 13.23 0 0 0 6.36 1.62h.01c7.33 0 13.3-5.96 13.3-13.3 0-3.55-1.38-6.89-3.89-9.4a13.2 13.2 0 0 0-9.41-3.9zm0 24.35h-.01a11 11 0 0 1-5.61-1.54l-.4-.24-4.18 1.1 1.12-4.07-.26-.42a11.02 11.02 0 0 1-1.7-5.88c0-6.08 4.96-11.04 11.05-11.04a10.97 10.97 0 0 1 7.81 3.24 10.98 10.98 0 0 1 3.23 7.81c0 6.09-4.96 11.04-11.05 11.04z"/>
    </svg>
    <span>WhatsApp hattımızdan bize ulaşın</span>
  `;

  support.appendChild(prefix);
  support.appendChild(link);
  messageElement.appendChild(support);
}

function addMsg(role, text, skipRecord = false, showWhatsappSupport = false){
  const row = document.createElement('div');
  row.className = 'msg-row ' + (role === 'user' ? 'user-row' : 'bot-row');

  if(role !== 'user'){
    const av = document.createElement('div');
    av.className = 'mini-avatar';
    const avImg = document.createElement('img');
    avImg.src = '/robot.png';
    avImg.alt = 'Robot';
    av.appendChild(avImg);
    row.appendChild(av);
  }

  if(role !== 'user') {
    text = String(text || '')
      .replace(/seçilmemiş gibi devam eder\.?/gi, '')
      .replace(/Bence\s+\*{0,2}Puana göre\*{0,2}\s+daha net sonuç verir\s*😉?/gi, 'Tabii ki **Başarı sırasına göre** daha net sonuçlar verir.')
      .trim();

    // Kontenjan adımındaki metin API'den "Kontenjanlar filtresi ne olsun?"
    // veya eski sürümlerde "Özel kontenjanlar filtresi ne olsun?" olarak gelebilir.
    // Her iki durumda da ekranda yalnızca kurumsal açıklama gösterilir.
    const quotaNorm = normalizeTR(text);
    const quotaQuestion = /(?:^|\n)\s*(?:[^,\n]{1,60},\s*)?(?:OZEL\s+)?KONTENJANLAR?\s+FILTRESI\s+NE\s+OLSUN\??/iu;
    if(quotaQuestion.test(quotaNorm)){
      text = `${pickHitap()}, Özel Kontenjanlardan yararlanıyorsan bu filtrelerden seçim yapabilirsin.`;
    }else{
      text = varyHitap(text);
    }
  }

  const div = document.createElement('div');
  div.className = 'msg ' + (role === 'user' ? 'user' : 'bot');
  div.innerHTML = renderMarkdown(text);

  if(role !== 'user' && showWhatsappSupport){
    appendWhatsappSupport(div);
  }

  if(role === 'user'){
    const stack = document.createElement('div');
    stack.className = 'user-message-stack';
    stack.appendChild(div);
    row.appendChild(stack);
    row._messageStack = stack;
  }else{
    row.appendChild(div);
  }

  messages.appendChild(row);
  if(!skipRecord) scrollMessageToStart(row);

  if(!skipRecord){
    recordUiEvent({
      type:'message',
      role:role === 'user' ? 'user' : 'bot',
      text:String(text || ''),
      whatsapp_support:role !== 'user' && !!showWhatsappSupport
    });
  }

  return row;
}

function addAnswerEditLink(userRow, criterion){
  const key = criterion === 'burs_istegi' ? 'burslar' : String(criterion || '');
  const editable = new Set(['tercih_turu','universite_turu','sehirler','tercih_gosterim','yeni_programlar','ogretim_turleri','ogrenim_ucreti','burslar','kontenjanlar','puan_turleri','bolum_ara']);
  if(!userRow || !userRow._messageStack || !editable.has(key)) return;

  const btn = document.createElement('button');
  btn.type = 'button';
  btn.className = 'answer-edit-inline';
  btn.dataset.criterion = key;
  btn.textContent = 'Düzenle';
  userRow._messageStack.appendChild(btn);

  if(!restoringUiChat){
    for(let i = uiChatHistory.length - 1; i >= 0; i--){
      const event = uiChatHistory[i];
      if(event && event.type === 'message' && event.role === 'user'){
        event.criterion = key;
        scheduleChatSave();
        break;
      }
    }
  }
}
function setTyping(on){
  const visible = !!on;
  typing.classList.toggle('show', visible);
  const wrap = typing.closest('.typing-wrap');
  if(wrap) wrap.classList.toggle('show', visible);
}
function clearQuickReplies(){
  if(quickReplies) quickReplies.innerHTML = '';
}
function normalizeTR(s){
  return String(s||'')
    .toLocaleUpperCase('tr-TR')
    .replaceAll('İ','I').replaceAll('Ş','S').replaceAll('Ğ','G')
    .replaceAll('Ü','U').replaceAll('Ö','O').replaceAll('Ç','C');
}
function quickConfigFor(reply){
  const r = normalizeTR(reply);
  if((r.includes('SORULARA CEVAP') || r.includes('MEVCUT FILTRELERI') || r.includes('HAZIR ADIMLARI')) && r.includes('NE YAPMAK ISTERSIN')){
    return {mode:'single', options:['Hazır adımları kullanacağım', 'Soru soracağım'], criterion:''};
  }
  // Tek seçim olması gerekenler
  if(r.includes('SONUC GOSTERIM') || r.includes('SONUÇ GÖSTERIM') || r.includes('TERCIH TURU / GOSTERIM') || r.includes('TERCIH TÜRÜ / GÖSTERIM') || r.includes('PUANA GORE MI') || r.includes('BASARI SIRASINA')){
    return {mode:'single', options:['Başarı sırasına göre', 'Puana göre'], criterion:'tercih_gosterim'};
  }
  if(r.includes('YENI ACILAN') || r.includes('YENI PROGRAM')){
    return {mode:'single', options:['Gösterme', 'Göster', 'Sadece yeni'], criterion:'yeni_programlar'};
  }
  if(r.includes('BELIRLI BIR BOLUM') || r.includes('BOLUM ISTIYOR')){
    return {mode:'single', options:['Hepsini listele', 'Psikoloji', 'Hukuk', 'Bilgisayar', 'Tıp'], criterion:'bolum_ara'};
  }

  // Çoklu seçim destekleyenler
  if(r.includes('TERCIH TURU') || r.includes('TERCIH TÜRÜ') || r.includes('LISANS MI')){
    return {mode:'multi', options:['Lisans', 'Önlisans', 'İkisi de'], exclusive:['İkisi de'], done:'Seçilenleri gönder', criterion:'tercih_turu'};
  }
  if(r.includes('UNIVERSITE TURU')){
    return {mode:'multi', options:['Devlet', 'Vakıf', 'KKTC', 'Yurtdışı', 'Tümü'], exclusive:['Tümü'], done:'Seçilenleri gönder', criterion:'universite_turu'};
  }
  if(r.includes('HANGI SEHIR') || r.includes('SEHIRLER') || r.includes('BOLGELER')){
    return {mode:'multi', options:['İstanbul', 'Ankara', 'İzmir', 'Tüm Türkiye'], exclusive:['Tüm Türkiye'], done:'Seçilenleri gönder', criterion:'sehirler'};
  }
  if(r.includes('OGRETIM TUR')){
    return {mode:'multi', options:['Normal Öğretim', 'Açık Öğretim', 'Uzaktan Eğitim', 'Fark etmez'], exclusive:['Fark etmez'], done:'Seçilenleri gönder', criterion:'ogretim_turleri'};
  }
  if(r.includes('OGRENIM UCRETI') || r.includes('ÖGRENIM ÜCRETI') || r.includes('ÜCRET FILTRESI') || r.includes('UCRET FILTRESI')){
    return {mode:'multi', options:['Ücretsiz', 'Ücretli', 'Fark etmez'], exclusive:['Fark etmez'], done:'Seçilenleri gönder', criterion:'ogrenim_ucreti'};
  }
  if(r.includes('BURSLU BOLUM SECMEK ISTER MISIN')){
    return {mode:'single', options:['Evet', 'Hayır'], criterion:'burslar'};
  }
  if(r.includes('BURSLAR') || r.includes('BURS FILTRESI')){
    return {mode:'multi', options:['Tam burslu', '%75 burslu', '%50 burslu', '%25 burslu'], exclusive:[], done:'Seçilenleri gönder', criterion:'burslar'};
  }
  if(r.includes('KONTENJANLAR') || r.includes('KONTENJAN FILTRESI')){
    return {mode:'multi', options:['Hiçbiri', 'Okul Birincisi', 'MEBB', 'Şehit ve Gazi Yak.', '34 Yaş Üstü Kadın', 'Depremzede'], exclusive:['Hiçbiri'], done:'Seçilenleri gönder', criterion:'kontenjanlar'};
  }
  if(r.includes('PUAN TURU') || r.includes('PUAN TURLERI') || r.includes('PUAN TURLERİ')){
    return {mode:'multi', options:['Tümü', 'TYT', 'SAY', 'EA', 'SÖZ', 'DİL'], exclusive:['Tümü'], done:'Seçilenleri gönder', criterion:'puan_turleri'};
  }
  return {mode:'none', options:[], criterion:''};
}
function renderQuickReplies(reply){
  if(!quickReplies) return;
  clearQuickReplies();
  const cfg = quickConfigFor(reply);
  activeCriterion = (cfg && cfg.criterion) ? String(cfg.criterion) : '';
  const opts = (cfg && Array.isArray(cfg.options)) ? cfg.options : [];
  if(!opts.length) return;

  if(cfg.mode === 'single'){
    opts.forEach(text => {
      const b = document.createElement('button');
      b.type = 'button';
      b.className = 'quick-btn';
      b.textContent = text;
      b.addEventListener('click', () => sendMessage(text));
      quickReplies.appendChild(b);
    });
    return;
  }

  const selected = new Set();
  const exclusive = new Set(cfg.exclusive || []);
  const buttons = [];
  const refresh = () => {
    buttons.forEach(b => b.classList.toggle('selected', selected.has(b.dataset.value)));
    done.disabled = selected.size === 0;
  };

  opts.forEach(text => {
    const b = document.createElement('button');
    b.type = 'button';
    b.className = 'quick-btn';
    b.textContent = text;
    b.dataset.value = text;
    b.addEventListener('click', () => {
      if(exclusive.has(text)){
        selected.clear();
        selected.add(text);
      }else{
        exclusive.forEach(x => selected.delete(x));
        selected.has(text) ? selected.delete(text) : selected.add(text);
      }
      refresh();
    });
    buttons.push(b);
    quickReplies.appendChild(b);
  });

  const done = document.createElement('button');
  done.type = 'button';
  done.className = 'quick-btn quick-done';
  done.textContent = cfg.done || 'Devam et';
  done.disabled = true;
  done.addEventListener('click', () => {
    const text = Array.from(selected).join(', ');
    if(text) sendMessage(text);
  });
  quickReplies.appendChild(done);
  refresh();
}
function fmtNum(v){
  const n = Number(v || 0);
  if(!Number.isFinite(n) || n <= 0) return 'YOK';
  return Math.round(n).toLocaleString('tr-TR');
}
function fmtScore(v){
  const n = Number(v || 0);
  if(!Number.isFinite(n) || n <= 0) return 'YOK';
  return n.toLocaleString('tr-TR', {minimumFractionDigits:3, maximumFractionDigits:3});
}
function aiTruthyFlag(value){
  if(value === true || value === 1) return true;
  const normalized = String(value ?? '').trim().toLowerCase();
  return ['1','true','evet','yes','yeni'].includes(normalized);
}
function isNewProgram(program){
  if(!program || typeof program !== 'object') return false;

  // API sonucu session/veritabanından geri geldiğinde boolean alanlar bazen
  // true yerine 1 veya "1" olabilir. Hepsini yeni program işareti say.
  if(aiTruthyFlag(program.yeni_program) || aiTruthyFlag(program.is_new_program)) return true;

  const score = Number(program.taban_puan ?? program.TabanPuan ?? 0);
  const rawTbs = Number(
    program.tbs_ham
    ?? program.tbs_raw
    ?? program.kullanilan_program_sira_ham
    ?? program.kullanilan_program_sira_raw
    ?? program.TBS
    ?? program.tbs
    ?? 0
  );
  const tbsYok = aiTruthyFlag(program.tbs_yok)
    || aiTruthyFlag(program.kullanilan_program_sira_yok)
    || (Number.isFinite(rawTbs) && rawTbs >= 10000000);

  return Number.isFinite(score) && score === 0 && tbsYok;
}
function programTabanPuan(program){
  const serverText = String(program?.taban_puan_gosterim ?? '').trim();
  if(serverText && normalizeTR(serverText) === 'YENİ') return 'YENİ';
  if(isNewProgram(program)) return 'YENİ';
  return fmtScore(program && (program.taban_puan ?? program.TabanPuan));
}
function deriveListTitle(question, filters, reply){
  const joined = normalizeTR(`${question||''} ${(filters&&filters.bolum_exact)||''} ${(filters&&filters.bolum_ara)||''} ${reply||''}`);
  if(/GARANTI|GUVENLI|KESIN/.test(joined)) return 'GARANTİLİ TERCİH LİSTEN';
  if(/OGRETMEN/.test(joined)) return 'ÖĞRETMENLİK TERCİHLERİN';
  const rawDept = String((filters && (filters.bolum_exact || filters.bolum_ara)) || '').trim();
  if(rawDept && !/HEPSI|TUMU|LISTELE/i.test(normalizeTR(rawDept))){
    return `${rawDept.toLocaleUpperCase('tr-TR')} TERCİHLERİN`;
  }
  return 'TERCİH LİSTEN';
}

function riskClassOf(program){
  const p = Number(program && program.kullanilan_program_sira || 0);
  const a = Number(program && program.kullanilan_aday_sira || 0);
  if(!(p > 0 && a > 0)) return 'unknown-gray';
  if(p < a) return 'risk-yellow';
  if(p >= a * 1.20) return 'safe-green';
  return 'balanced-blue';
}

function safeFilePart(value){
  return String(value || 'TERCIH_LISTEN')
    .toLocaleUpperCase('tr-TR')
    .replace(/[İI]/g,'I').replace(/[Ş]/g,'S').replace(/[Ğ]/g,'G').replace(/[Ü]/g,'U').replace(/[Ö]/g,'O').replace(/[Ç]/g,'C')
    .replace(/[^A-Z0-9]+/g,'_').replace(/^_+|_+$/g,'').slice(0,90) || 'TERCIH_LISTEN';
}

function uniquePdfFilename(title){
  const base = safeFilePart(title);
  const key = `tercih_pdf_version_${base}`;
  let version = Number(localStorage.getItem(key) || 0) + 1;
  localStorage.setItem(key, String(version));
  const d = new Date();
  const stamp = `${d.getFullYear()}${String(d.getMonth()+1).padStart(2,'0')}${String(d.getDate()).padStart(2,'0')}_${String(d.getHours()).padStart(2,'0')}${String(d.getMinutes()).padStart(2,'0')}${String(d.getSeconds()).padStart(2,'0')}`;
  return {filename:`${base}_v${version}_${stamp}.pdf`, version};
}

function pdfTabanPuan(program){
  const raw = String((program && (program.taban_puan_raw ?? program.TabanPuanRaw)) ?? '').trim();
  if(raw && /^-2/.test(raw)) return 'DOLMADI';
  if(raw && /^-1/.test(raw)) return 'Y.P.TÜR';
  if(isNewProgram(program)) return 'Yeni';
  const n = Number(program && program.taban_puan || 0);
  if(Number.isFinite(n) && n > 0) return fmtScore(n);
  return 'YOK';
}

function programRankDisplay(program){
  const analogRank = Number(program && program.yeni_program_emsal_tbs || 0);
  if(isNewProgram(program) && Number.isFinite(analogRank) && analogRank > 0){
    const fundingLabel = String(program && program.yeni_program_emsal_mali_etiket || '').trim();
    return fundingLabel
      ? `${fmtNum(analogRank)} (emsal · ${fundingLabel})`
      : `${fmtNum(analogRank)} (emsal)`;
  }
  if(program && (program.kullanilan_program_sira_yok || program.tbs_yok)) return 'YOK';
  return fmtNum(program && program.kullanilan_program_sira);
}
function pdfProgramRank(program){
  return programRankDisplay(program);
}

function pdfQuota(program){
  const raw = program && program.kontenjan;
  if(raw === null || raw === undefined || raw === '') return '—';
  const n = Number(raw);
  return Number.isFinite(n) ? Math.round(n).toLocaleString('tr-TR') : String(raw);
}

function buildPdfTableRows(rows, startIndex, isMobile){
  return rows.map((b, localIndex) => {
    const code = b.program_kodu || b.kodu || b.Kodu || b.id || '';
    const program = b.bolum || b.liste_bolum || '';
    const university = b.universite || '';
    const academic = b.akademik_birim || '';
    const education = b.egitim_turu || b.ogretim_turu || '—';
    const scoreType = b.puan_turu || '—';
    const candidateRank = fmtNum(b.kullanilan_aday_sira);
    const isRisk = riskClassOf(b) === 'risk-yellow';

    if(isMobile){
      const order = startIndex + localIndex + 1;
      const candidateRankHtml = isRisk
        ? `<span class="pdf-mobile-rank-risk">${escapeHtml(candidateRank)}</span>`
        : escapeHtml(candidateRank);
      return `<tr>
        <td>
          <div class="pdf-export-program-main"><span class="pdf-mobile-order">${order}</span><span class="pdf-mobile-program-text">${escapeHtml(code)} ${escapeHtml(program)}</span></div>
          <div class="pdf-export-program-sub">${escapeHtml(university)}${academic ? ` • ${escapeHtml(academic)}` : ''}</div>
          <div class="pdf-export-program-meta">
            <span class="pdf-mobile-meta-item">${escapeHtml(education)} • ${escapeHtml(scoreType)}</span>
            <span class="pdf-mobile-meta-item"><span class="pdf-mobile-meta-label">Taban:</span> ${escapeHtml(pdfTabanPuan(b))}</span>
            <span class="pdf-mobile-meta-item"><span class="pdf-mobile-meta-label">Kontenjan:</span> ${escapeHtml(pdfQuota(b))}</span>
            <span class="pdf-mobile-meta-item"><span class="pdf-mobile-meta-label">Türkiye Başarı:</span> ${escapeHtml(pdfProgramRank(b))}</span>
            <span class="pdf-mobile-meta-item"><span class="pdf-mobile-meta-label">Adayın Başarı:</span> ${candidateRankHtml}</span>
          </div>
        </td>
      </tr>`;
    }

    return `<tr>
      <td class="c">${startIndex + localIndex + 1}</td>
      <td><div class="pdf-export-program-main">${escapeHtml(code)} ${escapeHtml(program)}</div><div class="pdf-export-program-sub">${escapeHtml(university)}${academic ? ` • ${escapeHtml(academic)}` : ''}</div></td>
      <td class="c">${escapeHtml(education)}</td>
      <td class="c">${escapeHtml(scoreType)}</td>
      <td class="r">${escapeHtml(pdfTabanPuan(b))}</td>
      <td class="r">${escapeHtml(pdfProgramRank(b))}</td>
      <td class="r${isRisk ? ' pdf-risk-cell' : ''}">${escapeHtml(candidateRank)}</td>
      <td class="c">${escapeHtml(pdfQuota(b))}</td>
    </tr>`;
  }).join('');
}

function pdfNotesHtml(){
  return `<div class="pdf-export-notes">
    <div class="pdf-export-notes-title">Açıklamalar</div>
    <p class="pdf-export-risk-note">${escapeHtml(RISK_WARNING)}</p>
    <p>TBS, bölümün geçen yıl oluşan ve dikkate alınması gereken Türkiye başarı sırasıdır.</p>
    <p>Yeni açılan programlar, aynı bölüm adı + aynı puan türü + aynı eğitim süresindeki geçmiş programların TBS değerleri adayın sırasıyla karşılaştırılarak listelenir. “Emsal” ibaresi gerçek program TBS'si değil, bu karşılaştırmada kullanılan en yakın geçmiş TBS'dir.</p>
    <p class="pdf-export-source-note">${escapeHtml(SOURCE_WARNING)}</p>
    <p><b>Kısaltmalar:</b> YENİ: Bu yıl yeni açılan programdır. DOLMADI: Geçen yıl kontenjanı dolmayan programdır. Y.P.TÜR: Puan türü değişen programdır.</p>
  </div>`;
}

function isMobilePdfDevice(){
  const ua = String(navigator.userAgent || navigator.vendor || '').toLowerCase();
  const mobileUa = /android|iphone|ipad|ipod|mobile|opera mini|iemobile/.test(ua);
  const mobileScreen = Math.min(window.screen?.width || 9999, window.innerWidth || 9999) <= 820;
  const coarsePointer = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
  return mobileUa || (mobileScreen && coarsePointer);
}

function buildPdfPage(state, chunk, startIndex, pageNumber, totalPages, includeNotes, dateText, isMobile){
  const page = document.createElement('section');
  page.className = 'pdf-export-page';
  const student = String(STUDENT_FULL_NAME || STUDENT_NAME || 'Sayın aday').trim();
  const tableHtml = isMobile
    ? `<table class="pdf-export-table">
        <colgroup><col style="width:100%"></colgroup>
        <thead><tr><th>Tercih Programı / Üniversite ve Başarı Bilgileri</th></tr></thead>
        <tbody>${buildPdfTableRows(chunk, startIndex, true)}</tbody>
      </table>`
    : `<table class="pdf-export-table">
        <colgroup><col style="width:4%"><col style="width:49%"><col style="width:8%"><col style="width:7%"><col style="width:9%"><col style="width:9%"><col style="width:9%"><col style="width:5%"></colgroup>
        <thead><tr><th>Sıra</th><th>Bölüm</th><th>Eğitim Türü</th><th>Puan Türü</th><th>Taban Puan</th><th>Türkiye Başarı</th><th>Adayın Başarı</th><th>Kontenjan</th></tr></thead>
        <tbody>${buildPdfTableRows(chunk, startIndex, false)}</tbody>
      </table>`;

  page.innerHTML = `
    <div class="pdf-export-heading"><h1>${escapeHtml(state.title)}</h1><div class="pdf-export-brand">Tercih Robotu</div></div>
    <div class="pdf-export-info">
      <div class="pdf-export-info-row"><b>Adı ve Soyadı:</b> ${escapeHtml(student)}</div>
      <div class="pdf-export-info-row"><b>Liste Adı:</b> ${escapeHtml(state.title)}</div>
      <div class="pdf-export-info-row"><b>Oluşturulma:</b> ${escapeHtml(dateText)} &nbsp; • &nbsp; Toplam ${state.rows.length.toLocaleString('tr-TR')} tercih</div>
    </div>
    ${chunk.length ? tableHtml : ''}
    ${includeNotes ? pdfNotesHtml() : ''}
    <div class="pdf-export-footer"><span>Tüm veriler ÖSYM ve YÖK kaynaklıdır.</span><span>Sayfa ${pageNumber} / ${totalPages}</span></div>`;
  return page;
}

function buildPdfPages(state){
  const isMobile = isMobilePdfDevice();
  const root = document.createElement('div');
  root.className = `pdf-export-root ${isMobile ? 'pdf-mobile' : 'pdf-desktop'}`;
  const firstCapacity = isMobile ? 8 : 14;
  const otherCapacity = isMobile ? 9 : 16;
  const notesThreshold = isMobile ? 2 : 5;
  const chunks = [];
  let offset = 0;
  while(offset < state.rows.length){
    const capacity = chunks.length === 0 ? firstCapacity : otherCapacity;
    chunks.push({start:offset, rows:state.rows.slice(offset, offset + capacity)});
    offset += capacity;
  }
  const notesFitLastPage = chunks.length > 0 && chunks[chunks.length - 1].rows.length <= notesThreshold;
  const totalPages = chunks.length + (notesFitLastPage ? 0 : 1);
  const dateText = new Date().toLocaleString('tr-TR');
  const pages = [];

  chunks.forEach((chunk, index) => {
    const includeNotes = notesFitLastPage && index === chunks.length - 1;
    const page = buildPdfPage(state, chunk.rows, chunk.start, index + 1, totalPages, includeNotes, dateText, isMobile);
    root.appendChild(page);
    pages.push(page);
  });

  if(!notesFitLastPage){
    const notesPage = buildPdfPage(state, [], state.rows.length, totalPages, totalPages, true, dateText, isMobile);
    root.appendChild(notesPage);
    pages.push(notesPage);
  }

  document.body.appendChild(root);
  return {
    root,
    pages,
    isMobile,
    pixelWidth: isMobile ? 794 : 1123,
    pixelHeight: isMobile ? 1123 : 794,
    pdfWidth: isMobile ? 210 : 297,
    pdfHeight: isMobile ? 297 : 210,
    orientation: isMobile ? 'portrait' : 'landscape'
  };
}

function pdfLibraryReady(test){
  try{return !!test();}catch(e){return false;}
}

function loadPdfLibraryScript(url, test, timeoutMs = 6500){
  return new Promise((resolve, reject) => {
    if(pdfLibraryReady(test)) return resolve();

    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    script.setAttribute('data-pdf-library', url);

    let finished = false;
    const finish = (ok, error) => {
      if(finished) return;
      finished = true;
      clearTimeout(timer);
      script.onload = null;
      script.onerror = null;
      if(ok) resolve();
      else {
        script.remove();
        reject(error || new Error('Kütüphane yüklenemedi: ' + url));
      }
    };

    script.onload = () => finish(pdfLibraryReady(test), new Error('Kütüphane açıldı ancak kullanılamadı: ' + url));
    script.onerror = () => finish(false, new Error('Kütüphane adresine ulaşılamadı: ' + url));
    const timer = setTimeout(() => finish(false, new Error('Kütüphane yükleme süresi doldu: ' + url)), timeoutMs);
    document.head.appendChild(script);
  });
}

async function loadFirstAvailablePdfLibrary(urls, test, label){
  if(pdfLibraryReady(test)) return;
  let lastError = null;
  for(const url of urls){
    try{
      await loadPdfLibraryScript(url, test);
      if(pdfLibraryReady(test)) return;
    }catch(error){
      lastError = error;
      console.warn(label + ' yükleme denemesi başarısız:', url, error);
    }
  }
  throw lastError || new Error(label + ' yüklenemedi.');
}

async function ensureDirectPdfLibraries(){
  await loadFirstAvailablePdfLibrary([
    'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
    'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js',
    'https://unpkg.com/html2canvas@1.4.1/dist/html2canvas.min.js'
  ], () => typeof window.html2canvas === 'function', 'html2canvas');

  await loadFirstAvailablePdfLibrary([
    'https://cdn.jsdelivr.net/npm/jspdf@4.2.1/dist/jspdf.umd.min.js',
    'https://unpkg.com/jspdf@4.2.1/dist/jspdf.umd.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/jspdf/4.0.0/jspdf.umd.min.js'
  ], () => !!(window.jspdf && window.jspdf.jsPDF), 'jsPDF');
}

function downloadPdfBlob(pdf, filename){
  const blob = pdf.output('blob');
  if(!(blob instanceof Blob) || blob.size < 100){
    throw new Error('PDF dosyası oluşturulamadı.');
  }

  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 15000);
}

async function savePreferencePdf(state, button){
  if(!state.finalized){
    alert('PDF kaydından önce listeyi kesinleştirmelisin.');
    return;
  }
  if(!state.rows.length){
    alert('Kaydedilecek tercih kalmadı.');
    return;
  }

  const file = uniquePdfFilename(state.title);
  const oldText = button.textContent;
  button.disabled = true;
  button.textContent = 'PDF hazırlanıyor...';
  let exportDoc = null;

  try{
    await ensureDirectPdfLibraries();
    exportDoc = buildPdfPages(state);
    if(document.fonts && document.fonts.ready) await document.fonts.ready;
    await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));

    const {jsPDF} = window.jspdf;
    const pdf = new jsPDF({orientation:exportDoc.orientation, unit:'mm', format:'a4', compress:true});
    const renderScale = exportDoc.isMobile ? 1.25 : 2;
    const jpegQuality = exportDoc.isMobile ? 0.90 : 0.96;

    for(let i = 0; i < exportDoc.pages.length; i++){
      const page = exportDoc.pages[i];
      const canvas = await window.html2canvas(page, {
        scale:renderScale,
        useCORS:true,
        backgroundColor:'#ffffff',
        logging:false,
        width:exportDoc.pixelWidth,
        height:exportDoc.pixelHeight,
        windowWidth:exportDoc.pixelWidth,
        windowHeight:exportDoc.pixelHeight,
        scrollX:0,
        scrollY:0,
        imageTimeout:8000,
        removeContainer:true
      });
      const image = canvas.toDataURL('image/jpeg', jpegQuality);
      if(i > 0) pdf.addPage([exportDoc.pdfWidth, exportDoc.pdfHeight], exportDoc.orientation);
      pdf.addImage(image, 'JPEG', 0, 0, exportDoc.pdfWidth, exportDoc.pdfHeight, undefined, 'FAST');
      canvas.width = 1;
      canvas.height = 1;
      await new Promise(resolve => setTimeout(resolve, exportDoc.isMobile ? 40 : 0));
    }

    downloadPdfBlob(pdf, file.filename);
    state.saved = true;
    state.version = file.version;
    button.textContent = `Yeni PDF Sürümü Kaydet • son v${file.version}`;
    if(activePreferenceList === state) activePreferenceList.saved = true;
  }catch(err){
    console.error(err);
    alert('PDF indirilemedi: ' + ((err && err.message) ? err.message : 'Bilinmeyen hata'));
    button.textContent = oldText;
  }finally{
    if(exportDoc && exportDoc.root) exportDoc.root.remove();
    button.disabled = false;
  }
}

function addResultCard(j, skipRecord = false){
  const result = (j && j.result) ? j.result : {};
  const type = result.direct_type || 'bolumler';
  let allRows = [];
  if(type === 'universiteler') allRows = Array.isArray(result.universiteler) ? result.universiteler.slice() : [];
  else if(type === 'programlar') allRows = Array.isArray(result.programs) ? result.programs.slice(0, 150).map((x,i)=>({...x,_listId:`p_${Date.now()}_${i}_${Math.random()}`})) : [];
  else allRows = Array.isArray(result.bolumler) ? result.bolumler.slice() : [];

  if(!allRows.length){
    addMsg('bot', (j && j.reply) ? j.reply : 'Bu filtrelerle sonuç bulunamadı 😕');
    return;
  }

  const row = document.createElement('div');
  row.className = 'msg-row bot-row result-message-row';
  const av = document.createElement('div');
  av.className = 'mini-avatar';
  const avImg = document.createElement('img');
  avImg.src = '/robot.png'; avImg.alt = 'Robot'; av.appendChild(avImg); row.appendChild(av);

  const card = document.createElement('div');
  card.className = 'msg bot result-card';
  const hitap = pickHitap();
  const rankMode = j && j.filters && j.filters.tercih_gosterim === 'basari';
  const listTitle = type === 'programlar' ? deriveListTitle(lastUserQuestion, j && j.filters, j && j.reply) : '';
  const title = type === 'universiteler' ? 'Üniversite Listesi' : (type === 'programlar' ? listTitle : (type === 'bolum_kontrol' ? 'Bölüm Kontrolü' : 'Bölüm Listesi'));
  const defaultDesc = type === 'universiteler' ? 'Şehir ve üniversite türüne göre sonuçları çıkardım.' : (type === 'programlar' ? 'Başarı sırana göre uygun programları üniversite adı ve program koduyla listeledim.' : 'Veritabanında eşleşen sonuçları kontrol ettim.');
  const descRaw = (j && typeof j.reply === 'string' && j.reply.trim()) ? j.reply.trim() : defaultDesc;
  const desc = descRaw.replace(/\r/g, '').replace(/\n[ \t]*\n+/g, '\n').replace(/[ \t]+/g, ' ').trim();
  const totalProgram = Number(result.total_program || result.total_bolum || allRows.length || 0);
  const shownProgram = Number(result.shown_program || result.shown_bolum || allRows.length || 0);
  const statLabel = type === 'universiteler' ? `🏫 Toplam Üniversite: ${allRows.length}` : (type === 'programlar' ? `🎯 Listede: ${allRows.length} program` : `📚 Toplam Sonuç: ${allRows.length}`);
  const autoLimitNotice = type === 'programlar' ? (totalProgram > shownProgram ? `Toplam ${totalProgram.toLocaleString('tr-TR')} uygun program bulundu. Başarı sırana en uygun ${shownProgram.toLocaleString('tr-TR')} program gösteriliyor.` : `Toplam ${totalProgram.toLocaleString('tr-TR')} uygun program bulundu.`) : '';
  const searchText = type === 'universiteler' ? 'Üniversite ara...' : (type === 'programlar' ? 'Program ara: üniversite, bölüm, kod, şehir...' : 'Sonuçlarda ara...');

  card.innerHTML = `
    <div class="result-hero result-hero-compact"><div class="result-kicker">${escapeHtml(hitap)}, sonuçlar hazır</div><h3>${escapeHtml(title)}</h3><p>${escapeHtml(desc).replace(/\n/g,'<br>')}</p>${(result.notice || result.result_note || autoLimitNotice) ? `<div class="result-note">${escapeHtml(result.notice || result.result_note || autoLimitNotice)}</div>` : ''}<div class="result-count-compact"><span class="result-stat js-current-count">${escapeHtml(statLabel)}</span></div><div class="result-stats"><span class="result-stat">${type === 'programlar' ? 'Üniversite adı ve program kodu' : 'Akıllı filtrelenmiş sonuç'}</span></div></div>
    <div class="result-tools"><input class="result-search" type="search" placeholder="${escapeHtml(searchText)}"></div>
    <div class="result-list"></div><div class="result-more">Aşağı indikçe daha fazla sonuç yüklenecek…</div>
    ${type === 'programlar' ? `<div class="result-final-panel"><div class="risk-alert">${escapeHtml(RISK_WARNING)}</div><div class="final-actions"><button class="final-action finalize-list" type="button">Listeyi Kesinleştir</button><button class="final-action save-pdf" type="button" disabled>PDF Olarak Kaydet</button></div><div class="final-status">Sıralamayı ↑ ↓ oklarıyla değiştirebilir, istemediğin programı X'e tıklayarak silebilirsin.</div><div class="source-alert">${escapeHtml(SOURCE_WARNING)}</div></div>` : ''}`;
  row.appendChild(card); messages.appendChild(row);

  const list = card.querySelector('.result-list');
  const more = card.querySelector('.result-more');
  const search = card.querySelector('.result-search');
  const countBadge = card.querySelector('.js-current-count');
  const finalPanel = card.querySelector('.result-final-panel');
  const finalizeBtn = card.querySelector('.finalize-list');
  const pdfBtn = card.querySelector('.save-pdf');
  const finalStatus = card.querySelector('.final-status');
  const sourceAlert = card.querySelector('.source-alert');
  const chunk = type === 'programlar' ? 18 : 24;
  let shown = 0;
  let initialRevealLocked = isMobileChatViewport() && !skipRecord;
  let filtered = allRows.slice();
  const state = type === 'programlar' ? {card, rows:allRows, title:listTitle, finalized:false, saved:false, version:0} : null;
  if(state) activePreferenceList = state;

  const updateCount = () => {
    if(type === 'programlar') countBadge.textContent = `🎯 Listede: ${allRows.length} program`;
  };
  const markDirty = () => {
    if(!state) return;
    state.finalized = false; state.saved = false;
    if(finalizeBtn) finalizeBtn.textContent = 'Listeyi Yeniden Kesinleştir';
    if(pdfBtn){ pdfBtn.disabled = true; pdfBtn.textContent = 'PDF Olarak Kaydet'; }
    if(sourceAlert) sourceAlert.classList.remove('show');
    if(finalStatus) finalStatus.textContent = 'Liste değişti. PDF kaydından önce yeniden kesinleştir.';
  };
  const rowHtml = (b) => {
    if(type === 'universiteler'){
      return `<div class="result-row"><div><div class="result-name">${escapeHtml(b.universite||'')}</div><div class="result-sub">${escapeHtml(b.il||'')} • ${escapeHtml(b.universite_turu||'')} • ${escapeHtml(b.bolum_sayisi||0)} bölüm</div></div><div class="result-edu">${escapeHtml(b.universite_turu||'')}</div><div class="result-count">${escapeHtml(b.program_sayisi||0)} program</div></div>`;
    }
    if(type === 'programlar'){
      const idx = allRows.findIndex(x=>x._listId === b._listId);
      const code = b.program_kodu || b.kodu || b.Kodu || b.id || '';
      const uni = b.universite || '';
      const bolum = b.bolum || b.liste_bolum || '';
      const il = b.il || '';
      const tur = b.universite_turu || b.UniversiteTuru || b.tur || '';
      const pt = b.puan_turu || '';
      const fee = b.ogretim_ucreti || '';
      const sira = programRankDisplay(b);
      const aday = fmtNum(b.kullanilan_aday_sira);
      const puan = programTabanPuan(b);
      const warnings = Array.isArray(b.uyarilar) ? b.uyarilar.join(' ') : (b.uyari || '');
      return `<div class="result-row program-row preference-row ${riskClassOf(b)}" data-list-id="${escapeHtml(b._listId)}" draggable="true">
        <div class="preference-number">${idx+1}</div><div class="program-main"><div class="result-program-title">${escapeHtml(code)} — ${escapeHtml(uni)}<br>${escapeHtml(bolum)}</div><div class="program-tags"><span class="program-tag">${escapeHtml(pt)}</span><span class="program-tag">${escapeHtml(il)}</span><span class="program-tag">${escapeHtml(tur||'-')}</span></div></div>
        <div class="list-controls"><button class="list-control" data-action="up" title="Yukarı taşı" ${idx===0?'disabled':''}>↑</button><button class="list-control" data-action="down" title="Aşağı taşı" ${idx===allRows.length-1?'disabled':''}>↓</button><button class="list-control delete" data-action="delete" title="Listeden sil">×</button></div>
        <div class="result-program-meta">Program kodu: ${escapeHtml(code||'-')} • Taban puan: ${escapeHtml(puan)} • Program başarı sırası: ${escapeHtml(sira)} • Aday başarı sırası: ${escapeHtml(aday)}${fee ? ` • Ücret: ${escapeHtml(fee)}` : ''}</div>${warnings ? `<div class="result-warning">⚠️ ${escapeHtml(warnings)}</div>` : ''}</div>`;
    }
    return `<div class="result-row"><div class="result-name">${escapeHtml(b.bolum||b.Bolum||'')}</div><div class="result-edu">${escapeHtml(b.egitim_turu||'')}</div><div class="result-count">${escapeHtml(b.count||0)} bölüm</div></div>`;
  };
  const searchTextOf = (b) => type === 'universiteler' ? `${b.universite||''} ${b.il||''} ${b.universite_turu||''}` : (type === 'programlar' ? `${b.program_kodu||b.kodu||''} ${b.universite||''} ${b.bolum||''} ${b.liste_bolum||''} ${b.il||''} ${b.puan_turu||''}` : `${b.bolum||''} ${b.egitim_turu||''}`);
  const syncFiltered = () => { const q=normalizeTR(search.value.trim()); filtered=!q?allRows.slice():allRows.filter(b=>normalizeTR(searchTextOf(b)).includes(q)); };
  const updateEnd = () => {
    const atFullEnd = !search.value.trim() && shown >= allRows.length;
    if(filtered.length===0){ more.textContent='Bu aramada sonuç yok.'; more.classList.remove('end'); }
    else if(shown>=filtered.length){ more.textContent=atFullEnd?'✅ Sona geldiniz':'Arama sonuçlarının sonuna geldiniz.'; more.classList.toggle('end',atFullEnd); }
    else { more.textContent='Aşağı indikçe daha fazla sonuç yüklenecek…'; more.classList.remove('end'); }
    if(finalPanel) finalPanel.classList.toggle('show', atFullEnd);
  };
  const renderMore = () => { const end=Math.min(shown+chunk,filtered.length); let html=''; for(let i=shown;i<end;i++) html+=rowHtml(filtered[i]); list.insertAdjacentHTML('beforeend',html); shown=end; updateEnd(); };
  const rerender = (keepCount=true) => { const target=keepCount?Math.max(chunk,shown):chunk; list.innerHTML=''; shown=0; syncFiltered(); while(shown<filtered.length && shown<target) renderMore(); updateCount(); updateEnd(); };

  search.addEventListener('input',()=>rerender(false));
  more.addEventListener('click',()=>{ if(shown<filtered.length) renderMore(); });
  messages.addEventListener('scroll',()=>{
    if(initialRevealLocked || shown>=filtered.length) return;
    const r=more.getBoundingClientRect();
    const s=messages.getBoundingClientRect();
    /* İşaretçi gerçekten görünümün altına yaklaşınca yükle. Üstte kalmış eski
       işaretçiler mobilde arka arkaya satır yükleyip kullanıcıyı 50+ satıra atmasın. */
    if(r.bottom >= s.top - 20 && r.top < s.bottom + 220) renderMore();
  });

  if(type === 'programlar'){
    list.addEventListener('click',(e)=>{
      const btn=e.target.closest('.list-control'); if(!btn) return;
      const item=btn.closest('[data-list-id]'); const id=item&&item.dataset.listId; const idx=allRows.findIndex(x=>x._listId===id); if(idx<0)return;
      const action=btn.dataset.action;
      if(action==='delete'){ allRows.splice(idx,1); }
      else if(action==='up'&&idx>0){ [allRows[idx-1],allRows[idx]]=[allRows[idx],allRows[idx-1]]; }
      else if(action==='down'&&idx<allRows.length-1){ [allRows[idx+1],allRows[idx]]=[allRows[idx],allRows[idx+1]]; }
      state.rows=allRows; markDirty(); rerender(true);
    });
    let dragId='';
    list.addEventListener('dragstart',(e)=>{ const item=e.target.closest('[data-list-id]'); if(item){dragId=item.dataset.listId; e.dataTransfer.effectAllowed='move';} });
    list.addEventListener('dragover',(e)=>{ if(e.target.closest('[data-list-id]')) e.preventDefault(); });
    list.addEventListener('drop',(e)=>{ e.preventDefault(); const target=e.target.closest('[data-list-id]'); if(!target||!dragId||target.dataset.listId===dragId)return; const from=allRows.findIndex(x=>x._listId===dragId), to=allRows.findIndex(x=>x._listId===target.dataset.listId); if(from<0||to<0)return; const [moved]=allRows.splice(from,1); allRows.splice(to,0,moved); state.rows=allRows; markDirty(); rerender(true); dragId=''; });
    finalizeBtn.addEventListener('click',()=>{ if(!allRows.length){alert('Listede program kalmadı.');return;} state.finalized=true; state.saved=false; finalizeBtn.textContent='Liste Kesinleştirildi ✓'; pdfBtn.disabled=false; sourceAlert.classList.add('show'); finalStatus.textContent='Listen kesinleştirildi. Yeni bir soruya geçmeden önce PDF olarak kaydet.'; activePreferenceList=state; });
    pdfBtn.addEventListener('click',()=>savePreferencePdf(state,pdfBtn));
  }

  renderMore();
  if(!skipRecord){
    if(isMobileChatViewport()){
      pinResultMessageToTop(row);
      window.setTimeout(() => {
        initialRevealLocked = false;
        pinResultMessageToTop(row);
      }, 1750);
    }else{
      scrollMessageToStart(row);
      initialRevealLocked = false;
    }
  }else{
    initialRevealLocked = false;
  }

  if(!skipRecord){
    recordUiEvent({type:'result', payload:j});
  }

  return row;
}

function guardUnsavedFinalList(){
  if(activePreferenceList && activePreferenceList.finalized && !activePreferenceList.saved){
    const ok = window.confirm('Kesinleştirdiğin tercih listesini henüz PDF olarak kaydetmedin. Yeni soruya geçmeden veya listeyi sıfırlamadan önce kaydetmen önerilir. Yine de devam etmek istiyor musun?');
    if(!ok) return false;
    activePreferenceList = null;
  }
  return true;
}

messages.addEventListener('click', async (e)=>{
  const btn = e.target.closest('.answer-edit-inline');
  if(!btn || btn.disabled || sendBtn.disabled) return;
  if(!hasCurrentPdfAccess()){
    addPaymentRequiredMsg();
    return;
  }
  if(!guardUnsavedFinalList()) return;

  const criterion = String(btn.dataset.criterion || '');
  if(!criterion) return;

  messages.querySelectorAll('.answer-edit-inline').forEach(b => b.disabled = true);
  sendBtn.disabled = true;
  clearQuickReplies();
  activeCriterion = '';
  setTyping(true);
  try{
    const j = await api({action:'edit_criterion', criterion});
    const reply = (j && j.reply) ? j.reply : 'Bu seçimi yeniden yapabilirsin.';
    addMsg('bot', reply);
    renderQuickReplies(reply);
  }catch(err){
    addMsg('bot','Kriter düzenleme sırasında bağlantı hatası oldu.');
  }finally{
    setTyping(false);
    sendBtn.disabled = false;
    messages.querySelectorAll('.answer-edit-inline').forEach(b => b.disabled = false);
    input.focus();
  }
});

window.addEventListener('beforeunload',(e)=>{if(activePreferenceList&&activePreferenceList.finalized&&!activePreferenceList.saved){e.preventDefault();e.returnValue='';}});

function setQuickDisabled(disabled){
  if(!quickReplies) return;
  quickReplies.querySelectorAll('button').forEach(b => b.disabled = !!disabled);
}
async function sendMessage(text){
  text = String(text || '').trim();
  if(!text) return;

  // İlk açılışta kullanıcı iki başlangıç seçeneğinden birini seçmeden serbest mesaj gönderemez.
  if(!initialChoiceMade){
    if(!isInitialChoiceText(text)) return;
    initialChoiceMade = true;
    setComposerLocked(false);
  }

  if(sendBtn.disabled) return;

  // Mobilde mesaj gönderildiği anda klavyeyi kapat; sonuç listesi klavye altında kalmasın.
  dismissMobileKeyboard();

  // Bu PDF için kullanım hakkı yoksa soruyu göster, ancak AI API'sine istek gönderme.
  if(!hasCurrentPdfAccess()){
    lastUserQuestion = text;
    messages.classList.remove('initial-question');
    activeCriterion = '';
    clearQuickReplies();
    input.value = '';
    input.style.height = 'auto';
    addMsg('user', text);
    addPaymentRequiredMsg();
    focusComposerOnDesktop();
    return;
  }

  if(!guardUnsavedFinalList()) return;
  lastUserQuestion = text;
  messages.classList.remove('initial-question');
  const apiText = text === 'Hazır adımları kullanacağım' ? 'Mevcut filtreleri kullanacağım' : text;
  const answeredCriterion = activeCriterion;
  activeCriterion = '';
  clearQuickReplies();
  input.value='';
  input.style.height='auto';
  const userRow = addMsg('user', text);
  addAnswerEditLink(userRow, answeredCriterion);
  sendBtn.disabled = true;
  setQuickDisabled(true);

  await delayedBotReply({action:'message', message:apiText}, 'Tamam.');
  sendBtn.disabled = false;
  setQuickDisabled(false);
  focusComposerOnDesktop();
}
async function api(payload){
  const r = await fetch('ai_tercih_api.php?v=yeni-program-v5-20260722', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify(payload)
  });
  const txt = await r.text();
  let j = null;
  try { j = JSON.parse(txt); } catch(e) { throw new Error('API_JSON_DEGIL: ' + txt.slice(0, 160)); }
  if(!r.ok || (j && j.ok === false && j.error)){ throw new Error(j.reply || j.error || 'API_HATA'); }
  return j;
}
async function delayedBotReply(payload, fallback){
  clearQuickReplies();
  setTyping(true);
  const started = Date.now();
  let addedResultRow = null;
  try{
    const j = await api(payload);
    const wait = Math.max(0, minDelay() - (Date.now() - started));
    await sleep(wait);
    let reply = (j && typeof j.reply === 'string') ? j.reply.trim() : '';
    const resultType = j && j.result ? (j.result.direct_type || '') : '';
    const hasResultCard = resultType !== 'info' && j && j.result && (
      (Array.isArray(j.result.bolumler) && j.result.bolumler.length) ||
      (Array.isArray(j.result.universiteler) && j.result.universiteler.length) ||
      (Array.isArray(j.result.programs) && j.result.programs.length)
    );
    if(hasResultCard){
      activeCriterion = '';
      addedResultRow = addResultCard(j);
    }else{
      if(!reply) reply = fallback || firstQuestion();

      const isDirectAnswer = !!(
        j && (
          j.direct_query === true
          || (j.result && j.result.direct_query === true)
          || j.mode === 'direct'
        )
      );

      const isFilterFlow = !!(
        j
        && !isDirectAnswer
        && (j.mode === 'filter' || j.next_step || j.editing)
      );

      /*
       | Bölüm/program/üniversite listeleri addResultCard ile gösterilir.
       | Hazır filtre soruları cevap değildir. WhatsApp desteği yalnız liste
       | olmayan gerçek metinsel cevapların sonunda gösterilir.
       */
      addMsg('bot', reply, false, !isFilterFlow);

      if(isFilterFlow) renderQuickReplies(reply);
      else clearQuickReplies();
    }
  }catch(e){
    await sleep(900);
    addMsg('bot','API bağlantısında hata oldu. Lütfen tekrar deneyin.');
  }finally{
    setTyping(false);
    /* Yazıyor alanı kapandıktan ve mobil klavye tamamen çekildikten sonra sonuç
       kartının başını son kez sabitle. */
    if(addedResultRow && isMobileChatViewport()){
      pinResultMessageToTop(addedResultRow);
    }
  }
}
async function init(forceFresh = false){
  updatePdfAccessStatus();
  messages.innerHTML = '';
  scrollMessagesToTop('auto');
  messages.classList.add('initial-question');
  clearQuickReplies();
  initialChoiceMade = false;
  activeCriterion = '';
  setComposerLocked(true);
  setTyping(false);

  if(!hasCurrentPdfAccess()){
    if(forceFresh){
      uiChatHistory = [];
      uiChatMeta = {};
      await persistUiChat(false);
    }

    addPaymentRequiredMsg();
    input.placeholder = remainingPdfRights > 0
      ? 'Önce ÖSYM Sonuç Belgenizi yükleyin.'
      : 'Önce Sonuç Belgesi paketi satın alın.';
    return;
  }

  // Belgeye ait eski sohbet varsa API'yi sıfırlama; mesajları ve bağlamı geri getir.
  if(!forceFresh && restoreUiChatHistory()){
    input.placeholder = 'Sorunu yaz...';
    return;
  }

  if(!forceFresh && HAS_RESTORED_SERVER_CONTEXT){
    fallbackHistoryFromServer();
    if(restoreUiChatHistory()){
      input.placeholder = 'Sorunu yaz...';
      return;
    }
  }

  try{ await api({action:'reset'}); }catch(e){}

  uiChatHistory = [];
  uiChatMeta = {};

  const q = firstQuestion();
  addMsg('bot', q);
  renderQuickReplies(q);
  scheduleChatSave(50);
}
form.addEventListener('submit', async (e)=>{
  e.preventDefault();
  if(speechRecognitionActive && speechRecognition){
    speechRecognition.stop();
  }
  await sendMessage(input.value.trim());
});
input.addEventListener('keydown', (e)=>{
  if(e.key === 'Enter' && !e.shiftKey){
    e.preventDefault();
    if(!sendBtn.disabled){
      form.requestSubmit ? form.requestSubmit() : form.dispatchEvent(new Event('submit', {cancelable:true}));
    }
  }
});
resetBtn.addEventListener('click', async ()=>{
  if(sendBtn.disabled) return;
  if(!guardUnsavedFinalList()) return;

  activePreferenceList = null;
  sendBtn.disabled = true;
  uiChatHistory = [];
  uiChatMeta = {};
  messages.innerHTML = '';
  clearQuickReplies();

  await persistUiChat(false);
  await init(true);

  sendBtn.disabled = false;
  input.focus();
});
input.addEventListener('input', resizeComposerInput);
(async () => {
  await init();
  scrollMessagesToTop('auto');
  window.setTimeout(() => scrollMessagesToTop('auto'), 120);
})();
</script>

<!-- AI MOBIL SOHBET YUKSEKLIGI DUZELTMESI BASLA -->
<script id="ai-mobile-chat-height-fix">
(function () {
  'use strict';

  var root = document.documentElement;
  var mobileQuery = window.matchMedia('(max-width: 980px)');

  function setMobileChatHeight() {
    if (!mobileQuery.matches) {
      root.style.removeProperty('--ai-mobile-chat-height');
      return;
    }
    var viewport = window.visualViewport;
    var viewportHeight = viewport && viewport.height
      ? viewport.height
      : window.innerHeight;
    var available = Math.floor(viewportHeight);

    /* Çok kısa yatay ekranlarda bile formun tamamı erişilebilir kalsın. */
    available = Math.max(300, available);
    root.style.setProperty('--ai-mobile-chat-height', available + 'px');
  }

  function scheduleUpdate() {
    window.requestAnimationFrame(setMobileChatHeight);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', scheduleUpdate, { once: true });
  } else {
    scheduleUpdate();
  }

  window.addEventListener('load', scheduleUpdate, { once: true });
  window.addEventListener('resize', scheduleUpdate, { passive: true });
  window.addEventListener('orientationchange', scheduleUpdate, { passive: true });

  if (window.visualViewport) {
    window.visualViewport.addEventListener('resize', scheduleUpdate, { passive: true });
  }

  if (typeof mobileQuery.addEventListener === 'function') {
    mobileQuery.addEventListener('change', scheduleUpdate);
  } else if (typeof mobileQuery.addListener === 'function') {
    mobileQuery.addListener(scheduleUpdate);
  }
})();
</script>
<!-- AI MOBIL SOHBET YUKSEKLIGI DUZELTMESI BITIR -->


<script id="ai-chatgpt-sidebar-script">
(() => {
  const page = document.querySelector('.tr-ai-page > .page');
  const sidebar = document.getElementById('aiSidebar');
  const toggle = document.getElementById('aiSidebarToggle');
  const close = document.getElementById('aiSidebarClose');
  const backdrop = document.getElementById('aiSidebarBackdrop');
  if (!page || !sidebar || !toggle) return;

  const mobileQuery = window.matchMedia('(max-width:980px)');
  const storageKey = 'tercihRobotuAiSidebarCollapsed';

  const isMobile = () => mobileQuery.matches;

  function setExpanded(expanded, remember = true) {
    if (isMobile()) {
      page.classList.toggle('sidebar-mobile-open', expanded);
      page.classList.remove('sidebar-desktop-collapsed');
      document.body.classList.toggle('ai-sidebar-modal-open', expanded);
    } else {
      page.classList.remove('sidebar-mobile-open');
      page.classList.toggle('sidebar-desktop-collapsed', !expanded);
      document.body.classList.remove('ai-sidebar-modal-open');
      if (remember) {
        try { localStorage.setItem(storageKey, expanded ? '0' : '1'); } catch (e) {}
      }
    }
    toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
  }

  function currentExpanded() {
    return isMobile()
      ? page.classList.contains('sidebar-mobile-open')
      : !page.classList.contains('sidebar-desktop-collapsed');
  }

  function applyInitialState() {
    if (isMobile()) {
      setExpanded(false, false);
      return;
    }
    /* Masaüstünde her sayfa açılışında sol menü varsayılan olarak açık gelsin. */
    try { localStorage.removeItem(storageKey); } catch (e) {}
    setExpanded(true, false);
  }

  toggle.addEventListener('click', () => setExpanded(!currentExpanded()));
  if (close) close.addEventListener('click', () => setExpanded(false));
  if (backdrop) backdrop.addEventListener('click', () => setExpanded(false, false));

  sidebar.addEventListener('click', event => {
    if (isMobile() && event.target.closest('a')) setExpanded(false, false);
  });

  document.addEventListener('keydown', event => {
    if (event.key === 'Escape' && isMobile() && currentExpanded()) setExpanded(false, false);
  });

  const onBreakpointChange = () => applyInitialState();
  if (typeof mobileQuery.addEventListener === 'function') mobileQuery.addEventListener('change', onBreakpointChange);
  else if (typeof mobileQuery.addListener === 'function') mobileQuery.addListener(onBreakpointChange);

  applyInitialState();
})();
</script>

</body>
</html>
