<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// ================= COOKIE / SESSION =================
require_once($_SERVER["DOCUMENT_ROOT"] . '/includes/config.php');
session_set_cookie_params(inpay_session_cookie_params());

include_once($_SERVER["DOCUMENT_ROOT"] . '/includes/db.php');

if (session_status() === PHP_SESSION_NONE) {
    session_start();

}

if (!isset($_SESSION['user_id']) && !empty($_COOKIE['INPAY_SESSION'])) {

    $token = $_COOKIE['INPAY_SESSION'];

    $stmt = $conn->prepare("
        SELECT user_id
        FROM user_sessions
        WHERE session_token = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $session = $result->fetch_assoc();
    $stmt->close();

    if ($session) {
        $_SESSION['user_id'] = $session['user_id'];
        $_SESSION['session_token'] = $token;
    }
}




// ================= SSO AUTO LOGIN =================
if (!isset($_SESSION['user_id'])) {

    if (!empty($_COOKIE['INPAY_SESSION'])) {

        $token = $_COOKIE['INPAY_SESSION'];

        $stmt = $conn->prepare("
            SELECT user_id, ip_address, user_agent
            FROM user_sessions
            WHERE session_token = ?
            LIMIT 1
        ");

        $stmt->bind_param("s", $token);
        $stmt->execute();
        $result = $stmt->get_result();
        $session = $result->fetch_assoc();
        $stmt->close();

        if ($session) {

            // optional security check
            $currentIp  = $_SERVER['REMOTE_ADDR'] ?? '';
            $currentUA  = $_SERVER['HTTP_USER_AGENT'] ?? '';

            if (
                $session['ip_address'] === $currentIp &&
                $session['user_agent'] === $currentUA
            ) {
                $_SESSION['user_id'] = $session['user_id'];
                $_SESSION['session_token'] = $token;
            }
        }
    }
}

// Mehmon foydalanuvchilar uchun marketing landing sahifa ko'rsatiladi
if (!isset($_SESSION['user_id'])) {
    require $_SERVER['DOCUMENT_ROOT'] . '/landing.php';
    exit;
}


$user_id = (int)$_SESSION['user_id'];

// ================= DEVICE =================
function detect_device(string $ua): string
{
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Opera Mini)/i', $ua)) {
        return 'Mobile';
    }
    if (preg_match('/(Macintosh|Windows|Linux)/i', $ua)) {
        return 'Desktop';
    }
    return 'Unknown';
}

$ip         = $_SERVER['REMOTE_ADDR'] ?? '';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$device     = detect_device($userAgent);

// ================= SESSION TRACKING =================
if (!isset($_SESSION['session_token'])) {

    $sessionToken = bin2hex(random_bytes(32));
    $_SESSION['session_token'] = $sessionToken;

    $stmt = $conn->prepare("
        INSERT INTO user_sessions
        (user_id, device, user_agent, last_login, ip_address, session_token)
        VALUES (?, ?, ?, NOW(), ?, ?)
    ");
    $stmt->bind_param("issss", $user_id, $device, $userAgent, $ip, $sessionToken);
    $stmt->execute();
    $stmt->close();

} else {

    $stmt = $conn->prepare("
        SELECT COUNT(*) 
        FROM user_sessions 
        WHERE user_id = ? AND session_token = ?
    ");
    $stmt->bind_param("is", $user_id, $_SESSION['session_token']);
    $stmt->execute();
    $stmt->bind_result($active);
    $stmt->fetch();
    $stmt->close();

    if ((int)$active === 0) {
        session_unset();
        session_destroy();

        header("Location: /login?reason=session_expired");
        exit;
    }
}

// ================= USER CORE DATA =================
$stmt = $conn->prepare("
    SELECT 
        passport_status,
        passport_contract,
        phone,
        balance,
        pricing_plan,
        background
    FROM users
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// === PASSPORT STATUS (YAGONA MANBA) ===
$passportStatus   = (int)($user['passport_status'] ?? 0);
$passportContract = $user['passport_contract'] ?? null;

// === PHONE ===
$hasPhone = !empty($user['phone']);

// === BALANCE ===
$currentBalance = $user['balance'] ?? 0;
$userPricing    = strtoupper($user['pricing_plan'] ?? 'STANDART');


// ================= TRANSACTION COUNT =================
$stmt = $conn->prepare("
    SELECT COUNT(*) AS total_count
    FROM transactions t
    INNER JOIN merchant_requests m ON t.merchant_id = m.merchant_id
    WHERE m.user_id = ?
      AND m.status = 'approved'
      AND t.status = 'success'
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$transactionCount = $stmt->get_result()->fetch_assoc()['total_count'] ?? 0;
$stmt->close();

// === BACKGROUND ===
$userBackground = !empty($user['background'])
    ? "/uploads/" . htmlspecialchars($user['background'])
    : null;

// ================= CSRF =================
//if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  //  if (
    //    empty($_POST['csrf_token']) ||
     //   $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')
//    ) {
  //      die("❗ CSRF token noto'g'ri!");
    //}

//    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
//}

// ================= TRANSACTIONS =================
$stmt = $conn->prepare("
    SELECT amount, created_at, order_id
    FROM transactions
    WHERE user_id = ? AND status = 'success'
    ORDER BY created_at ASC
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$balances = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ================= SHOPS =================
$stmt = $conn->prepare("
    SELECT COUNT(*) AS total
    FROM merchant_requests
    WHERE user_id = ? AND status = 'approved'
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$shopStats = $stmt->get_result()->fetch_assoc();
$stmt->close();

$activeShops = (int)($shopStats['total'] ?? 0);

// ================= TURNOVER =================
$stmt = $conn->prepare("
    SELECT COALESCE(SUM(t.amount),0) AS total_sum
    FROM transactions t
    INNER JOIN merchant_requests m ON t.merchant_id = m.merchant_id
    WHERE m.user_id = ?
      AND m.status = 'approved'
      AND t.status = 'success'
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$totalTurnover = $stmt->get_result()->fetch_assoc()['total_sum'] ?? 0;
$stmt->close();

// ================= TODAY =================
$stmt = $conn->prepare("
    SELECT COALESCE(SUM(t.amount),0) AS today_sum
    FROM transactions t
    INNER JOIN merchant_requests m ON t.merchant_id = m.merchant_id
    WHERE m.user_id = ?
      AND m.status = 'approved'
      AND t.status = 'success'
      AND DATE(t.created_at) = CURDATE()
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$todayTurnover = $stmt->get_result()->fetch_assoc()['today_sum'] ?? 0;
$stmt->close();

// ================= WITHDRAW =================
$stmt = $conn->prepare("
    SELECT COUNT(*) AS cnt, COALESCE(SUM(amount),0) AS total
    FROM withdrawal_requests
    WHERE user_id = ? AND status = 'approved'
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$withdraw = $stmt->get_result()->fetch_assoc();
$stmt->close();

$withdrawCount = (int)($withdraw['cnt'] ?? 0);
$withdrawSum   = $withdraw['total'] ?? 0;

// ================= BYOK kassalar + obuna ma'lumotlari =================
$byok_kassas = [];
$byok_helper_path = $_SERVER['DOCUMENT_ROOT'] . '/includes/payment_credentials.php';
if (file_exists($byok_helper_path)) {
    require_once $byok_helper_path;
    $stmt = $conn->prepare("
        SELECT id, merchant_id, business_name
          FROM merchant_requests
         WHERE user_id    = ?
           AND kassa_mode = 'byok'
           AND is_active  = 1
    ");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $q = function_exists('inpay_get_active_byok_quota')
           ? inpay_get_active_byok_quota($conn, (string)$row['merchant_id'])
           : null;
        $byok_kassas[] = ['kassa' => $row, 'quota' => $q];
    }
    $stmt->close();
}


// Foydalanuvchi background rasmi
$bg_stmt = $conn->prepare("SELECT background FROM users WHERE id = ? LIMIT 1");
$bg_stmt->bind_param("i", $user_id);
$bg_stmt->execute();
$bgData = $bg_stmt->get_result()->fetch_assoc();
$bg_stmt->close();

$userBackground = !empty($bgData['background']) ? "/uploads/" . htmlspecialchars($bgData['background']) : null;

// ================= USER DISPLAY NAME =================
$stmt = $conn->prepare("SELECT username,  email FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$userInfo = $stmt->get_result()->fetch_assoc();
$stmt->close();
$displayName    = trim(($userInfo['username'] ?? '') . ' ' . ($userInfo['last_name'] ?? ''));
$displayInitial = strtoupper(mb_substr($displayName ?: ($userInfo['email'] ?? 'U'), 0, 1));
?>
<?php include_once($_SERVER["DOCUMENT_ROOT"] . "/business/includes/head.php"); ?>
<style>
/* ============================================================
   CSS VARIABLES & RESET
============================================================ */
:root {
  --bg: #f7f6f3;
  --surface: #ffffff;
  --surface-2: #f0efe9;
  --border: #e5e3dc;
  --border-hover: #c9c6bc;
  --text-primary: #0d0c0a;
  --text-secondary: #6a6760;
  --text-muted: #9e9b95;
  --accent: #1d4ed8;
  --accent-hover: #1e40af;
  --accent-light: #eef2ff;
  --accent-mid: rgba(29,78,216,0.12);
  --success: #15803d;
  --success-light: #f0fdf4;
  --warning: #b45309;
  --warning-light: #fefce8;
  --danger: #b91c1c;
  --danger-light: #fef2f2;
  --gold: #b45309;
  --purple: #6d28d9;
  --purple-light: #f5f3ff;
  --radius-xs: 6px;
  --radius-sm: 10px;
  --radius-md: 14px;
  --radius-lg: 18px;
  --radius-xl: 24px;
  --radius-2xl: 32px;
  --shadow-xs: 0 1px 2px rgba(0,0,0,0.05);
  --shadow-sm: 0 1px 4px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04);
  --shadow-md: 0 4px 16px rgba(0,0,0,0.07), 0 2px 4px rgba(0,0,0,0.04);
  --shadow-lg: 0 12px 40px rgba(0,0,0,0.09), 0 4px 8px rgba(0,0,0,0.05);
  --transition: 0.2s cubic-bezier(0.4,0,0.2,1);
  --font-display: 'Syne', sans-serif;
  --font-body: 'DM Sans', sans-serif;
}

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

html { scroll-behavior: smooth; }

body {
  font-family: var(--font-body);
  background: var(--bg);
  color: var(--text-primary);
  min-height: 100vh;
  font-size: 15px;
  line-height: 1.6;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

a { text-decoration: none; color: inherit; }
button { font-family: inherit; }
img { max-width: 100%; display: block; }

/* ============================================================
   TOPBAR
============================================================ */
.topbar {
  position: sticky;
  top: 0;
  z-index: 200;
  height: 62px;
  background: rgba(247,246,243,0.88);
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 36px;
}

.logo {
  font-family: var(--font-display);
  font-weight: 800;
  font-size: 1.3rem;
  letter-spacing: -0.04em;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 3px;
}

.logo-accent { color: var(--accent); }

.logo-dot {
  width: 7px;
  height: 7px;
  background: var(--accent);
  border-radius: 50%;
  margin-left: 2px;
  flex-shrink: 0;
}

.topbar-center {
  display: flex;
  align-items: center;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 100px;
  padding: 4px;
  gap: 2px;
  margin: 0 auto;
}

.topbar-center a {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  padding: 7px 16px;
  border-radius: 100px;
  transition: var(--transition);
  white-space: nowrap;
}

.topbar-center a:hover { color: var(--text-primary); }
.topbar-center a.active { background: var(--text-primary); color: #fff; }

.topbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.topbar-icon-btn {
  width: 38px;
  height: 38px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--border);
  background: var(--surface);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  font-size: 17px;
  transition: var(--transition);
  text-decoration: none;
}

.topbar-icon-btn:hover { border-color: var(--border-hover); color: var(--text-primary); }

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--accent), var(--purple));
  color: white;
  font-family: var(--font-display);
  font-size: 0.85rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid var(--border);
  cursor: pointer;
  transition: var(--transition);
  flex-shrink: 0;
}

.avatar:hover { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-light); }

/* ============================================================
   PAGE WRAPPER
============================================================ */
.page {
  max-width: 1360px;
  margin: 0 auto;
  padding: 28px 36px 80px;
}

/* ============================================================
   SECTION LABEL
============================================================ */
.section-label {
  font-family: var(--font-display);
  font-size: 0.68rem;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.14em;
  margin-bottom: 12px;
}

/* ============================================================
   ALERT BANNERS
============================================================ */
.alert-stack { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; }

.alert-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 14px 18px;
  animation: slideDown 0.4s ease;
  box-shadow: var(--shadow-xs);
}

.alert-banner.passport   { border-left: 3px solid var(--warning); }
.alert-banner.pending    { border-left: 3px solid #64748b; }
.alert-banner.rejected   { border-left: 3px solid var(--danger); }
.alert-banner.session-msg{ border-left: 3px solid var(--accent); }

.alert-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.alert-icon-wrap {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 17px;
  flex-shrink: 0;
}

.passport   .alert-icon-wrap { background: var(--warning-light); color: var(--warning); }
.pending    .alert-icon-wrap { background: #f1f5f9; color: #64748b; }
.rejected   .alert-icon-wrap { background: var(--danger-light); color: var(--danger); }
.session-msg .alert-icon-wrap { background: var(--accent-light); color: var(--accent); }

.alert-text strong {
  display: block;
  font-size: 0.85rem;
  font-weight: 600;
  color: var(--text-primary);
}

.alert-text span {
  font-size: 0.78rem;
  color: var(--text-secondary);
}

.alert-cta {
  font-size: 0.8rem;
  font-weight: 600;
  border-radius: 100px;
  padding: 8px 18px;
  border: none;
  cursor: pointer;
  text-decoration: none;
  transition: var(--transition);
  white-space: nowrap;
  flex-shrink: 0;
}

.passport  .alert-cta { background: var(--warning-light); color: var(--warning); }
.passport  .alert-cta:hover { background: var(--warning); color: #fff; }
.rejected  .alert-cta { background: var(--danger-light); color: var(--danger); }
.rejected  .alert-cta:hover { background: var(--danger); color: #fff; }
.pending   .alert-cta { background: #f1f5f9; color: #64748b; cursor: default; }

/* ============================================================
   RAMADAN BANNER
============================================================ */
.ramadan-wrap {
  background: var(--text-primary);
  border-radius: var(--radius-xl);
  padding: 24px 30px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  position: relative;
  overflow: hidden;
  animation: fadeUp 0.5s ease;
}

.ramadan-wrap::before {
  content: '☽';
  position: absolute;
  right: -10px;
  bottom: -50px;
  font-size: 180px;
  opacity: 0.04;
  pointer-events: none;
  line-height: 1;
}

.ramadan-info h5 {
  font-family: var(--font-display);
  font-size: 0.65rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.14em;
  color: rgba(255,255,255,0.4);
  margin-bottom: 4px;
}

.ramadan-info p {
  font-family: var(--font-display);
  font-size: 1.05rem;
  font-weight: 700;
  color: white;
  line-height: 1.2;
}

.ramadan-timer {
  display: flex;
  align-items: center;
  gap: 4px;
}

.t-block { text-align: center; min-width: 66px; }

.t-block .t-num {
  font-family: var(--font-display);
  font-size: 2.6rem;
  font-weight: 800;
  color: white;
  display: block;
  line-height: 1;
  letter-spacing: -0.03em;
}

.t-block .t-unit {
  font-size: 0.62rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  color: rgba(255,255,255,0.35);
  margin-top: 5px;
  display: block;
}

.t-sep {
  font-size: 2rem;
  color: rgba(255,255,255,0.18);
  font-weight: 300;
  padding: 0 2px;
  margin-bottom: 18px;
  line-height: 1;
}

.ramadan-prayers {
  display: flex;
  gap: 0;
  align-items: center;
}

.prayer-item { text-align: center; padding: 0 16px; }
.prayer-item:first-child { padding-left: 0; }

.prayer-item .p-label {
  font-size: 0.62rem;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  color: rgba(255,255,255,0.35);
  display: block;
  margin-bottom: 3px;
}

.prayer-item .p-val {
  font-family: var(--font-display);
  font-size: 1.1rem;
  font-weight: 700;
  color: rgba(255,255,255,0.88);
}

.prayer-sep {
  width: 1px;
  height: 32px;
  background: rgba(255,255,255,0.1);
}

/* ============================================================
   STATS ROW
============================================================ */
.stats-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.stat-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 22px 22px 20px;
  transition: var(--transition);
  cursor: default;
  position: relative;
  overflow: hidden;
  animation: fadeUp 0.45s ease backwards;
}

.stat-card:nth-child(1) { animation-delay: 0.05s; }
.stat-card:nth-child(2) { animation-delay: 0.10s; }
.stat-card:nth-child(3) { animation-delay: 0.15s; }

.stat-card::after {
  content: '';
  position: absolute;
  bottom: 0; left: 0; right: 0;
  height: 2px;
  background: var(--accent);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
  border-radius: 0 0 var(--radius-lg) var(--radius-lg);
}

.stat-card:hover { border-color: var(--border-hover); box-shadow: var(--shadow-md); transform: translateY(-2px); }
.stat-card:hover::after { transform: scaleX(1); }

.sc-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 14px;
}

.sc-label {
  font-size: 0.72rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.09em;
  color: var(--text-muted);
}

.sc-icon {
  width: 32px;
  height: 32px;
  border-radius: var(--radius-xs);
  background: var(--surface-2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  color: var(--text-secondary);
  transition: var(--transition);
}

.stat-card:hover .sc-icon { background: var(--accent-light); color: var(--accent); }

.sc-value {
  font-family: var(--font-display);
  font-size: 1.65rem;
  font-weight: 700;
  color: var(--text-primary);
  letter-spacing: -0.03em;
  line-height: 1;
}

.sc-unit {
  font-family: var(--font-body);
  font-size: 0.8rem;
  font-weight: 400;
  color: var(--text-muted);
  margin-left: 4px;
}

/* ============================================================
   HERO GRID
============================================================ */
.hero-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.hero-card {
  border-radius: var(--radius-xl);
  padding: 28px 28px 26px;
  position: relative;
  overflow: hidden;
  animation: fadeUp 0.5s ease 0.2s backwards;
}

/* AI Card */
.hero-ai {
  background: var(--accent);
}

.hero-ai::before {
  content: '';
  position: absolute;
  top: -60px; right: -60px;
  width: 220px; height: 220px;
  background: radial-gradient(circle, rgba(255,255,255,0.12), transparent 70%);
  pointer-events: none;
}

.hero-ai::after {
  content: '';
  position: absolute;
  bottom: -40px; left: -40px;
  width: 160px; height: 160px;
  background: radial-gradient(circle, rgba(109,40,217,0.35), transparent 70%);
  pointer-events: none;
}

/* Plan Card */
.hero-plan-standart { background: var(--surface); border: 1px solid var(--border); }
.hero-plan-premium  { background: linear-gradient(135deg, #1e1b4b, #312e81); }
.hero-plan-business { background: var(--text-primary); }

.h-tag {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 0.68rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.12em;
  margin-bottom: 10px;
  padding: 4px 10px;
  border-radius: 100px;
}

.hero-ai .h-tag         { background: rgba(255,255,255,0.15); color: rgba(255,255,255,0.8); }
.hero-plan-standart .h-tag { background: var(--surface-2); color: var(--text-muted); }
.hero-plan-premium .h-tag  { background: rgba(255,255,255,0.1); color: rgba(255,255,255,0.65); }
.hero-plan-business .h-tag { background: rgba(255,255,255,0.1); color: rgba(255,255,255,0.5); }

.h-title {
  font-family: var(--font-display);
  font-size: 1.45rem;
  font-weight: 800;
  letter-spacing: -0.025em;
  line-height: 1.2;
  margin-bottom: 20px;
}

.hero-ai .h-title         { color: white; }
.hero-plan-standart .h-title { color: var(--text-primary); }
.hero-plan-premium .h-title  { color: white; }
.hero-plan-business .h-title { color: white; }

.h-btn {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  font-size: 0.83rem;
  font-weight: 600;
  border-radius: 100px;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  text-decoration: none;
  transition: var(--transition);
  font-family: inherit;
  position: relative;
  z-index: 1;
}

.hero-ai .h-btn {
  background: white;
  color: var(--accent);
}

.hero-ai .h-btn:hover {
  box-shadow: 0 8px 28px rgba(255,255,255,0.3);
  transform: translateY(-1px);
  color: var(--accent);
}

.hero-plan-standart .h-btn {
  background: var(--text-primary);
  color: white;
}

.hero-plan-standart .h-btn:hover {
  background: #1e293b;
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
  color: white;
}

.hero-plan-premium .h-btn,
.hero-plan-business .h-btn {
  background: rgba(255,255,255,0.12);
  color: rgba(255,255,255,0.85);
  border: 1px solid rgba(255,255,255,0.15);
  cursor: default;
}

/* ============================================================
   EMPTY SHOP STATE
============================================================ */
.empty-shop {
  background: var(--surface);
  border: 2px dashed var(--border);
  border-radius: var(--radius-xl);
  padding: 64px 40px;
  text-align: center;
  margin-bottom: 16px;
  animation: fadeUp 0.5s ease;
}

.empty-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 18px;
  background: var(--surface-2);
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26px;
  color: var(--text-muted);
}

.empty-shop h4 {
  font-family: var(--font-display);
  font-size: 1.2rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.empty-shop p {
  color: var(--text-secondary);
  font-size: 0.88rem;
  margin-bottom: 24px;
  max-width: 320px;
  margin-left: auto;
  margin-right: auto;
}

.btn-primary {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  background: var(--accent);
  color: white;
  font-size: 0.85rem;
  font-weight: 600;
  border-radius: 100px;
  padding: 11px 24px;
  border: none;
  cursor: pointer;
  text-decoration: none;
  transition: var(--transition);
  font-family: inherit;
}

.btn-primary:hover {
  background: var(--accent-hover);
  box-shadow: 0 8px 28px rgba(29,78,216,0.3);
  transform: translateY(-1px);
  color: white;
}

/* ============================================================
   CHART CARD
============================================================ */
.chart-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-xl);
  padding: 26px 28px;
  animation: fadeUp 0.5s ease 0.3s backwards;
}

.chart-hdr {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 22px;
  flex-wrap: wrap;
}

.chart-hdr-left .chart-title {
  font-family: var(--font-display);
  font-size: 0.95rem;
  font-weight: 700;
  color: var(--text-primary);
  letter-spacing: -0.01em;
}

.chart-hdr-left .chart-sub {
  font-size: 0.77rem;
  color: var(--text-muted);
  margin-top: 3px;
}

.filter-tabs {
  display: flex;
  align-items: center;
  background: var(--surface-2);
  border-radius: 100px;
  padding: 3px;
  gap: 2px;
}

.filter-tab {
  font-size: 0.74rem;
  font-weight: 600;
  color: var(--text-secondary);
  background: transparent;
  border: none;
  border-radius: 100px;
  padding: 6px 14px;
  cursor: pointer;
  transition: var(--transition);
  letter-spacing: 0.04em;
  font-family: inherit;
}

.filter-tab:hover:not(.active) { color: var(--text-primary); }

.filter-tab.active {
  background: var(--surface);
  color: var(--text-primary);
  box-shadow: var(--shadow-xs);
}

.chart-canvas-wrap {
  position: relative;
  height: 310px;
}

.no-data-msg {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: var(--text-muted);
  font-size: 0.85rem;
}

.no-data-msg i { font-size: 28px; opacity: 0.35; }

/* ============================================================
   UPGRADE CARD
============================================================ */
.upgrade-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-xl);
  padding: 36px;
  text-align: center;
  animation: fadeUp 0.5s ease 0.3s backwards;
}

.upgrade-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 0.7rem;
  font-weight: 600;
  color: var(--gold);
  background: #fef9c3;
  border-radius: 100px;
  padding: 5px 12px;
  margin-bottom: 14px;
  text-transform: uppercase;
  letter-spacing: 0.08em;
}

.upgrade-card h4 {
  font-family: var(--font-display);
  font-size: 1.1rem;
  font-weight: 700;
  margin-bottom: 7px;
  color: var(--text-primary);
}

.upgrade-card p {
  font-size: 0.86rem;
  color: var(--text-secondary);
  margin-bottom: 22px;
  max-width: 380px;
  margin-left: auto;
  margin-right: auto;
}

/* ============================================================
   AI MODAL
============================================================ */
.ai-modal-overlay {
  display: none;
  position: fixed;
  inset: 0;
  z-index: 9999;
  background: rgba(13,12,10,0.72);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.ai-modal-overlay.open { display: flex; }

.ai-modal-box {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-2xl);
  width: 100%;
  max-width: 1080px;
  max-height: 92vh;
  overflow-y: auto;
  position: relative;
  animation: modalUp 0.38s cubic-bezier(0.4,0,0.2,1);
  box-shadow: var(--shadow-lg);
}

@keyframes modalUp {
  from { opacity: 0; transform: translateY(24px) scale(0.97); }
  to   { opacity: 1; transform: translateY(0)  scale(1); }
}

.ai-modal-box::-webkit-scrollbar { width: 5px; }
.ai-modal-box::-webkit-scrollbar-track { background: var(--surface-2); border-radius: 3px; }
.ai-modal-box::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }

.ai-close-btn {
  position: absolute;
  top: 18px; right: 18px;
  width: 34px; height: 34px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--border);
  background: var(--surface);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  font-size: 17px;
  transition: var(--transition);
  z-index: 10;
}

.ai-close-btn:hover { background: var(--surface-2); color: var(--text-primary); }

/* Loader */
.ai-loader-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 90px 40px;
  gap: 22px;
}

.spinner {
  position: relative;
  width: 60px; height: 60px;
}

.spinner::before,
.spinner::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  border: 2.5px solid transparent;
}

.spinner::before {
  inset: 0;
  border-top-color: var(--accent);
  animation: spin 1s linear infinite;
}

.spinner::after {
  inset: 10px;
  border-top-color: var(--purple);
  animation: spin 0.65s linear infinite reverse;
}

@keyframes spin { to { transform: rotate(360deg); } }

.ai-loader-label {
  text-align: center;
  font-size: 0.9rem;
  color: var(--text-secondary);
  line-height: 1.6;
}

.ai-loader-label strong { display: block; color: var(--text-primary); font-size: 1rem; margin-bottom: 4px; }

/* AI Results */
.ai-body { padding: 36px; }

.ai-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 28px;
  flex-wrap: wrap;
  gap: 12px;
}

.ai-title {
  font-family: var(--font-display);
  font-size: 1.4rem;
  font-weight: 800;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 10px;
  letter-spacing: -0.02em;
}

.ai-title i { color: var(--accent); }

.live-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 0.7rem;
  font-weight: 600;
  color: var(--accent);
  background: var(--accent-light);
  border: 1px solid rgba(29,78,216,0.15);
  border-radius: 100px;
  padding: 5px 12px;
  text-transform: uppercase;
  letter-spacing: 0.06em;
}

.live-dot {
  width: 6px; height: 6px;
  background: var(--accent);
  border-radius: 50%;
  animation: pulseDot 2s ease-in-out infinite;
}

@keyframes pulseDot { 0%,100% { opacity:1; } 50% { opacity:0.35; } }

/* Metrics */
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-bottom: 22px;
}

.metric-tile {
  background: var(--surface-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 18px 16px;
  transition: var(--transition);
  animation: fadeUp 0.4s ease backwards;
}

.metric-tile:nth-child(1) { animation-delay: 0.05s; }
.metric-tile:nth-child(2) { animation-delay: 0.10s; }
.metric-tile:nth-child(3) { animation-delay: 0.15s; }
.metric-tile:nth-child(4) { animation-delay: 0.20s; }
.metric-tile:hover { border-color: var(--border-hover); background: var(--surface); }

.m-label {
  font-size: 0.68rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.09em;
  color: var(--text-muted);
  margin-bottom: 8px;
}

.m-value {
  font-family: var(--font-display);
  font-size: 1.2rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 5px;
  letter-spacing: -0.02em;
  line-height: 1;
}

.m-sub {
  font-size: 0.73rem;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  gap: 4px;
}

.positive { color: var(--success) !important; }
.negative { color: var(--danger) !important; }

/* Forecast */
.forecast-box {
  background: var(--surface-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 22px;
  margin-bottom: 20px;
}

.box-hdr {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.box-title {
  font-family: var(--font-display);
  font-size: 0.85rem;
  font-weight: 700;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 8px;
}

.box-title i { color: var(--accent); }

.box-badge {
  font-size: 0.68rem;
  font-weight: 600;
  color: var(--purple);
  background: var(--purple-light);
  border-radius: 100px;
  padding: 4px 10px;
  text-transform: uppercase;
  letter-spacing: 0.06em;
}

.forecast-chart-wrap { height: 220px; position: relative; }

/* Recommendations */
.recs-box { margin-bottom: 22px; }

.recs-box .box-title {
  font-family: var(--font-display);
  font-size: 0.85rem;
  font-weight: 700;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.rec-item {
  display: flex;
  gap: 12px;
  background: var(--surface-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-md);
  padding: 15px;
  margin-bottom: 8px;
  transition: var(--transition);
  animation: slideLeft 0.4s ease backwards;
}

.rec-item:nth-child(1) { animation-delay: 0.1s; }
.rec-item:nth-child(2) { animation-delay: 0.2s; }
.rec-item:nth-child(3) { animation-delay: 0.3s; }
.rec-item:hover { border-color: var(--border-hover); }

.rec-icon {
  width: 36px; height: 36px;
  border-radius: var(--radius-sm);
  background: var(--accent-light);
  color: var(--accent);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.rec-body h6 {
  font-size: 0.85rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 3px;
}

.rec-body p {
  font-size: 0.79rem;
  color: var(--text-secondary);
  line-height: 1.55;
}

/* Recommendation level rangli chap chiziq */
.rec-item.rec-danger  { border-left: 3px solid #dc3545; }
.rec-item.rec-warning { border-left: 3px solid #f59e0b; }
.rec-item.rec-success { border-left: 3px solid #16a34a; }
.rec-item.rec-info    { border-left: 3px solid #2563eb; }
.rec-item.rec-danger  .rec-icon { background: rgba(220,53,69,0.1);  color: #dc3545; }
.rec-item.rec-warning .rec-icon { background: rgba(245,158,11,0.1); color: #d97706; }
.rec-item.rec-success .rec-icon { background: rgba(22,163,74,0.1);  color: #16a34a; }
.rec-item.rec-info    .rec-icon { background: rgba(37,99,235,0.1);  color: #2563eb; }

/* Real signal context block (recommendations ustida) */
.rec-context {
  background: var(--surface-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-md);
  padding: 14px 16px;
  margin-bottom: 14px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 10px 18px;
}
.rec-ctx-row {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.78rem;
  color: var(--text-secondary);
  flex-wrap: wrap;
}
.rec-ctx-row i { color: var(--accent); }
.rec-ctx-row strong {
  color: var(--text-primary);
  font-weight: 700;
  margin-left: 2px;
}
.rec-ctx-row small {
  color: var(--text-secondary);
  opacity: 0.7;
  font-size: 0.72rem;
}

/* Prediction */
.pred-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.pred-tile {
  background: var(--surface-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 22px;
  text-align: center;
  transition: var(--transition);
}

.pred-tile:hover { border-color: var(--border-hover); background: var(--surface); }

.pred-tile i { font-size: 22px; color: var(--accent); margin-bottom: 10px; }
.pred-label { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 8px; }

.pred-value {
  font-family: var(--font-display);
  font-size: 1.35rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
  letter-spacing: -0.02em;
}

.pred-bar { height: 4px; background: var(--border); border-radius: 100px; overflow: hidden; margin-bottom: 6px; }
.pred-fill { height: 100%; background: var(--accent); border-radius: 100px; animation: fillUp 1.2s ease forwards; }
@keyframes fillUp { from { width: 0; } }

.pred-conf { font-size: 0.72rem; color: var(--text-muted); }
.pred-conf span { color: var(--accent); font-weight: 600; }

/* ============================================================
   ANIMATIONS
============================================================ */
@keyframes fadeUp {
  from { opacity: 0; transform: translateY(14px); }
  to   { opacity: 1; transform: translateY(0); }
}

@keyframes slideDown {
  from { opacity: 0; transform: translateY(-10px); }
  to   { opacity: 1; transform: translateY(0); }
}

@keyframes slideLeft {
  from { opacity: 0; transform: translateX(-14px); }
  to   { opacity: 1; transform: translateX(0); }
}

/* ============================================================
   RESPONSIVE
============================================================ */
@media (max-width: 1100px) {
  .metrics-grid { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 900px) {
  .hero-grid  { grid-template-columns: 1fr; }
  .stats-row  { grid-template-columns: 1fr 1fr; }
  .topbar-center { display: none; }
  .page { padding: 20px 20px 60px; }
  .topbar { display:none; }
}

@media (max-width: 640px) {
  .stats-row       { grid-template-columns: 1fr; }
  .metrics-grid    { grid-template-columns: 1fr 1fr; }
  .pred-grid       { grid-template-columns: 1fr; }
  .ramadan-wrap    { flex-direction: column; align-items: flex-start; }
  .ramadan-prayers { flex-wrap: wrap; }
  .ai-body         { padding: 20px 16px; }
  .ai-title        { font-size: 1.15rem; }
  .t-block .t-num  { font-size: 2rem; }
  .chart-hdr       { flex-direction: column; align-items: flex-start; }
}

/* ============================================================
   BUSINESS GOLD THEME
============================================================ */

.theme-business {

  /* primary accent gold */
  --accent: #D4AF37;
  --accent-hover: #B8962E;
  --accent-light: rgba(212,175,55,0.12);
  --accent-mid: rgba(212,175,55,0.18);

  /* premium gradient */
  --gold-gradient: linear-gradient(
    135deg,
    #F6E27A,
    #D4AF37,
    #C5A028
  );
}

/* ===== PREMIUM GOLD MATERIAL ===== */

.theme-business {
  --gold-1:#FFF3B0;
  --gold-2:#F6E27A;
  --gold-3:#D4AF37;
  --gold-4:#B8962E;
  --gold-5:#7A5C12;
}

.theme-business .gold-surface {
  background:
    linear-gradient(
      120deg,
      var(--gold-1) 0%,
      var(--gold-2) 18%,
      var(--gold-3) 38%,
      var(--gold-2) 55%,
      var(--gold-4) 75%,
      var(--gold-5) 100%
    );
}

/* ===== TOPBAR GOLD ACCENT ===== */
.theme-business .logo-accent,
.theme-business .logo-dot {
  background: var(--accent);
  color: var(--accent);
}

/* ===== PRIMARY BUTTON ===== */
.theme-business .btn-primary {
  background: var(--gold-gradient);
  color: #1a1a1a;
  font-weight: 600;
}

.theme-business .btn-primary:hover {
  box-shadow: 0 10px 30px rgba(212,175,55,0.35);
}

/* ===== STAT CARD PREMIUM LINE ===== */
.theme-business .stat-card::after {
  background: var(--gold-gradient);
}

/* ===== ICON HOVER ===== */
.theme-business .stat-card:hover .sc-icon {
  background: rgba(212,175,55,0.12);
  color: var(--accent);
}
.theme-business .stat-card::before{
  content:"";
  position:absolute;
  inset:0;
  border-radius:inherit;
  padding:1px;
  background:linear-gradient(
    135deg,
    rgba(212,175,55,.35),
    transparent 40%
  );
  -webkit-mask:
      linear-gradient(#000 0 0) content-box,
      linear-gradient(#000 0 0);
  -webkit-mask-composite:xor;
  mask-composite:exclude;
  pointer-events:none;
}
/* ===== AVATAR PREMIUM ===== */
.theme-business .avatar {
  background: var(--gold-gradient);
}

/* ===== AI CARD GOLD GLOW ===== */
.theme-business .hero-ai {
  background: linear-gradient(135deg,#1a1a1a,#2b2b2b);
}

.theme-business .hero-ai::after {
  background: radial-gradient(circle,
    rgba(212,175,55,0.35),
    transparent 70%);
}

/* ===== PREMIUM GLOW (SUBTLE) ===== */
.theme-business .stat-card,
.theme-business .chart-card {
  box-shadow:
    0 0 0 1px rgba(212,175,55,0.08),
    0 8px 30px rgba(212,175,55,0.08);
}

.theme-business .btn-primary:hover{
  transform:translateY(-2px) scale(1.01);
}
/* ===== GOLD SHINE ANIMATION ===== */

.theme-business .hero-plan-business {
  position: relative;
  overflow: hidden;
}

.theme-business .hero-plan-business::before {
  content:"";
  position:absolute;
  top:0;
  left:-120%;
  width:80%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,0.25),
    transparent
  );
  transform:skewX(-25deg);
  animation: goldShine 6s infinite;
}

@keyframes goldShine {
  0% { left:-120%; }
  40% { left:130%; }
  100% { left:130%; }
}

.theme-business .topbar-center a.active{
  background:linear-gradient(135deg,#F6E27A,#D4AF37);
  color:#1a1a1a;
}

.business-badge{
  position:absolute;
  top:18px;
  right:18px;
  padding:6px 14px;
  font-size:11px;
  font-weight:700;
  letter-spacing:.12em;
  border-radius:999px;
  color:#1a1a1a;
  background:linear-gradient(135deg,#F6E27A,#D4AF37);
  box-shadow:
    0 0 0 1px rgba(255,255,255,.2) inset,
    0 6px 20px rgba(212,175,55,.35);
}

/* ============================================================
   BUSINESS — PREMIUM 4D EFFECTS
============================================================ */

/* Animated gold mesh gradient backdrop */
.theme-business::before {
  content: "";
  position: fixed; inset: 0; z-index: -2;
  background:
    radial-gradient(ellipse 80% 60% at 15% 20%, rgba(246,226,122,.18) 0%, transparent 50%),
    radial-gradient(ellipse 70% 50% at 85% 75%, rgba(212,175,55,.16) 0%, transparent 55%),
    radial-gradient(ellipse 60% 45% at 50% 50%, rgba(184,150,46,.10) 0%, transparent 60%),
    radial-gradient(circle  at 70% 25%, rgba(255,243,176,.10) 0%, transparent 35%);
  animation: bizMeshShift 28s ease-in-out infinite;
  pointer-events: none;
  filter: blur(20px);
}
@keyframes bizMeshShift {
  0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); }
  25%      { transform: translate(-2%, 3%) rotate(2deg) scale(1.05); }
  50%      { transform: translate(3%, -2%) rotate(-1deg) scale(.97); }
  75%      { transform: translate(-1%, -2%) rotate(1deg) scale(1.03); }
}

/* Floating gold particles */
.biz-particles {
  position: fixed; inset: 0; z-index: 0;
  pointer-events: none; overflow: hidden;
}
.biz-particle {
  position: absolute; border-radius: 50%;
  background: radial-gradient(circle, rgba(246,226,122,.85), rgba(212,175,55,.2) 40%, transparent 70%);
  box-shadow: 0 0 12px rgba(212,175,55,.45);
  animation: bizFloat var(--dur, 14s) ease-in-out infinite;
  will-change: transform, opacity;
}
@keyframes bizFloat {
  0%   { transform: translate(0, 100vh) scale(.4); opacity: 0; }
  10%  { opacity: .9; }
  50%  { transform: translate(calc(var(--dx,0) * 1px), 50vh) scale(1); }
  90%  { opacity: .6; }
  100% { transform: translate(calc(var(--dx,0) * 2px), -10vh) scale(.5); opacity: 0; }
}

/* Cursor spotlight */
.biz-cursor {
  position: fixed; pointer-events: none; z-index: 1;
  width: 700px; height: 700px;
  background: radial-gradient(circle, rgba(212,175,55,.10) 0%, rgba(212,175,55,.04) 30%, transparent 60%);
  border-radius: 50%; transform: translate(-50%, -50%);
  transition: opacity .35s ease;
  mix-blend-mode: screen;
  opacity: 0;
}
body.theme-business.biz-cursor-active .biz-cursor { opacity: 1; }

/* 3D tilt-ready cards */
.theme-business .stat-card,
.theme-business .chart-card,
.theme-business .hero-ai,
.theme-business .hero-plan-business {
  transform-style: preserve-3d;
  transition: transform .35s cubic-bezier(.34, 1.56, .64, 1), box-shadow .35s ease;
  position: relative;
  will-change: transform;
}
.theme-business .stat-card,
.theme-business .chart-card { z-index: 2; }

/* Shimmer sweep across cards */
.theme-business .biz-shimmer {
  position: absolute; inset: 0; pointer-events: none;
  border-radius: inherit; overflow: hidden;
}
.theme-business .biz-shimmer::before {
  content: ""; position: absolute; top: 0; left: -150%; width: 50%; height: 100%;
  background: linear-gradient(105deg, transparent 30%, rgba(255,243,176,.45) 50%, transparent 70%);
  transform: skewX(-15deg);
  transition: left .9s ease;
}
.theme-business .stat-card:hover .biz-shimmer::before,
.theme-business .chart-card:hover .biz-shimmer::before { left: 150%; }

/* Glow halo on hero-plan card */
.theme-business .hero-plan-business {
  box-shadow:
    0 0 0 1px rgba(212,175,55,.25),
    0 24px 60px rgba(212,175,55,.18),
    0 8px 24px rgba(0,0,0,.35);
  animation: bizEntrance .7s cubic-bezier(.22, 1, .36, 1) backwards, bizHaloPulse 5s ease-in-out 1s infinite;
}
@keyframes bizHaloPulse {
  0%, 100% { box-shadow: 0 0 0 1px rgba(212,175,55,.25), 0 24px 60px rgba(212,175,55,.18), 0 8px 24px rgba(0,0,0,.35); }
  50%      { box-shadow: 0 0 0 1px rgba(255,243,176,.4),  0 30px 80px rgba(212,175,55,.32), 0 8px 24px rgba(0,0,0,.4); }
}

/* BUSINESS badge — pulse + shine */
.theme-business .business-badge {
  animation: bizBadgePulse 2.4s ease-in-out infinite;
  position: absolute; overflow: hidden;
  z-index: 3;
}
@keyframes bizBadgePulse {
  0%, 100% { box-shadow: 0 0 0 1px rgba(255,255,255,.2) inset, 0 0 0 0 rgba(212,175,55,.6), 0 6px 20px rgba(212,175,55,.35); }
  50%      { box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset, 0 0 0 10px rgba(212,175,55,0),  0 8px 28px rgba(212,175,55,.5); }
}
.theme-business .business-badge::after {
  content: ""; position: absolute; top: 0; left: -100%; width: 60%; height: 100%;
  background: linear-gradient(120deg, transparent 30%, rgba(255,255,255,.7) 50%, transparent 70%);
  animation: bizBadgeShine 3.5s ease-in-out infinite;
}
@keyframes bizBadgeShine {
  0%, 100% { left: -100%; }
  50%      { left: 200%; }
}

/* Stagger entrance */
.theme-business .stat-card,
.theme-business .chart-card,
.theme-business .hero-ai {
  animation: bizEntrance .7s cubic-bezier(.22, 1, .36, 1) backwards;
}
.theme-business .stat-card:nth-of-type(1) { animation-delay: .05s; }
.theme-business .stat-card:nth-of-type(2) { animation-delay: .12s; }
.theme-business .stat-card:nth-of-type(3) { animation-delay: .19s; }
.theme-business .stat-card:nth-of-type(4) { animation-delay: .26s; }
.theme-business .chart-card { animation-delay: .35s; }
.theme-business .hero-ai { animation-delay: .45s; }
@keyframes bizEntrance {
  from { opacity: 0; transform: translateY(20px) scale(.97); filter: blur(8px); }
  to   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
}

/* Gradient gold text on numbers */
.theme-business .t-num,
.theme-business .sc-num {
  background: linear-gradient(135deg, #FFF3B0 0%, #D4AF37 60%, #B8962E 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  filter: drop-shadow(0 1px 2px rgba(212,175,55,.2));
}

/* Hero plan border shine */
.theme-business .hero-plan-business::before {
  background: linear-gradient(90deg, transparent, rgba(246,226,122,.6) 30%, rgba(212,175,55,.8) 50%, rgba(246,226,122,.6) 70%, transparent);
  background-size: 200% 100%;
  animation: bizBorderShine 4s linear infinite;
}
@keyframes bizBorderShine { from { background-position: -100% 0; } to { background-position: 200% 0; } }

@media (prefers-reduced-motion: reduce) {
  .theme-business::before,
  .theme-business .business-badge,
  .theme-business .hero-plan-business,
  .biz-particle { animation: none !important; }
}

</style>

<body class="<?= $userPricing === 'BUSINESS' ? 'theme-business' : '' ?>">
<?php if ($userPricing === 'BUSINESS'): ?>
  <div class="biz-particles" id="bizParticles" aria-hidden="true"></div>
  <div class="biz-cursor" id="bizCursor" aria-hidden="true"></div>
<?php endif; ?>
<?php include_once($_SERVER["DOCUMENT_ROOT"] . "/business/includes/nav.php"); ?>
<!-- ============================================================
     AI TAHLIL MODAL
============================================================ -->
<div class="ai-modal-overlay" id="aiModal">
  <div class="ai-modal-box">
    <button class="ai-close-btn" onclick="closeAi()" title="Yopish">
      <i class="bi bi-x"></i>
    </button>

    <!-- Loader -->
    <div class="ai-loader-wrap" id="aiLoader">
      <div class="spinner"></div>
      <div class="ai-loader-label">
        <strong>AI tahlil qilmoqda...</strong>
        Biznes ma'lumotlaringiz qayta ishlanmoqda. Biroz sabr qiling.
      </div>
    </div>

    <!-- Results -->
    <div class="ai-body" id="aiResults" style="display:none;">
      <div class="ai-header">
        <div class="ai-title">
          <i class="bi bi-stars"></i>
          AI Business Tahlil
        </div>
        <div class="live-badge"><span class="live-dot"></span> Jonli tahlil</div>
      </div>

      <!-- Metrics -->
      <div class="metrics-grid">
        <div class="metric-tile">
          <div class="m-label">O'sish sur'ati</div>
          <div class="m-value" id="aiGrowth">—</div>
          <div class="m-sub" id="aiGrowthSub">—</div>
        </div>
        <div class="metric-tile">
          <div class="m-label">O'rtacha kunlik</div>
          <div class="m-value" id="aiAvg">—</div>
          <div class="m-sub"><i class="bi bi-calendar3"></i> So'nggi 30 kun</div>
        </div>
        <div class="metric-tile">
          <div class="m-label">Eng yaxshi kun</div>
          <div class="m-value" id="aiBest">—</div>
          <div class="m-sub" id="aiBestDate"><i class="bi bi-trophy"></i> —</div>
        </div>
        <div class="metric-tile">
          <div class="m-label">Faollik darajasi</div>
          <div class="m-value" id="aiActivity">—</div>
          <div class="m-sub" id="aiActivitySub">—</div>
        </div>
      </div>

      <!-- Forecast chart -->
      <div class="forecast-box">
        <div class="box-hdr">
          <div class="box-title"><i class="bi bi-bar-chart-line"></i> Keyingi oy uchun prognoz</div>
          <span class="box-badge">AI bashorati</span>
        </div>
        <div class="forecast-chart-wrap">
          <canvas id="forecastCanvas"></canvas>
        </div>
      </div>

      <!-- Recommendations -->
      <div class="recs-box">
        <div class="box-title"><i class="bi bi-lightbulb" style="color:var(--warning)"></i> AI tavsiylari</div>
        <div id="aiRecs"></div>
      </div>

      <!-- Predictions -->
      <div class="pred-grid">
        <div class="pred-tile">
          <i class="bi bi-calendar-range"></i>
          <div class="pred-label">Keyingi 7 kun</div>
          <div class="pred-value" id="aiW7">—</div>
          <div class="pred-bar"><div class="pred-fill" id="aiW7Fill"></div></div>
          <div class="pred-conf">Ishonch: <span id="aiW7Conf">—</span></div>
        </div>
        <div class="pred-tile">
          <i class="bi bi-calendar-month"></i>
          <div class="pred-label">Keyingi 30 kun</div>
          <div class="pred-value" id="aiM30">—</div>
          <div class="pred-bar"><div class="pred-fill" id="aiM30Fill"></div></div>
          <div class="pred-conf">Ishonch: <span id="aiM30Conf">—</span></div>
        </div>
      </div>
    </div><!-- /ai-body -->
  </div>
</div>
 <?php if ($userPricing === 'BUSINESS'): ?>
<!-- <span class="business-badge">BUSINESS</span> -->
<?php endif; ?>
<!-- ============================================================
     PAGE CONTENT
============================================================ -->
<main class="page">

  <!-- RAMADAN TIMER -->
<!--   <div class="ramadan-wrap">
  <div class="ramadan-info">
    <h5>Ramazon muborak</h5>
    <p id="ramadanTitle">Yuklanmoqda...</p>
  </div>
  <div class="ramadan-timer">
    <div class="t-block">
      <span class="t-num" id="tHours">00</span>
      <span class="t-unit">Soat</span>
    </div>
    <span class="t-sep">:</span>
    <div class="t-block">
      <span class="t-num" id="tMinutes">00</span>
      <span class="t-unit">Daqiqa</span>
    </div>
    <span class="t-sep">:</span>
    <div class="t-block">
      <span class="t-num" id="tSeconds">00</span>
      <span class="t-unit">Soniya</span>
    </div>
  </div>
  <div class="ramadan-prayers">
    <div class="prayer-item">
      <span class="p-label">Saharlik</span>
      <span class="p-val" id="saharlikTime">--:--</span>
    </div>
    <div class="prayer-sep"></div>
    <div class="prayer-item">
      <span class="p-label">Iftorlik</span>
      <span class="p-val" id="iftorlikTime">--:--</span>
    </div>
  </div>
</div> -->

  <!-- ALERTS -->
  <div class="alert-stack">

    <?php if ($passportStatus === 0): ?>
    <div class="alert-banner passport">
      <div class="alert-left">
        <div class="alert-icon-wrap"><i class="bi bi-person-bounding-box"></i></div>
        <div class="alert-text">
          <strong>Shaxsni tasdiqlash talab qilinadi</strong>
          <span>To'lovlarni qabul qilish uchun identifikatsiyadan o'ting</span>
        </div>
      </div>
      <a href="/identification" class="alert-cta">Davom etish</a>
    </div>

    <?php elseif ($passportStatus === 2): ?>
    <div class="alert-banner rejected">
      <div class="alert-left">
        <div class="alert-icon-wrap"><i class="bi bi-x-circle"></i></div>
        <div class="alert-text">
          <strong>Shaxsni tasdiqlash rad etildi</strong>
          <span>Iltimos, qayta identifikatsiya qiling</span>
        </div>
      </div>
      <a href="/identification" class="alert-cta">Qayta urinish</a>
    </div>

    <?php elseif ($passportStatus === 1): ?>
    <div class="alert-banner pending">
      <div class="alert-left">
        <div class="alert-icon-wrap"><i class="bi bi-hourglass-split"></i></div>
        <div class="alert-text">
          <strong>Shaxsni tasdiqlash tekshirilmoqda</strong>
          <span>Bu 1–3 ish kunini olishi mumkin</span>
        </div>
      </div>
      <span class="alert-cta">Kuting</span>
    </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['message'])): ?>
    <div class="alert-banner session-msg">
      <div class="alert-left">
        <div class="alert-icon-wrap"><i class="bi bi-info-circle"></i></div>
        <div class="alert-text">
          <strong><?= htmlspecialchars($_SESSION['message']) ?></strong>
        </div>
      </div>
    </div>
    <?php unset($_SESSION['message']); ?>
    <?php endif; ?>

  </div><!-- /alert-stack -->

  <!-- EMPTY SHOP -->
  <?php if ($activeShops === 0): ?>
  <div class="empty-shop">
    <div class="empty-icon"><i class="bi bi-shop"></i></div>
    <h4>Biznes kassa yarating</h4>
    <p>Birinchi to'lovingizni qabul qilish uchun yangi biznes kassangizni yarating.</p>
    <a href="/merchant/create" class="btn-primary">
      <i class="bi bi-plus-circle"></i> Yangi kassa
    </a>
  </div>
  <?php endif; ?>

  <!-- STAT CARDS -->
  <div class="stats-row">
    <div class="stat-card">
      <div class="sc-top">
        <span class="sc-label">Kassalar</span>
        <div class="sc-icon"><i class="bi bi-shop"></i></div>
      </div>
      <div class="sc-value">
        <?= number_format($activeShops, 0, '.', ' ') ?>
        <span class="sc-unit">ta</span>
      </div>
    </div>
    <div class="stat-card">
      <div class="sc-top">
        <span class="sc-label">Tranzaksiyalar</span>
        <div class="sc-icon"><i class="bi bi-arrow-left-right"></i></div>
      </div>
      <div class="sc-value">
        <?= number_format($transactionCount, 0, '.', ' ') ?>
        <span class="sc-unit">ta</span>
      </div>
    </div>
    <div class="stat-card">
      <div class="sc-top">
        <span class="sc-label">Bugungi tushum</span>
        <div class="sc-icon"><i class="bi bi-cash-stack"></i></div>
      </div>
      <div class="sc-value">
        <?= number_format($todayTurnover, 0, '.', ' ') ?>
        <span class="sc-unit">UZS</span>
      </div>
    </div>
  </div>

  <?php if (!empty($byok_kassas)): ?>
  <style>
  .byok-dash { background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); border: 1px solid #fcd34d; border-radius: 14px; padding: 18px 20px; margin: 0 0 26px 0; position: relative; overflow: hidden; }
  .byok-dash::before { content:''; position:absolute; inset:0 0 auto 0; height:3px; background: linear-gradient(90deg,#fbbf24,#f59e0b,#d97706); }
  .byok-dash h5 { font-weight: 800; color: #78350f; margin: 0 0 14px 0; font-size: 16px; display:flex; align-items:center; gap:8px; }
  .byok-dash h5 i { color: #b45309; }
  .byok-dash h5 .pill { background:#b45309; color:#fff; font-size:11px; padding:2px 8px; border-radius:99px; font-weight:800; letter-spacing:.04em; }
  .byok-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; }
  .byok-tile { background: #fff; border: 1px solid #fde68a; border-radius: 10px; padding: 14px 16px; transition: .15s; }
  .byok-tile:hover { border-color:#f59e0b; box-shadow: 0 2px 8px rgba(217,119,6,.1); }
  .byok-tile-h { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
  .byok-tile-h .nm { font-weight:700; color:#1f2937; font-size:14px; flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .byok-tile-h .mid { font-family: monospace; font-size:11px; color:#9ca3af; }
  .byok-stat { display:flex; align-items:baseline; gap:6px; margin-bottom:6px; }
  .byok-stat .num { font-size: 22px; font-weight: 800; color: #92400e; font-variant-numeric: tabular-nums; }
  .byok-stat .of  { font-size: 13px; color: #b45309; font-weight: 600; }
  .byok-stat .sub { font-size: 11px; color: #78350f; margin-left: auto; }
  .byok-bar { height: 6px; background: #fef3c7; border-radius: 99px; overflow: hidden; margin: 8px 0 6px; }
  .byok-bar > div { height: 100%; background: linear-gradient(90deg, #10b981, #059669); transition: width .4s; }
  .byok-bar.warn > div { background: linear-gradient(90deg, #f59e0b, #d97706); }
  .byok-bar.crit > div { background: linear-gradient(90deg, #dc2626, #991b1b); }
  .byok-meta { display:flex; justify-content:space-between; font-size:11.5px; color:#78350f; margin-top:4px; gap:8px; }
  .byok-meta .lnk { color:#b45309; font-weight:700; text-decoration:none; white-space:nowrap; }
  .byok-meta .lnk:hover { text-decoration:underline; }
  .byok-noplan { padding:12px 14px; background:#fff; border:1px dashed #f59e0b; border-radius:8px; color:#92400e; font-size:12.5px; display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
  .byok-noplan .btn { background:#b45309; color:#fff; padding:6px 12px; border-radius:6px; font-size:12px; font-weight:700; text-decoration:none; white-space:nowrap; }
  .byok-noplan .btn:hover { background:#92400e; color:#fff; }
  </style>
  <div class="byok-dash">
    <h5>
      <i class="bi bi-key-fill"></i>
      BYOK kassalaringiz va obuna
      <span class="pill"><?= count($byok_kassas) ?> ta kassa</span>
    </h5>
    <div class="byok-grid">
      <?php foreach ($byok_kassas as $bk):
          $k = $bk['kassa']; $q = $bk['quota'];
      ?>
        <div class="byok-tile">
          <div class="byok-tile-h">
            <div class="nm"><?= htmlspecialchars($k['business_name']) ?></div>
            <div class="mid">#<?= htmlspecialchars($k['merchant_id']) ?></div>
          </div>
          <?php if ($q):
              $quota = (int)$q['tx_quota'];
              $used  = (int)$q['tx_used'];
              $rem   = $quota === 0 ? PHP_INT_MAX : max(0, $quota - $used);
              $pct   = $quota === 0 ? 0 : min(100, round($used / max($quota,1) * 100, 1));
              $bar_cls = $pct >= 90 ? 'crit' : ($pct >= 70 ? 'warn' : '');
              $days_left = max(0, (int)round((strtotime($q['period_end']) - time()) / 86400));
          ?>
            <div class="byok-stat">
              <span class="num"><?= $quota === 0 ? '∞' : number_format($rem) ?></span>
              <span class="of">/ <?= $quota === 0 ? '∞' : number_format($quota) ?></span>
              <span class="sub">tranzaksiya qoldi</span>
            </div>
            <div class="byok-bar <?= $bar_cls ?>"><div style="width:<?= $pct ?>%"></div></div>
            <div class="byok-meta">
              <span><?= $days_left ?> kun qoldi · <?= date('d.m', strtotime($q['period_end'])) ?> gacha</span>
              <a class="lnk" href="/billing/byok-buy/?merchant_id=<?= urlencode($k['merchant_id']) ?>">Tarif almashtirish →</a>
            </div>
          <?php else: ?>
            <div class="byok-noplan">
              <span><i class="bi bi-exclamation-triangle-fill" style="color:#dc2626"></i> Faol obuna yo'q — yangi tranzaksiyalar bloklangan</span>
              <a class="btn" href="/billing/byok-buy/?merchant_id=<?= urlencode($k['merchant_id']) ?>">Tarif sotib olish</a>
            </div>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- HERO CARDS -->
  <div class="hero-grid">

    <!-- AI Card -->
    <div class="hero-card hero-ai">
      <div class="h-tag"><i class="bi bi-stars"></i> AI Tahlil</div>
      <div class="h-title">AI endi siz bilan ishlaydi</div>
      <?php if (in_array($userPricing, ['PREMIUM', 'BUSINESS'])): ?>
        <button class="h-btn" onclick="openAi()">
          <i class="bi bi-stars"></i> Boshlash
        </button>
      <?php else: ?>
        <a href="/pricing" class="h-btn">
          <i class="bi bi-arrow-up-circle"></i> Premium olish
        </a>
      <?php endif; ?>
    </div>

    <!-- Plan Card -->
    
    <?php
      $planClass = 'hero-plan-standart';
      if ($userPricing === 'PREMIUM')  $planClass = 'hero-plan-premium';
      if ($userPricing === 'BUSINESS') $planClass = 'hero-plan-business';
    ?>
   
    <div class="hero-card <?= $planClass ?>">
        
      <div class="h-tag"><i class="bi bi-patch-check"></i> Tarif rejangiz</div>
      <div class="h-title"><?= htmlspecialchars($userPricing) ?></div>
      <?php if ($userPricing === 'BUSINESS'): ?>
        <button class="h-btn" disabled>
          <i class="bi bi-patch-check"></i> Cheklovlarsiz
        </button>
      <?php elseif ($userPricing === 'PREMIUM'): ?>
        <a href="/pricing" class="h-btn">
          <i class="bi bi-arrow-up-circle"></i> Business'ga o'tish
        </a>
      <?php else: ?>
        <a href="/pricing" class="h-btn">
          <i class="bi bi-arrow-up-circle"></i> Daraja ko'tarish
        </a>
      <?php endif; ?>
    </div>

  </div>


<?php include_once($_SERVER["DOCUMENT_ROOT"] . "/includes/goals_widget.php"); ?>


  <!-- CHART SECTION -->
  <?php if (in_array($userPricing, ['PREMIUM', 'BUSINESS'])): ?>

  <div class="chart-card">
    <div class="chart-hdr">
      <div class="chart-hdr-left">
        <div class="chart-title">Tranzaksiyalar statistikasi</div>
        <div class="chart-sub">Barcha muvaffaqiyatli to'lovlar grafigi</div>
      </div>
      <div class="filter-tabs">
        <button class="filter-tab active" onclick="filterChart(event,'all')">HAMMA</button>
        <button class="filter-tab" onclick="filterChart(event,'month')">OYLIK</button>
        <button class="filter-tab" onclick="filterChart(event,'week')">HAFTA</button>
      </div>
    </div>
    <div class="chart-canvas-wrap">
      <canvas id="mainChart"></canvas>
    </div>
  </div>

  <?php else: ?>

  <div class="upgrade-card">
    <div class="upgrade-badge"><i class="bi bi-lock"></i> Cheklangan</div>
    <h4>Statistika yuqori tariflarda mavjud</h4>
    <p>Batafsil grafik va tahlillarni ko'rish uchun Premium yoki Business tarifiga o'ting.</p>
    <a href="/pricing" class="btn-primary">
      <i class="bi bi-arrow-up-circle"></i> Premiumga o'tish
    </a>
  </div>

  <?php endif; ?>

</main>

<!-- ============================================================
     SCRIPTS
============================================================ -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . '/includes/i18n.php');
$AI_I18N = [
  'growth_pos'        => t('ai.js.growth_pos'),
  'growth_neg'        => t('ai.js.growth_neg'),
  'activity_high'     => t('ai.js.activity_high'),
  'activity_mid'      => t('ai.js.activity_mid'),
  'activity_low'      => t('ai.js.activity_low'),
  'day_unit'          => t('ai.js.day_unit'),
  'rank'              => t('ai.js.ctx.rank'),
  'rank_top'          => t('ai.js.ctx.rank_top'),
  'merchants_active'  => t('ai.js.ctx.merchants_active'),
  'unique_payers'     => t('ai.js.ctx.unique_payers'),
  'success_rate'      => t('ai.js.ctx.success_rate'),
  'avg_check'         => t('ai.js.ctx.avg_check'),
  'platform_avg'      => t('ai.js.ctx.platform_avg'),
  'peak'              => t('ai.js.ctx.peak'),
  'no_data_title'     => t('ai.js.no_data_title'),
  'no_data_text'      => t('ai.js.no_data_text'),
  'error_title'       => t('ai.js.error_title'),
  'error_text'        => t('ai.js.error_text'),
  'chart_no_period'   => t('chart.no_data_period'),
  'chart_no_tx'       => t('chart.no_tx_yet'),
  'chart_payments'    => t('chart.label_payments'),
];
?>
<script>
/* ============================================================
   PHP DATA — window.* deb yoziladi (NOT const) — Turbo body-swap
   yangi script blokini qayta otganda const bilan SyntaxError chiqadi.
============================================================ */
window.TOTAL_TURNOVER = <?= (float)$totalTurnover ?>;
window.TX_COUNT       = <?= (int)$transactionCount ?>;
window.IS_BUSINESS    = <?= $userPricing === 'BUSINESS' ? 'true' : 'false' ?>;
window.I18N_AI        = <?= json_encode($AI_I18N, JSON_UNESCAPED_UNICODE) ?>;
window.GOLD_LINE        = '#D4AF37';
window.GOLD_FILL_TOP    = 'rgba(212,175,55,0.22)';
window.GOLD_FILL_BOTTOM = 'rgba(212,175,55,0)';

/* ============================================================
   IIFE wrap — Turbo body-swap script qayta ijro etilganda const'lar
   qayta e'lon qilinmasligi uchun. Funksiyalardan onclick'larga zarur
   bo'lganlari oxirida window.*'ga qo'shiladi.
============================================================ */
(function(){
// Window'dan local alias — quyidagi kod bare nom bilan o'qishi davom etadi.
const IS_BUSINESS      = window.IS_BUSINESS;
const I18N_AI          = window.I18N_AI;
const GOLD_LINE        = window.GOLD_LINE;
const GOLD_FILL_TOP    = window.GOLD_FILL_TOP;
const GOLD_FILL_BOTTOM = window.GOLD_FILL_BOTTOM;
const TX_COUNT         = window.TX_COUNT;
const TOTAL_TURNOVER   = window.TOTAL_TURNOVER;

/* ============================================================
   UZBEK MONTH NAMES
============================================================ */
const MON = ['Yan','Fev','Mart','Apr','May','Iyun','Iyul','Avg','Sen','Okt','Noy','Dek'];


function fmtDate(d, withTime = false) {
  const day = d.getDate(), mon = MON[d.getMonth()];
  if (withTime) {
    const h = String(d.getHours()).padStart(2,'0');
    const m = String(d.getMinutes()).padStart(2,'0');
    return `${day} ${mon} ${h}:${m}`;
  }
  return `${day} ${mon}`;
}

function fmtNum(n) {
  return Math.round(n).toLocaleString('uz-UZ');
}

/* ============================================================
   MAIN CHART
============================================================ */
let mainChartInstance = null;

function buildGradient(ctx) {
  const g = ctx.createLinearGradient(0, 0, 0, 280);

  if (IS_BUSINESS) {
    g.addColorStop(0, GOLD_FILL_TOP);
    g.addColorStop(1, GOLD_FILL_BOTTOM);
  } else {
    g.addColorStop(0, 'rgba(29,78,216,0.14)');
    g.addColorStop(1, 'rgba(29,78,216,0)');
  }

  return g;
}

function drawMainChart(data) {
  const canvas = document.getElementById('mainChart');
  if (!canvas) return;

  const wrap = canvas.parentElement;

  // Remove previous no-data message
  const old = wrap.querySelector('.no-data-msg');
  if (old) old.remove();

  if (mainChartInstance) {
    mainChartInstance.destroy();
    mainChartInstance = null;
  }

  if (!data.length) {
    canvas.style.display = 'none';
    const msg = document.createElement('div');
    msg.className = 'no-data-msg';
    msg.innerHTML = `<i class="bi bi-bar-chart-line"></i><span>${I18N_AI.chart_no_period}</span>`;
    wrap.appendChild(msg);
    return;
  }

  canvas.style.display = 'block';

  const labels  = data.map(b => fmtDate(new Date(b.created_at), true));
  const amounts = data.map(b => parseFloat(b.amount));

  mainChartInstance = new Chart(canvas.getContext('2d'), {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: I18N_AI.chart_payments,
        data: amounts,
        borderColor: IS_BUSINESS ? GOLD_LINE : '#1d4ed8',
        borderWidth: 2.5,
        backgroundColor: ctx => buildGradient(ctx.chart.ctx),
        fill: true,
        tension: 0.42,
        pointRadius: 0,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: IS_BUSINESS ? GOLD_LINE : '#1d4ed8',
        pointHoverBorderColor: '#fff',
        pointHoverBorderWidth: 2.5
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { mode: 'index', intersect: false },
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: '#fff',
         titleColor: '#9e9b95',
bodyColor: '#0d0c0a',
borderColor: '#e5e3dc',
          borderWidth: 1,
          padding: 12,
          cornerRadius: 10,
          titleFont: { size: 11, family: "'DM Sans', sans-serif" },
          bodyFont: { size: 13, weight: '600', family: "'DM Sans', sans-serif" },
          callbacks: {
            label: ctx => '  ' + fmtNum(ctx.parsed.y) + ' UZS'
          }
        }
      },
      scales: {
        x: {
          grid: { display: false },
          border: { display: false },
          ticks: {
            color: '#9e9b95',
            font: { size: 11 },
            maxTicksLimit: 12,
            maxRotation: 0
          }
        },
        y: {
          beginAtZero: true,
          grid: { color: '#f0efe9', lineWidth: 1 },
          border: { display: false, dash: [4, 4] },
          ticks: {
            color: '#9e9b95',
            font: { size: 11 },
            callback: v => v >= 1e6 ? (v/1e6).toFixed(1)+'M' : (v/1e3).toFixed(0)+'K'
          }
        }
      }
    }
  });
}

async function fetchChartData(period) {
  try {
    const r = await fetch('/api/chart_data.php?period=' + encodeURIComponent(period), {
      credentials: 'same-origin',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
    });
    if (!r.ok) throw new Error('http_' + r.status);
    const j = await r.json();
    if (!j.ok) throw new Error(j.error || 'unknown');
    return j.data || [];
  } catch (e) {
    console.warn('[chart_data]', e);
    return [];
  }
}

async function filterChart(e, period) {
  document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
  if (e && e.currentTarget) e.currentTarget.classList.add('active');

  const data = await fetchChartData(period);
  drawMainChart(data);
}

/* ============================================================
   AI MODAL — real backend tahlili
============================================================ */
let AI_LAST_DATA = null;

async function openAi() {
  document.getElementById('aiModal').classList.add('open');
  document.getElementById('aiLoader').style.display = 'flex';
  document.getElementById('aiResults').style.display = 'none';
  document.body.style.overflow = 'hidden';

  try {
    const res = await fetch('/api/ai/analyze.php', { credentials: 'same-origin' });
    if (!res.ok) throw new Error('http_' + res.status);
    const data = await res.json();
    if (!data.ok) throw new Error(data.error || 'unknown');

    AI_LAST_DATA = data;
    renderAi(data);
    document.getElementById('aiLoader').style.display = 'none';
    document.getElementById('aiResults').style.display = 'block';
  } catch (e) {
    document.getElementById('aiLoader').innerHTML =
      `<div class='ai-loader-label'><strong>${I18N_AI.error_title}</strong>${I18N_AI.error_text}</div>`;
  }
}

function closeAi() {
  document.getElementById('aiModal').classList.remove('open');
  document.body.style.overflow = '';
}

document.getElementById('aiModal').addEventListener('click', function(e) {
  if (e.target === this) closeAi();
});

document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAi(); });

/* ============================================================
   AI RENDER — backenddan kelgan real metrikalar
============================================================ */
function renderAi(data) {
  const m = data.metrics;
  const p = data.platform;
  const f = data.forecast;
  const gr = parseFloat(m.growth_7);

  document.getElementById('aiGrowth').textContent = (gr >= 0 ? '+' : '') + gr + '%';
  const sub = document.getElementById('aiGrowthSub');
  sub.className = 'm-sub ' + (gr >= 0 ? 'positive' : 'negative');
  sub.innerHTML = `<i class="bi bi-arrow-${gr >= 0 ? 'up' : 'down'}-short"></i> ` +
    (gr >= 0 ? I18N_AI.growth_pos : I18N_AI.growth_neg);

  document.getElementById('aiAvg').textContent  = fmtNum(m.avg_daily) + ' UZS';
  document.getElementById('aiBest').textContent = fmtNum(m.best_amount) + ' UZS';
  document.getElementById('aiBestDate').innerHTML =
    `<i class="bi bi-trophy"></i> ${m.best_date || '—'}`;

  document.getElementById('aiActivity').textContent = m.activity_level + '%';
  document.getElementById('aiActivitySub').innerHTML = `<i class="bi bi-lightning"></i> ` + (
    m.activity_level > 70 ? I18N_AI.activity_high :
    m.activity_level > 40 ? I18N_AI.activity_mid : I18N_AI.activity_low
  ) + ` · ${m.active_days}/30 ${I18N_AI.day_unit}`;

  document.getElementById('aiW7').textContent   = fmtNum(f.next_7) + ' UZS';
  document.getElementById('aiM30').textContent  = fmtNum(f.next_30) + ' UZS';
  document.getElementById('aiW7Conf').textContent  = f.week_conf + '%';
  document.getElementById('aiM30Conf').textContent = f.month_conf + '%';
  document.getElementById('aiW7Fill').style.width  = f.week_conf + '%';
  document.getElementById('aiM30Fill').style.width = f.month_conf + '%';

  buildRecommendations(data.recommendations || [], m, p);
  drawForecastChart(f);
}

/* ============================================================
   RECOMMENDATIONS — backenddan keladi + real signal context
============================================================ */
function buildRecommendations(recs, m, p) {
  const wrap = document.getElementById('aiRecs');

  const ctx = `
    <div class="rec-context">
      <div class="rec-ctx-row">
        <span><i class="bi bi-graph-up"></i> ${I18N_AI.rank}</span>
        <strong>${I18N_AI.rank_top} ${Math.max(1, 100 - p.percentile)}%</strong>
        <small>(${p.active_users} ${I18N_AI.merchants_active})</small>
      </div>
      <div class="rec-ctx-row">
        <span><i class="bi bi-people"></i> ${I18N_AI.unique_payers}</span>
        <strong>${m.unique_payers}</strong>
      </div>
      <div class="rec-ctx-row">
        <span><i class="bi bi-check-circle"></i> ${I18N_AI.success_rate}</span>
        <strong>${m.success_rate}%</strong>
        <small>(${m.tx_success}/${m.tx_total})</small>
      </div>
      <div class="rec-ctx-row">
        <span><i class="bi bi-receipt"></i> ${I18N_AI.avg_check}</span>
        <strong>${fmtNum(m.avg_ticket)} UZS</strong>
        <small>(${I18N_AI.platform_avg} ${fmtNum(p.avg_ticket)})</small>
      </div>
      ${m.peak_hour !== null ? `
      <div class="rec-ctx-row">
        <span><i class="bi bi-clock"></i> ${I18N_AI.peak}</span>
        <strong>${String(m.peak_hour).padStart(2,'0')}:00</strong>
        <small>· ${m.best_dow}</small>
      </div>` : ''}
    </div>
  `;

  const items = recs.length ? recs.map(r => `
    <div class="rec-item rec-${r.level || 'info'}">
      <div class="rec-icon"><i class="bi ${r.icon}"></i></div>
      <div class="rec-body">
        <h6>${r.title}</h6>
        <p>${r.text}</p>
      </div>
    </div>
  `).join('') : `
    <div class="rec-item">
      <div class="rec-icon"><i class="bi bi-info-circle"></i></div>
      <div class="rec-body">
        <h6>${I18N_AI.no_data_title}</h6>
        <p>${I18N_AI.no_data_text}</p>
      </div>
    </div>
  `;

  wrap.innerHTML = ctx + items;
}

/* ============================================================
   FORECAST CHART
============================================================ */
function drawForecastChart(f) {
  const existing = Chart.getChart('forecastCanvas');
  if (existing) existing.destroy();

  const canvas = document.getElementById('forecastCanvas');
  if (!canvas) return;

  const labels = [];
  const actual = [];
  const forecast = [];

  (f.actual || []).forEach(p => {
    labels.push(fmtDate(new Date(p.date)));
    actual.push(p.amount);
  });
  (f.predicted || []).forEach(p => {
    labels.push(fmtDate(new Date(p.date)));
    forecast.push(p.amount);
  });

  const aPad = [...actual, ...Array(forecast.length).fill(null)];
  const fPad = [...Array(actual.length).fill(null), ...forecast];

  new Chart(canvas.getContext('2d'), {
    type: 'line',
    data: {
      labels,
      datasets: [
        {
          label: 'Haqiqiy',
          data: aPad,
          borderColor: IS_BUSINESS ? GOLD_LINE : '#1d4ed8',
          borderWidth: 2.5,
          pointRadius: 3,
          pointBackgroundColor: '#1d4ed8',
          fill: false,
          tension: 0.42
        },
        {
          label: 'Prognoz',
          data: fPad,
          borderColor: IS_BUSINESS ? '#B8962E' : '#6d28d9',
          borderWidth: 2.5,
          borderDash: [5, 4],
          pointRadius: 3,
          pointBackgroundColor: '#6d28d9',
          fill: false,
          tension: 0.42
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          labels: { color: '#6a6760', font: { size: 11 }, boxWidth: 10, padding: 14 }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#9e9b95',
          bodyColor: '#0d0c0a',
          borderColor: '#e5e3dc',
          borderWidth: 1,
          padding: 10,
          cornerRadius: 8,
          callbacks: { label: ctx => '  ' + fmtNum(ctx.parsed.y) + ' UZS' }
        }
      },
      scales: {
        x: {
          grid: { display: false },
          border: { display: false },
          ticks: { color: '#9e9b95', font: { size: 10 } }
        },
        y: {
          beginAtZero: true,
          grid: { color: '#f0efe9' },
          border: { display: false },
          ticks: {
            color: '#9e9b95',
            font: { size: 10 },
            callback: v => (v / 1000).toFixed(0) + 'K'
          }
        }
      }
    }
  });
}

/* ============================================================
   RAMADAN TIMER
============================================================ */
let saharlik, iftorlik, serverBase, clientBase;

async function loadRamadan() {
  try {
    const res  = await fetch('https://inpay.uz/api/home/ramadan/');
    const data = await res.json();
    if (!data.status) return;

    document.getElementById('saharlikTime').textContent = data.saharlik;
    document.getElementById('iftorlikTime').textContent = data.iftorlik;

    serverBase = new Date(data.server_time);
    clientBase = new Date();
    saharlik   = buildPrayerTime(data.saharlik);
    iftorlik   = buildPrayerTime(data.iftorlik);
    startTimer();
  } catch (e) {
    // Fallback demo values
    serverBase = new Date();
    clientBase = new Date();
    saharlik   = buildPrayerTime('04:55');
    iftorlik   = buildPrayerTime('19:30');
    document.getElementById('saharlikTime').textContent = '04:55';
    document.getElementById('iftorlikTime').textContent = '19:30';
    startTimer();
  }
}

function buildPrayerTime(str) {
  const [h, m] = str.split(':');
  return new Date(serverBase.getFullYear(), serverBase.getMonth(), serverBase.getDate(), +h, +m, 0);
}

function getServerNow() {
  return new Date(serverBase.getTime() + (Date.now() - clientBase.getTime()));
}

function startTimer() {
  setInterval(() => {
    const now  = getServerNow();
    let target, title;

    if (now < saharlik) {
      target = saharlik;
      title  = '🌙 Saharlikkacha';
    } else if (now < iftorlik) {
      target = iftorlik;
      title  = '🍽 Iftorgacha';
    } else {
      const next = new Date(saharlik);
      next.setDate(next.getDate() + 1);
      target = next;
      title  = '🌅 Keyingi saharlikkacha';
    }

    document.getElementById('ramadanTitle').textContent = title;

    const diff = Math.max(0, target - now);
    document.getElementById('tHours').textContent   = String(Math.floor(diff / 3600000)).padStart(2,'0');
    document.getElementById('tMinutes').textContent = String(Math.floor((diff % 3600000) / 60000)).padStart(2,'0');
    document.getElementById('tSeconds').textContent = String(Math.floor((diff % 60000) / 1000)).padStart(2,'0');
  }, 1000);
}

/* ============================================================
   INIT — DOMContentLoaded VA Turbo body-swap (turbo:load)
============================================================ */
async function initHomePage() {
  const chartCanvas = document.getElementById('mainChart');
  if (chartCanvas) {
    // Birinchi yuklanishda 'all' period bilan API'dan tortamiz.
    // Default tab ham 'all' (active class HTML'da o'rnatilgan).
    document.querySelectorAll('.filter-tab').forEach((t, i) => {
      t.classList.toggle('active', i === 0);
    });

    const data = await fetchChartData('all');
    if (data.length > 0) {
      drawMainChart(data);
    } else {
      chartCanvas.style.display = 'none';
      const wrap = chartCanvas.parentElement;
      const old = wrap.querySelector('.no-data-msg');
      if (old) old.remove();
      const msg = document.createElement('div');
      msg.className = 'no-data-msg';
      msg.innerHTML = `<i class="bi bi-bar-chart-line"></i><span>${I18N_AI.chart_no_tx}</span>`;
      wrap.appendChild(msg);
    }
  }

  if (typeof loadRamadan === 'function') loadRamadan();
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initHomePage);
} else {
  // Turbo body-swap'dan keyin script qayta otilsa, DOM allaqachon ready.
  initHomePage();
}
document.addEventListener('turbo:load', initHomePage);

/* ============================================================
   EXPORTS — onclick="..." inline handler'lardan chaqirilishi uchun
============================================================ */
window.filterChart = filterChart;
window.openAi      = openAi;
window.closeAi     = closeAi;
})();   /* IIFE end */
</script>

<?php include_once($_SERVER["DOCUMENT_ROOT"]."/business/includes/footer.php"); ?>

<?php if ($userPricing === 'BUSINESS'): ?>
<script>
/* ============================================================
   BUSINESS — Premium 4D effects: particles + 3D tilt + spotlight
============================================================ */
(function(){
  const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
  const isMobile     = matchMedia('(max-width: 768px)').matches;

  // 1. Particles (CSS @keyframes, JS faqat dom yaratadi)
  const partsEl = document.getElementById('bizParticles');
  if (partsEl && !reduceMotion) {
    const N = isMobile ? 12 : 26;
    for (let i = 0; i < N; i++) {
      const p = document.createElement('div');
      p.className = 'biz-particle';
      const size = 4 + Math.random() * 8;
      p.style.width  = size + 'px';
      p.style.height = size + 'px';
      p.style.left   = (Math.random() * 100) + 'vw';
      p.style.setProperty('--dur', (10 + Math.random() * 14) + 's');
      p.style.setProperty('--dx', (Math.random() * 200 - 100));
      p.style.animationDelay = (-Math.random() * 14) + 's';
      partsEl.appendChild(p);
    }
  }

  // 2. Cursor spotlight
  const cursor = document.getElementById('bizCursor');
  if (cursor && !isMobile && !reduceMotion) {
    document.body.classList.add('biz-cursor-active');
    let raf = null, mx = innerWidth/2, my = innerHeight/2, cx = mx, cy = my;
    const step = () => {
      cx += (mx - cx) * 0.12;
      cy += (my - cy) * 0.12;
      cursor.style.transform = `translate(${cx}px, ${cy}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(step);
    };
    document.addEventListener('mousemove', e => { mx = e.clientX; my = e.clientY; });
    step();
  }

  // 3. 3D tilt on cards
  if (!reduceMotion) {
    document.querySelectorAll('.theme-business .stat-card, .theme-business .chart-card, .theme-business .hero-ai, .theme-business .hero-plan-business').forEach(card => {
      // shimmer overlay yarat
      if (!card.querySelector('.biz-shimmer')) {
        const s = document.createElement('span');
        s.className = 'biz-shimmer';
        card.appendChild(s);
      }
      let rect = null;
      const reset = () => {
        card.style.transform = '';
      };
      card.addEventListener('mouseenter', () => { rect = card.getBoundingClientRect(); });
      card.addEventListener('mousemove', (e) => {
        if (!rect) rect = card.getBoundingClientRect();
        const x = (e.clientX - rect.left) / rect.width;
        const y = (e.clientY - rect.top)  / rect.height;
        const rx = (0.5 - y) * 8;   // X o'qi atrofida ag'darish
        const ry = (x - 0.5) * 8;   // Y o'qi atrofida
        card.style.transform = `perspective(1000px) rotateX(${rx}deg) rotateY(${ry}deg) translateY(-3px) translateZ(8px)`;
      });
      card.addEventListener('mouseleave', () => { rect = null; reset(); });
    });
  }

  // 4. Number counter animations
  document.querySelectorAll('.theme-business .t-num, .theme-business .sc-num').forEach(el => {
    const text = el.textContent.trim();
    const m = text.match(/^[-]?[\d\s.,]+/);
    if (!m) return;
    const numStr = m[0].replace(/[\s ]/g, '').replace(',', '.');
    const target = parseFloat(numStr);
    if (!isFinite(target) || target === 0) return;
    const suffix = text.slice(m[0].length);
    const dec = (numStr.split('.')[1] || '').length;
    const dur = 1100;
    const t0 = performance.now();
    function frame(t) {
      const p = Math.min(1, (t - t0) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      const v = target * eased;
      el.textContent = v.toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ' ') + suffix;
      if (p < 1) requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
  });

  // 5. Body loaded class
  document.body.dataset.loaded = '1';
})();
</script>
<?php endif; ?>

</body>
</html>