<?php
require_once __DIR__ . "/includes/config.php";
session_start_secure();
$user = current_user();

// DEBUG endpoint
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    $dbg = ['session' => $_SESSION['user'] ?? null];
    if (!empty($_SESSION['user']['id'])) {
        try {
            $s = db()->prepare("SELECT id,name,role FROM baitari_users WHERE id=:id");
            $s->execute([':id'=>$_SESSION['user']['id']]);
            $dbg['db'] = $s->fetch();
        } catch(Exception $e) {
            $dbg['db_error'] = $e->getMessage();
        }
    }
    header('Content-Type: application/json');
    echo json_encode($dbg, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
    exit;
}
// Redirect to login if not authenticated
if (!$user) {
    header("Location: login.php");
    exit;
}
$lang  = $user["lang_pref"]  ?? "ar";
$theme = $user["theme_pref"] ?? "light";
$role  = $user["role"] ?? "client";
// Normalize legacy roles
if (in_array($role, ["pet_owner", "farm_owner"])) $role = "client";

// ── ROLE-BASED REDIRECTS ──
// Farm owners → herd management
if ($role === 'client' && !isset($_GET['stay'])) {
    // Only redirect if coming directly (not from internal nav)
    // header('Location: pages/farm-herds.php'); // Uncomment to force redirect
}

// ── VET VERIFICATION GATE ──
if ($role === 'vet') {
    // Check verification status
    $vstmt = db()->prepare(
        "SELECT verification_status FROM baitari_vet_profiles WHERE vet_id = :uid LIMIT 1"
    );
    $vstmt->execute([':uid' => (int)$user['id']]);
    $vp = $vstmt->fetch();
    $vstatus = $vp['verification_status'] ?? 'pending_docs';

    // Only 'approved' vets can access the main app
    if ($vstatus !== 'approved') {
        header("Location: pages/vet-onboarding.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>" dir="rtl" data-theme="<?php echo htmlspecialchars($theme); ?>" data-lang="<?php echo htmlspecialchars($lang); ?>" data-user-role="<?php echo htmlspecialchars($role); ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#1a7f5a">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<title>بيطري – صحة حيوانك همّنا</title>
<link rel="manifest" href="manifest.json">
<link rel="apple-touch-icon" href="assets/img/icon-192.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&family=Nunito:wght@400;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/baitari.css">
<style>
/* ═══════════════════════════════════════════════
   DESIGN TOKENS — CSS VARIABLES
═══════════════════════════════════════════════ */
:root {
  /* Brand palette */
  --green-50:  #f0faf5;
  --green-100: #d6f2e5;
  --green-200: #aae3cb;
  --green-400: #4aba8a;
  --green-500: #1a9f6a;
  --green-600: #1a7f5a;
  --green-700: #155f44;
  --green-800: #0e3f2e;

  --blue-50:   #eff6ff;
  --blue-100:  #dbeafe;
  --blue-400:  #60a5fa;
  --blue-500:  #3b82f6;
  --blue-600:  #2563eb;

  --red-500:   #ef4444;
  --red-600:   #dc2626;
  --red-700:   #b91c1c;
  --red-glow:  rgba(239,68,68,.35);

  --amber-400: #fbbf24;
  --amber-500: #f59e0b;

  /* Semantic — light mode */
  --bg:         #f7faf9;
  --bg-card:    #ffffff;
  --bg-nav:     #ffffff;
  --bg-input:   #f3f7f5;
  --border:     #e0ece7;
  --border-focus:#1a9f6a;
  --text-primary:#0e2d20;
  --text-sec:   #4a7060;
  --text-muted: #8aaa9a;
  --shadow-sm:  0 1px 4px rgba(0,60,30,.06);
  --shadow-md:  0 4px 20px rgba(0,60,30,.10);
  --shadow-lg:  0 8px 40px rgba(0,60,30,.15);
  --shadow-xl:  0 20px 60px rgba(0,60,30,.20);
  --overlay:    rgba(0,0,0,.45);
  --nav-height: 68px;
  --header-h:   64px;
  --radius-sm:  10px;
  --radius-md:  16px;
  --radius-lg:  24px;
  --radius-xl:  32px;
  --transition: .22s cubic-bezier(.4,0,.2,1);
}

[data-theme="dark"] {
  --bg:         #0a1a12;
  --bg-card:    #122010;
  --bg-nav:     #0d1c14;
  --bg-input:   #1a2e1e;
  --border:     #1e3828;
  --border-focus:#4aba8a;
  --text-primary:#e0f2e9;
  --text-sec:   #8abfa0;
  --text-muted: #4a7060;
  --shadow-sm:  0 1px 4px rgba(0,0,0,.3);
  --shadow-md:  0 4px 20px rgba(0,0,0,.4);
  --shadow-lg:  0 8px 40px rgba(0,0,0,.5);
  --shadow-xl:  0 20px 60px rgba(0,0,0,.6);
  --overlay:    rgba(0,0,0,.65);
  --green-50:  #0d1f14;
  --green-100: #112918;
  --blue-50:   #0a1220;
}

/* ═══════════════════════════════════════════════
   RESET & BASE
═══════════════════════════════════════════════ */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { scroll-behavior: smooth; -webkit-tap-highlight-color: transparent; }
body {
  font-family: 'Tajawal', 'Nunito', sans-serif;
  background: var(--bg);
  color: var(--text-primary);
  min-height: 100dvh;
  overflow-x: hidden;
  -webkit-font-smoothing: antialiased;
}
[lang="en"] body, [lang="fr"] body {
  font-family: 'Nunito', 'Tajawal', sans-serif;
}
img { max-width: 100%; display: block; }
button { cursor: pointer; border: none; background: none; font-family: inherit; }
input, textarea, select {
  font-family: inherit;
  font-size: inherit;
  outline: none;
  border: none;
}
a { text-decoration: none; color: inherit; }

/* ═══════════════════════════════════════════════
   LAYOUT SHELL
═══════════════════════════════════════════════ */
#app {
  max-width: 480px;
  margin: 0 auto;
  min-height: 100dvh;
  position: relative;
  background: var(--bg);
}

/* Desktop / Tablet sidebar */
@media (min-width: 768px) {
  #app { max-width: 100%; display: grid; grid-template-columns: 260px 1fr; }
  #bottom-nav { display: none !important; }
  #sidebar { display: flex !important; }
}
@media (min-width: 1200px) {
  #app { grid-template-columns: 280px 1fr 320px; }
}

/* Page container */
#page-wrapper {
  padding-bottom: calc(var(--nav-height) + 12px);
  min-height: 100dvh;
}
@media (min-width: 768px) {
  #page-wrapper { padding-bottom: 0; }
}

/* ═══════════════════════════════════════════════
   TOP HEADER
═══════════════════════════════════════════════ */
.app-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: var(--bg-card);
  border-bottom: 1px solid var(--border);
  height: var(--header-h);
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 12px;
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
}
.app-header .logo-mark {
  width: 38px; height: 38px;
  background: linear-gradient(135deg, var(--green-600), var(--green-400));
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 20px; flex-shrink: 0;
  box-shadow: 0 3px 12px rgba(26,127,90,.3);
}
.app-header .header-title {
  font-size: 20px; font-weight: 800;
  color: var(--text-primary);
  flex: 1;
}
.app-header .header-title span {
  color: var(--green-600);
}
.header-actions { display: flex; gap: 8px; }
.icon-btn {
  width: 40px; height: 40px;
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  background: var(--bg-input);
  color: var(--text-sec);
  font-size: 18px;
  transition: var(--transition);
  position: relative;
}
.icon-btn:hover { background: var(--green-100); color: var(--green-600); }
.notif-dot {
  position: absolute; top: 6px; right: 6px;
  width: 8px; height: 8px;
  background: var(--red-500);
  border-radius: 50%;
  border: 2px solid var(--bg-card);
}

/* ═══════════════════════════════════════════════
   BOTTOM NAVIGATION
═══════════════════════════════════════════════ */
#bottom-nav {
  position: fixed;
  bottom: 0; left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 480px;
  height: var(--nav-height);
  background: var(--bg-nav);
  border-top: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-around;
  z-index: 200;
  box-shadow: 0 -4px 24px rgba(0,0,0,.08);
  padding: 0 4px;
}
.nav-item {
  flex: 1;
  display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  gap: 3px;
  padding: 6px 4px;
  border-radius: var(--radius-sm);
  cursor: pointer;
  transition: var(--transition);
  color: var(--text-muted);
  position: relative;
  min-width: 0;
}
.nav-item.active {
  color: var(--green-600);
}
.nav-item .nav-icon {
  font-size: 22px;
  line-height: 1;
  transition: transform var(--transition);
}
.nav-item.active .nav-icon {
  transform: translateY(-2px);
}
.nav-item .nav-label {
  font-size: 10px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 56px;
  text-align: center;
}
/* Active indicator bar */
.nav-item.active::before {
  content: '';
  position: absolute;
  top: 0; left: 50%;
  transform: translateX(-50%);
  width: 24px; height: 3px;
  background: var(--green-600);
  border-radius: 0 0 3px 3px;
}
/* Emergency nav button */
.nav-item.emergency {
  flex: 0 0 60px;
}
.nav-item.emergency .nav-icon-wrap {
  width: 52px; height: 52px;
  background: linear-gradient(135deg, var(--red-600), var(--red-500));
  border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: 24px;
  margin-top: -20px;
  box-shadow: 0 4px 20px var(--red-glow), 0 0 0 4px var(--bg-nav);
  transition: var(--transition);
  animation: pulse-emergency 2.5s ease-in-out infinite;
}
.nav-item.emergency:hover .nav-icon-wrap,
.nav-item.emergency:active .nav-icon-wrap {
  transform: scale(1.1);
}
@keyframes pulse-emergency {
  0%, 100% { box-shadow: 0 4px 20px var(--red-glow), 0 0 0 4px var(--bg-nav); }
  50% { box-shadow: 0 4px 28px rgba(239,68,68,.5), 0 0 0 6px var(--bg-nav); }
}
.nav-item.emergency .nav-label { color: var(--red-500); }

/* ═══════════════════════════════════════════════
   DESKTOP SIDEBAR
═══════════════════════════════════════════════ */
#sidebar {
  display: none;
  flex-direction: column;
  background: var(--bg-card);
  border-left: 1px solid var(--border);
  height: 100dvh;
  position: sticky;
  top: 0;
  padding: 24px 0;
  overflow-y: auto;
}
.sidebar-logo {
  display: flex; align-items: center; gap: 12px;
  padding: 0 24px 24px;
  border-bottom: 1px solid var(--border);
  margin-bottom: 16px;
}
.sidebar-logo .logo-mark { width: 42px; height: 42px; font-size: 22px; }
.sidebar-logo h1 { font-size: 22px; font-weight: 900; }
.sidebar-logo h1 span { color: var(--green-600); }
.sidebar-nav-item {
  display: flex; align-items: center; gap: 14px;
  padding: 14px 24px;
  cursor: pointer;
  transition: var(--transition);
  color: var(--text-sec);
  font-weight: 600;
  font-size: 15px;
  border-radius: 0;
  margin: 2px 12px;
  border-radius: var(--radius-sm);
}
.sidebar-nav-item:hover { background: var(--green-50); color: var(--green-700); }
.sidebar-nav-item.active { background: var(--green-50); color: var(--green-600); }
.sidebar-nav-item .sn-icon { font-size: 20px; width: 24px; text-align: center; }
.sidebar-emergency {
  margin: 12px 16px;
  background: linear-gradient(135deg, var(--red-700), var(--red-500));
  color: white;
  border-radius: var(--radius-md);
  padding: 14px 20px;
  display: flex; align-items: center; gap: 12px;
  font-weight: 700; font-size: 15px;
  box-shadow: 0 4px 16px var(--red-glow);
  cursor: pointer;
}

/* ═══════════════════════════════════════════════
   PAGES
═══════════════════════════════════════════════ */
.page {
  display: none;
  animation: fadeUp .3s ease both;
}
.page.active { display: block; }
@keyframes fadeUp {
  from { opacity: 0; transform: translateY(16px); }
  to   { opacity: 1; transform: translateY(0); }
}

/* ═══════════════════════════════════════════════
   HOME PAGE
═══════════════════════════════════════════════ */
.home-hero {
  background: linear-gradient(135deg, var(--green-700) 0%, var(--green-500) 60%, var(--blue-500) 100%);
  padding: 28px 20px 40px;
  position: relative;
  overflow: hidden;
}
.home-hero::before {
  content: '';
  position: absolute;
  top: -40px; left: -40px;
  width: 200px; height: 200px;
  background: rgba(255,255,255,.06);
  border-radius: 50%;
}
.home-hero::after {
  content: '';
  position: absolute;
  bottom: -60px; right: -30px;
  width: 240px; height: 240px;
  background: rgba(255,255,255,.04);
  border-radius: 50%;
}
.hero-greeting {
  color: rgba(255,255,255,.8);
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}
.hero-name {
  color: #fff;
  font-size: 24px;
  font-weight: 800;
  margin-bottom: 16px;
}
.hero-stats {
  display: flex; gap: 10px;
}
.hero-stat {
  background: rgba(255,255,255,.15);
  backdrop-filter: blur(8px);
  border-radius: var(--radius-md);
  padding: 12px 16px;
  flex: 1;
  text-align: center;
  border: 1px solid rgba(255,255,255,.2);
}
.hero-stat .stat-num {
  font-size: 22px; font-weight: 800; color: #fff;
}
.hero-stat .stat-label {
  font-size: 11px; color: rgba(255,255,255,.75);
  font-weight: 500;
}

/* ═══════════════════════════════════════════════
   EMERGENCY CARD
═══════════════════════════════════════════════ */
.emergency-card {
  margin: -20px 16px 0;
  position: relative;
  z-index: 10;
  background: linear-gradient(135deg, var(--red-700), var(--red-500));
  border-radius: var(--radius-lg);
  padding: 18px 20px;
  display: flex; align-items: center; gap: 16px;
  box-shadow: 0 8px 32px var(--red-glow), 0 2px 8px rgba(0,0,0,.15);
  cursor: pointer;
  transition: var(--transition);
  border: 2px solid rgba(255,255,255,.2);
}
.emergency-card:hover { transform: translateY(-2px); box-shadow: 0 12px 40px rgba(239,68,68,.45); }
.emergency-card:active { transform: translateY(0); }
.emg-icon {
  width: 52px; height: 52px;
  background: rgba(255,255,255,.2);
  border-radius: 16px;
  display: flex; align-items: center; justify-content: center;
  font-size: 26px; flex-shrink: 0;
}
.emg-text { flex: 1; }
.emg-text h3 { color: #fff; font-size: 17px; font-weight: 800; }
.emg-text p { color: rgba(255,255,255,.8); font-size: 12px; margin-top: 2px; }
.emg-arrow { color: rgba(255,255,255,.7); font-size: 20px; }
[dir="ltr"] .emg-arrow { transform: scaleX(-1); }

/* ═══════════════════════════════════════════════
   SECTION HEADERS
═══════════════════════════════════════════════ */
.section-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 20px 20px 12px;
}
.section-title {
  font-size: 17px; font-weight: 800;
  color: var(--text-primary);
}
.section-link {
  font-size: 13px; color: var(--green-600);
  font-weight: 600;
  cursor: pointer;
}

/* ═══════════════════════════════════════════════
   PET CARDS
═══════════════════════════════════════════════ */
.pets-scroll {
  display: flex; gap: 12px;
  padding: 0 20px 4px;
  overflow-x: auto;
  scrollbar-width: none;
}
.pets-scroll::-webkit-scrollbar { display: none; }

.pet-card {
  flex: 0 0 110px;
  background: var(--bg-card);
  border-radius: var(--radius-md);
  padding: 14px 10px;
  text-align: center;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border);
  cursor: pointer;
  transition: var(--transition);
  position: relative;
}
.pet-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); }
.pet-card:active { transform: scale(.97); }
.pet-avatar {
  width: 56px; height: 56px;
  border-radius: 50%;
  margin: 0 auto 8px;
  background: var(--green-50);
  display: flex; align-items: center; justify-content: center;
  font-size: 28px;
  border: 2px solid var(--green-100);
}
.pet-name { font-size: 13px; font-weight: 700; color: var(--text-primary); }
.pet-breed { font-size: 11px; color: var(--text-muted); margin-top: 2px; }
.pet-status-dot {
  position: absolute; top: 10px; right: 10px;
  width: 10px; height: 10px; border-radius: 50%;
}
.pet-status-dot.healthy { background: #22c55e; }
.pet-status-dot.warning { background: var(--amber-500); }

/* Add Pet Card */
.species-btn {
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  padding: 10px 6px; border-radius: 12px;
  background: var(--bg-input); border: 1.5px solid var(--border);
  cursor: pointer; transition: .2s; font-family: 'Tajawal', sans-serif;
  color: var(--text-primary);
}
.species-btn:hover { border-color: var(--green-400, #34d399); transform: translateY(-2px); }
.species-btn.on { border-color: var(--green-500, #10b981); background: rgba(16,185,129,.08); box-shadow: 0 0 0 3px rgba(16,185,129,.12); }
.toggle-btn.on { background: var(--green-500, #10b981) !important; }
.toggle-btn.on span { right: 23px !important; }
.modal-header .modal-title { font-size: 18px; font-weight: 800; flex: 1; }

.add-pet-card {
  flex: 0 0 90px;
  background: var(--green-50);
  border: 2px dashed var(--green-200);
  border-radius: var(--radius-md);
  display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  gap: 6px;
  cursor: pointer;
  transition: var(--transition);
  padding: 14px 10px;
}
.add-pet-card:hover { background: var(--green-100); border-color: var(--green-400); }
.add-pet-card .add-icon { font-size: 28px; color: var(--green-500); }
.add-pet-card .add-label { font-size: 11px; font-weight: 700; color: var(--green-600); text-align: center; }

/* ═══════════════════════════════════════════════
   FARM HERD CARDS
═══════════════════════════════════════════════ */
.herd-list { padding: 0 16px; display: flex; flex-direction: column; gap: 10px; }
.herd-card {
  background: var(--bg-card);
  border-radius: var(--radius-md);
  padding: 16px;
  display: flex; align-items: center; gap: 14px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border);
  cursor: pointer;
  transition: var(--transition);
}
.herd-card:hover { box-shadow: var(--shadow-md); border-color: var(--green-200); }
.herd-icon {
  width: 52px; height: 52px;
  border-radius: 14px;
  display: flex; align-items: center; justify-content: center;
  font-size: 26px; flex-shrink: 0;
}
.herd-icon.cattle { background: #fef3c7; }
.herd-icon.sheep  { background: #f0f9ff; }
.herd-icon.goats  { background: #fdf4ff; }
.herd-icon.horses { background: #fff1f2; }
.herd-icon.poultry{ background: #fffbeb; }
.herd-info { flex: 1; }
.herd-name { font-size: 15px; font-weight: 700; color: var(--text-primary); }
.herd-count { font-size: 13px; color: var(--text-sec); margin-top: 2px; }
.herd-badge {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 11px; font-weight: 700;
}
.herd-badge.healthy { background: #dcfce7; color: #15803d; }
.herd-badge.needs-attention { background: #fef3c7; color: #92400e; }
.herd-badge.critical { background: #fee2e2; color: #991b1b; }

/* ═══════════════════════════════════════════════
   VET CARDS
═══════════════════════════════════════════════ */
.vets-list { padding: 0 16px; display: flex; flex-direction: column; gap: 12px; }
.vet-card {
  background: var(--bg-card);
  border-radius: var(--radius-lg);
  padding: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border);
  cursor: pointer;
  transition: var(--transition);
}
.vet-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.vet-card-top {
  display: flex; align-items: flex-start; gap: 14px;
}
.vet-avatar {
  width: 60px; height: 60px;
  border-radius: 18px;
  flex-shrink: 0;
  object-fit: cover;
  background: linear-gradient(135deg, var(--green-400), var(--blue-400));
  display: flex; align-items: center; justify-content: center;
  font-size: 28px; color: white;
  font-weight: 800;
}
.vet-info { flex: 1; min-width: 0; }
.vet-name {
  font-size: 16px; font-weight: 800;
  color: var(--text-primary);
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.vet-specialty {
  font-size: 12px; color: var(--green-600);
  font-weight: 600; margin-top: 2px;
}
.vet-meta {
  display: flex; gap: 10px; align-items: center;
  margin-top: 6px; flex-wrap: wrap;
}
.vet-meta-item {
  display: flex; align-items: center; gap: 4px;
  font-size: 12px; color: var(--text-sec);
}
.vet-rating-stars { color: var(--amber-500); font-size: 13px; }
.availability-badge {
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 11px; font-weight: 700;
  margin-right: auto;
}
.availability-badge.available { background: #dcfce7; color: #15803d; }
.availability-badge.busy { background: #fef3c7; color: #92400e; }
.availability-badge.offline { background: #f1f5f9; color: #64748b; }
.vet-card-actions {
  display: flex; gap: 10px; margin-top: 14px;
}
.btn-book {
  flex: 1;
  background: linear-gradient(135deg, var(--green-600), var(--green-500));
  color: white;
  border-radius: var(--radius-sm);
  padding: 10px;
  font-size: 14px; font-weight: 700;
  text-align: center;
  transition: var(--transition);
  box-shadow: 0 3px 12px rgba(26,127,90,.25);
}
.btn-book:hover { opacity: .9; transform: translateY(-1px); }
.btn-profile {
  width: 42px; height: 42px;
  background: var(--bg-input);
  border-radius: var(--radius-sm);
  display: flex; align-items: center; justify-content: center;
  font-size: 18px; color: var(--text-sec);
  transition: var(--transition);
}
.btn-profile:hover { background: var(--green-100); color: var(--green-600); }

/* Distance chip */
.distance-chip {
  display: flex; align-items: center; gap: 3px;
  font-size: 12px; color: var(--text-sec);
}
.distance-chip .icon { font-size: 14px; }

/* ═══════════════════════════════════════════════
   SEARCH PAGE
═══════════════════════════════════════════════ */
.search-bar-wrap {
  padding: 16px;
  position: sticky; top: var(--header-h);
  z-index: 90;
  background: var(--bg);
  border-bottom: 1px solid var(--border);
}
.search-bar {
  display: flex; align-items: center; gap: 10px;
  background: var(--bg-card);
  border: 1.5px solid var(--border);
  border-radius: 14px;
  padding: 10px 14px;
  transition: var(--transition);
}
.search-bar:focus-within { border-color: var(--green-500); box-shadow: 0 0 0 3px rgba(26,159,106,.1); }
.search-bar .search-icon { font-size: 20px; color: var(--text-muted); flex-shrink: 0; }
.search-bar input {
  flex: 1; background: none; color: var(--text-primary);
  font-size: 15px; font-weight: 500;
}
.search-bar input::placeholder { color: var(--text-muted); }
.filter-chips {
  display: flex; gap: 8px;
  padding: 12px 16px 0;
  overflow-x: auto; scrollbar-width: none;
}
.filter-chips::-webkit-scrollbar { display: none; }
.chip {
  flex: 0 0 auto;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 12px; font-weight: 700;
  background: var(--bg-card);
  border: 1.5px solid var(--border);
  color: var(--text-sec);
  cursor: pointer;
  transition: var(--transition);
  white-space: nowrap;
}
.chip.active { background: var(--green-600); border-color: var(--green-600); color: white; }
.chip:hover:not(.active) { border-color: var(--green-400); color: var(--green-600); }

/* ═══════════════════════════════════════════════
   APPOINTMENTS PAGE
═══════════════════════════════════════════════ */
.tab-bar {
  display: flex;
  background: var(--bg-card);
  border-bottom: 1px solid var(--border);
  padding: 0 16px;
}
.tab-item {
  flex: 1; padding: 14px 8px;
  text-align: center;
  font-size: 14px; font-weight: 700;
  color: var(--text-muted);
  cursor: pointer;
  position: relative;
  transition: var(--transition);
}
.tab-item.active { color: var(--green-600); }
.tab-item.active::after {
  content: '';
  position: absolute; bottom: 0; left: 10%; right: 10%;
  height: 3px; background: var(--green-600);
  border-radius: 3px 3px 0 0;
}

.appt-list { padding: 16px; display: flex; flex-direction: column; gap: 12px; }
.appt-card {
  background: var(--bg-card);
  border-radius: var(--radius-lg);
  padding: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border);
  display: flex; gap: 14px; align-items: flex-start;
}
.appt-date-block {
  text-align: center; flex-shrink: 0;
  background: var(--green-50);
  border-radius: 12px;
  padding: 8px 12px;
  border: 1px solid var(--green-100);
}
.appt-day { font-size: 24px; font-weight: 900; color: var(--green-700); line-height: 1; }
.appt-month { font-size: 11px; color: var(--green-600); font-weight: 600; }
.appt-info { flex: 1; }
.appt-vet-name { font-size: 15px; font-weight: 800; color: var(--text-primary); }
.appt-time { font-size: 13px; color: var(--text-sec); margin-top: 3px; }
.appt-pet { font-size: 12px; color: var(--text-muted); margin-top: 3px; }
.appt-status {
  margin-top: 8px;
  display: inline-flex;
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 11px; font-weight: 700;
}
.appt-status.confirmed { background: #dcfce7; color: #15803d; }
.appt-status.pending   { background: #fef3c7; color: #92400e; }
.appt-status.completed { background: #f0f9ff; color: #0369a1; }
.appt-status.cancelled { background: #fee2e2; color: #991b1b; }

/* ═══════════════════════════════════════════════
   BOOKING MODAL (3 steps)
═══════════════════════════════════════════════ */
.modal-overlay {
  position: fixed; inset: 0;
  background: var(--overlay);
  z-index: 500;
  display: none; align-items: flex-end; justify-content: center;
  backdrop-filter: blur(3px);
}
.modal-overlay.open { display: flex; }
.modal-sheet {
  width: 100%; max-width: 480px;
  background: var(--bg-card);
  border-radius: 28px 28px 0 0;
  padding: 0 0 32px;
  max-height: 92dvh;
  overflow-y: auto;
  animation: slideUp .35s cubic-bezier(.32,0,.67,0) both;
}
@keyframes slideUp {
  from { transform: translateY(100%); }
  to   { transform: translateY(0); }
}
.modal-handle {
  width: 40px; height: 4px;
  background: var(--border);
  border-radius: 2px;
  margin: 14px auto 0;
}
.modal-header {
  display: flex; align-items: center; gap: 14px;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border);
}
.modal-title { font-size: 18px; font-weight: 800; flex: 1; }
.modal-close {
  width: 34px; height: 34px;
  background: var(--bg-input);
  border-radius: 10px;
  display: flex; align-items: center; justify-content: center;
  font-size: 16px; color: var(--text-sec);
  cursor: pointer;
  flex-shrink: 0;
}

/* Step indicator */
.step-indicator {
  display: flex; align-items: center; justify-content: center;
  gap: 8px; padding: 16px 20px;
}
.step-dot {
  width: 32px; height: 4px;
  border-radius: 2px;
  background: var(--border);
  transition: var(--transition);
}
.step-dot.active { background: var(--green-600); width: 48px; }
.step-dot.done   { background: var(--green-400); }

.modal-body { padding: 8px 20px; }

/* Pet selector in booking */
.pet-selector {
  display: flex; gap: 10px; flex-wrap: wrap;
  margin: 12px 0;
}
.pet-select-item {
  flex: 0 0 calc(33.33% - 7px);
  background: var(--bg-input);
  border-radius: var(--radius-md);
  padding: 12px 8px;
  text-align: center;
  cursor: pointer;
  border: 2px solid transparent;
  transition: var(--transition);
}
.pet-select-item.selected {
  border-color: var(--green-500);
  background: var(--green-50);
}
.pet-select-item .ps-icon { font-size: 28px; margin-bottom: 6px; }
.pet-select-item .ps-name { font-size: 12px; font-weight: 700; color: var(--text-primary); }

/* Visit type toggle */
.visit-toggle {
  display: flex; gap: 8px; margin: 12px 0;
}
.visit-opt {
  flex: 1; padding: 12px;
  border: 2px solid var(--border);
  border-radius: var(--radius-sm);
  text-align: center; cursor: pointer;
  transition: var(--transition);
  font-size: 13px; font-weight: 700;
  color: var(--text-sec);
}
.visit-opt.selected { border-color: var(--green-500); background: var(--green-50); color: var(--green-700); }
.visit-opt .vo-icon { font-size: 22px; margin-bottom: 4px; }

/* Date/time grid */
.date-grid {
  display: flex; gap: 8px; overflow-x: auto;
  padding: 4px 0 8px; scrollbar-width: none;
  margin: 12px 0;
}
.date-grid::-webkit-scrollbar { display: none; }
.date-cell {
  flex: 0 0 56px; padding: 10px 6px;
  border: 2px solid var(--border);
  border-radius: var(--radius-sm);
  text-align: center; cursor: pointer;
  transition: var(--transition);
}
.date-cell.selected { border-color: var(--green-500); background: var(--green-600); }
.date-cell.selected .dc-day,
.date-cell.selected .dc-num { color: white; }
.date-cell.disabled { opacity: .4; pointer-events: none; }
.dc-day { font-size: 11px; color: var(--text-muted); font-weight: 600; }
.dc-num { font-size: 18px; font-weight: 800; color: var(--text-primary); }

.time-grid {
  display: flex; gap: 8px; flex-wrap: wrap;
  margin: 12px 0;
}
.time-slot {
  flex: 0 0 calc(25% - 6px);
  padding: 10px 4px;
  border: 1.5px solid var(--border);
  border-radius: var(--radius-sm);
  text-align: center; cursor: pointer;
  font-size: 13px; font-weight: 700;
  color: var(--text-sec);
  transition: var(--transition);
}
.time-slot.selected { border-color: var(--green-500); background: var(--green-600); color: white; }
.time-slot.taken { opacity: .4; pointer-events: none; text-decoration: line-through; }

/* Form inputs */
.form-group { margin: 12px 0; }
.form-label { font-size: 13px; font-weight: 700; color: var(--text-sec); margin-bottom: 6px; display: block; }
.form-input, .form-select, .form-textarea {
  width: 100%;
  background: var(--bg-input);
  border: 1.5px solid var(--border);
  border-radius: var(--radius-sm);
  padding: 12px 14px;
  font-size: 14px; color: var(--text-primary);
  transition: var(--transition);
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
  border-color: var(--green-500);
  box-shadow: 0 0 0 3px rgba(26,159,106,.1);
  background: var(--bg-card);
}
.form-textarea { resize: none; min-height: 90px; }
.form-select { appearance: none; }

/* CTA buttons */
.btn-primary {
  width: 100%;
  background: linear-gradient(135deg, var(--green-700), var(--green-500));
  color: white;
  border-radius: var(--radius-sm);
  padding: 15px;
  font-size: 16px; font-weight: 800;
  text-align: center;
  transition: var(--transition);
  box-shadow: 0 4px 16px rgba(26,127,90,.3);
  margin-top: 8px;
}
.btn-primary:hover { opacity: .92; transform: translateY(-1px); }
.btn-primary:active { transform: scale(.98); }
.btn-primary:disabled { opacity: .6; pointer-events: none; }

.btn-secondary {
  width: 100%;
  background: var(--bg-input);
  color: var(--text-sec);
  border-radius: var(--radius-sm);
  padding: 14px;
  font-size: 15px; font-weight: 700;
  text-align: center;
  transition: var(--transition);
  margin-top: 8px;
}
.btn-secondary:hover { background: var(--border); }

/* ═══════════════════════════════════════════════
   EMERGENCY MODAL
═══════════════════════════════════════════════ */
#emergency-modal .modal-header {
  background: linear-gradient(135deg, var(--red-700), var(--red-500));
}
#emergency-modal .modal-title { color: white; }
#emergency-modal .modal-close { background: rgba(255,255,255,.2); color: white; }
.emg-animal-grid {
  display: grid; grid-template-columns: repeat(4, 1fr);
  gap: 8px; margin: 12px 0;
}
.emg-animal-item {
  padding: 10px 4px;
  background: var(--bg-input);
  border: 2px solid transparent;
  border-radius: var(--radius-sm);
  text-align: center; cursor: pointer;
  transition: var(--transition);
}
.emg-animal-item.selected { border-color: var(--red-500); background: #fff5f5; }
[data-theme="dark"] .emg-animal-item.selected { background: #2d0f0f; }
.emg-animal-item .ea-icon { font-size: 24px; }
.emg-animal-item .ea-label { font-size: 11px; font-weight: 700; color: var(--text-sec); margin-top: 3px; }
.btn-emergency {
  width: 100%;
  background: linear-gradient(135deg, var(--red-700), var(--red-500));
  color: white;
  border-radius: var(--radius-sm);
  padding: 15px;
  font-size: 16px; font-weight: 800;
  text-align: center;
  transition: var(--transition);
  box-shadow: 0 4px 16px var(--red-glow);
  margin-top: 8px;
  animation: pulse-btn 2s infinite;
}
@keyframes pulse-btn {
  0%, 100% { box-shadow: 0 4px 16px var(--red-glow); }
  50% { box-shadow: 0 4px 28px rgba(239,68,68,.5); }
}
.btn-emergency:hover { opacity: .92; animation: none; }

/* Location row */
.location-row {
  display: flex; align-items: center; gap: 10px;
  background: var(--bg-input);
  border: 1.5px solid var(--border);
  border-radius: var(--radius-sm);
  padding: 12px 14px;
  cursor: pointer;
  transition: var(--transition);
  margin: 12px 0;
}
.location-row:hover { border-color: var(--green-400); }
.location-row .loc-icon { font-size: 20px; color: var(--red-500); }
.location-row .loc-text { flex: 1; font-size: 13px; color: var(--text-sec); font-weight: 600; }
.location-row .loc-badge {
  font-size: 11px; color: var(--green-600);
  background: var(--green-50);
  padding: 3px 8px; border-radius: 20px;
  font-weight: 700;
}

/* ═══════════════════════════════════════════════
   PROFILE PAGE
═══════════════════════════════════════════════ */
.profile-hero {
  background: linear-gradient(135deg, var(--green-800), var(--green-600));
  padding: 32px 20px 48px;
  text-align: center;
}
.profile-avatar {
  width: 86px; height: 86px;
  border-radius: 50%;
  background: rgba(255,255,255,.2);
  margin: 0 auto 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 40px;
  border: 3px solid rgba(255,255,255,.4);
}
.profile-name { font-size: 22px; font-weight: 800; color: white; }
.profile-role { font-size: 13px; color: rgba(255,255,255,.75); font-weight: 500; margin-top: 4px; }
.profile-edit-btn {
  margin-top: 14px;
  display: inline-flex; align-items: center; gap: 6px;
  background: rgba(255,255,255,.15);
  border: 1px solid rgba(255,255,255,.3);
  border-radius: 20px;
  padding: 6px 16px;
  font-size: 13px; font-weight: 700; color: white;
  cursor: pointer;
}

.settings-card {
  margin: -22px 16px 0;
  background: var(--bg-card);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  overflow: hidden;
  position: relative; z-index: 5;
}
.settings-item {
  display: flex; align-items: center; gap: 14px;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border);
  cursor: pointer;
  transition: var(--transition);
}
.settings-item:last-child { border-bottom: none; }
.settings-item:hover { background: var(--bg-input); }
.si-icon {
  width: 40px; height: 40px;
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 20px; flex-shrink: 0;
}
.si-text { flex: 1; }
.si-label { font-size: 14px; font-weight: 700; color: var(--text-primary); }
.si-sub { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
.si-arrow { font-size: 16px; color: var(--text-muted); }

/* Toggle switch */
.toggle-switch {
  width: 46px; height: 26px;
  background: var(--border);
  border-radius: 13px;
  position: relative; cursor: pointer;
  transition: var(--transition);
  flex-shrink: 0;
}
.toggle-switch.on { background: var(--green-500); }
.toggle-switch::after {
  content: '';
  position: absolute; top: 3px; left: 3px;
  width: 20px; height: 20px;
  background: white;
  border-radius: 50%;
  transition: var(--transition);
  box-shadow: 0 1px 4px rgba(0,0,0,.2);
}
.toggle-switch.on::after { left: 23px; }

/* Language selector */
.lang-select {
  display: flex; gap: 6px;
}
.lang-btn {
  padding: 4px 10px;
  border-radius: 8px;
  font-size: 12px; font-weight: 700;
  background: var(--bg-input);
  color: var(--text-sec);
  cursor: pointer;
  transition: var(--transition);
  border: 1.5px solid transparent;
}
.lang-btn.active { background: var(--green-50); color: var(--green-700); border-color: var(--green-400); }

/* Logout */
.logout-item { color: var(--red-500) !important; }
.logout-item .si-label { color: var(--red-500); }
.logout-item .si-icon { background: #fff5f5; }

/* ═══════════════════════════════════════════════
   VET DASHBOARD
═══════════════════════════════════════════════ */
.dash-stats {
  display: grid; grid-template-columns: 1fr 1fr;
  gap: 10px; padding: 16px;
}
.dash-stat-card {
  background: var(--bg-card);
  border-radius: var(--radius-md);
  padding: 16px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-sm);
}
.dsc-num { font-size: 28px; font-weight: 900; color: var(--green-600); }
.dsc-label { font-size: 12px; color: var(--text-sec); font-weight: 600; margin-top: 2px; }
.dash-stat-card.accent { background: linear-gradient(135deg, var(--green-700), var(--green-500)); border: none; }
.dash-stat-card.accent .dsc-num,
.dash-stat-card.accent .dsc-label { color: white; }

.request-card {
  background: var(--bg-card);
  border-radius: var(--radius-lg);
  padding: 16px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-sm);
  margin: 0 16px 10px;
}
.request-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
.request-user { font-size: 15px; font-weight: 800; color: var(--text-primary); }
.request-time { font-size: 11px; color: var(--text-muted); }
.request-detail { font-size: 13px; color: var(--text-sec); margin-bottom: 12px; }
.request-actions { display: flex; gap: 8px; }
.btn-accept {
  flex: 1; padding: 10px;
  background: linear-gradient(135deg, var(--green-600), var(--green-500));
  color: white; border-radius: var(--radius-sm);
  font-size: 14px; font-weight: 700; text-align: center;
}
.btn-reject {
  flex: 1; padding: 10px;
  background: var(--bg-input);
  color: var(--red-500); border-radius: var(--radius-sm);
  font-size: 14px; font-weight: 700; text-align: center;
  border: 1.5px solid var(--red-500);
}

/* ═══════════════════════════════════════════════
   SUCCESS STATE
═══════════════════════════════════════════════ */
.success-state {
  text-align: center; padding: 40px 20px;
  display: none;
}
.success-state.show { display: block; }
.success-icon {
  width: 80px; height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--green-400), var(--green-600));
  display: flex; align-items: center; justify-content: center;
  font-size: 36px; margin: 0 auto 16px;
  animation: scaleIn .4s cubic-bezier(.175,.885,.32,1.275) both;
}
@keyframes scaleIn {
  from { transform: scale(0); opacity: 0; }
  to   { transform: scale(1); opacity: 1; }
}
.success-title { font-size: 20px; font-weight: 800; color: var(--text-primary); margin-bottom: 8px; }
.success-sub { font-size: 14px; color: var(--text-sec); line-height: 1.6; }

/* ═══════════════════════════════════════════════
   HEALTH TIPS
═══════════════════════════════════════════════ */
.tip-card {
  background: var(--bg-card);
  border-radius: var(--radius-md);
  padding: 16px;
  border: 1px solid var(--border);
  display: flex; align-items: flex-start; gap: 12px;
  margin: 0 16px 10px;
}
.tip-icon {
  width: 42px; height: 42px;
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 22px; flex-shrink: 0;
  background: var(--green-50);
}
.tip-text h4 { font-size: 14px; font-weight: 800; color: var(--text-primary); margin-bottom: 4px; }
.tip-text p { font-size: 12px; color: var(--text-sec); line-height: 1.5; }

/* ═══════════════════════════════════════════════
   TOAST NOTIFICATION
═══════════════════════════════════════════════ */
#toast-container {
  position: fixed; top: 16px; left: 50%;
  transform: translateX(-50%);
  z-index: 9999; width: 90%; max-width: 400px;
  pointer-events: none;
}
.toast {
  background: var(--bg-card);
  border-radius: var(--radius-md);
  padding: 14px 18px;
  display: flex; align-items: center; gap: 12px;
  box-shadow: var(--shadow-xl);
  border: 1px solid var(--border);
  margin-bottom: 8px;
  animation: toastIn .3s ease both;
  pointer-events: auto;
}
.toast.removing { animation: toastOut .3s ease both; }
@keyframes toastIn {
  from { opacity: 0; transform: translateY(-20px) scale(.95); }
  to   { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes toastOut {
  from { opacity: 1; transform: translateY(0) scale(1); }
  to   { opacity: 0; transform: translateY(-20px) scale(.95); }
}
.toast-icon { font-size: 20px; flex-shrink: 0; }
.toast-msg { font-size: 13px; font-weight: 700; color: var(--text-primary); flex: 1; }
.toast.success .toast-icon { color: var(--green-500); }
.toast.error   .toast-icon { color: var(--red-500); }
.toast.info    .toast-icon { color: var(--blue-500); }

/* ═══════════════════════════════════════════════
   EMPTY STATE
═══════════════════════════════════════════════ */
.empty-state {
  text-align: center; padding: 48px 24px;
  color: var(--text-muted);
}
.empty-state .empty-icon { font-size: 52px; margin-bottom: 12px; opacity: .6; }
.empty-state p { font-size: 14px; }

/* ═══════════════════════════════════════════════
   LOADER
═══════════════════════════════════════════════ */
.loader {
  display: flex; align-items: center; justify-content: center;
  padding: 32px;
}
.spinner {
  width: 32px; height: 32px;
  border: 3px solid var(--border);
  border-top-color: var(--green-500);
  border-radius: 50%;
  animation: spin .7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }

/* ═══════════════════════════════════════════════
   SKELETON LOADER
═══════════════════════════════════════════════ */
.skeleton {
  background: linear-gradient(90deg, var(--border) 25%, var(--bg-input) 50%, var(--border) 75%);
  background-size: 200% 100%;
  animation: shimmer 1.2s ease-in-out infinite;
  border-radius: 8px;
}
@keyframes shimmer {
  from { background-position: 200% 0; }
  to   { background-position: -200% 0; }
}

/* ═══════════════════════════════════════════════
   RESPONSIVE DESKTOP ADJUSTMENTS
═══════════════════════════════════════════════ */
@media (min-width: 768px) {
  .app-header { display: none; }
  #page-wrapper { padding-bottom: 0; }
  .vets-list { display: grid; grid-template-columns: 1fr 1fr; }
  .dash-stats { grid-template-columns: repeat(4, 1fr); }
}
@media (min-width: 1200px) {
  .vets-list { grid-template-columns: 1fr 1fr; }
}

/* ═══════════════════════════════════════════════
   SCROLLBAR STYLING
═══════════════════════════════════════════════ */
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }

/* ═══════════════════════════════════════════════
   SAFE AREA (iPhone notch)
═══════════════════════════════════════════════ */
#bottom-nav { padding-bottom: env(safe-area-inset-bottom, 0); }
</style>
</head>
<body>

<!-- ══════════════════════════════════════════
     TOAST CONTAINER
══════════════════════════════════════════ -->
<div id="toast-container"></div>

<!-- ══════════════════════════════════════════
     APP SHELL
══════════════════════════════════════════ -->
<div id="app">

  <!-- SIDEBAR (Desktop) -->
  <nav id="sidebar">
    <div class="sidebar-logo">
      <a href="home.php"><img src="assets/img/logo.png?v=3" alt="VetNet" style="height:44px;object-fit:contain;"></a>
    </div>
    <div class="sidebar-emergency" onclick="handleEmergencyBtn()">
      <span style="font-size:24px;">🚨</span>
      <span data-i18n="home_emergency_cta">طوارئ</span>
    </div>
    <div class="sidebar-nav-item active" onclick="showPage('home')">
      <span class="sn-icon">🏠</span>
      <span data-i18n="nav_home">الرئيسية</span>
    </div>
    <div class="sidebar-nav-item" onclick="showPage('search')">
      <span class="sn-icon">🔍</span>
      <span data-i18n="nav_search">البحث</span>
    </div>
    <div class="sidebar-nav-item" onclick="showPage('appointments')">
      <span class="sn-icon">📅</span>
      <span data-i18n="nav_appointments">المواعيد</span>
    </div>
    <div class="sidebar-nav-item" onclick="showPage('profile')">
      <span class="sn-icon">👤</span>
      <span data-i18n="nav_profile">حسابي</span>
    </div>
  </nav>

  <!-- MAIN CONTENT -->
  <div id="page-wrapper">

    <!-- TOP HEADER -->
    <header class="app-header" id="main-header">
<a href="home.php"><img src="assets/img/logo.png?v=3" alt="VetNet" style="height:40px;object-fit:contain;"></a>
      <div class="header-title"><span data-i18n="app_name">بيطري</span></div>
      <div class="header-actions">
        <button class="icon-btn" onclick="showPage('search')" title="بحث">🔍</button>
        <button class="icon-btn" id="notif-btn" title="إشعارات">
          🔔
          <span class="notif-dot" id="notif-dot"></span>
        </button>
      </div>
    </header>

    <!-- ══ PAGE: HOME ══ -->
    <div id="page-home" class="page active">

      <!-- Hero Banner -->
      <div class="home-hero">
        <div class="hero-greeting" id="greeting-text" data-user="<?php echo h($user["name"] ?? ""); ?>">مرحباً</div>
        <div class="hero-name" id="user-name-display"><?php echo h($user["name"] ?? "المستخدم"); ?> 👋</div>
        <div class="hero-stats">
          <div class="hero-stat">
            <div class="stat-num" id="stat-pets">0</div>
            <div class="stat-label" data-i18n="home_my_pets">حيواناتي</div>
          </div>
          <div class="hero-stat">
            <div class="stat-num" id="stat-appts">0</div>
            <div class="stat-label" data-i18n="home_upcoming">مواعيد قادمة</div>
          </div>
          <div class="hero-stat">
            <div class="stat-num" id="stat-vets">...</div>
            <div class="stat-label" data-i18n="home_nearby_vets">أطباء قريبون</div>
          </div>
        </div>
      </div>

      <!-- Emergency Card -->
      <div class="emergency-card" onclick="openEmergency()">
        <div class="emg-icon">🚨</div>
        <div class="emg-text">
          <h3 data-i18n="home_emergency_cta">🚨 طوارئ</h3>
          <p data-i18n="home_emergency_sub">اتصال فوري بأقرب طبيب بيطري</p>
        </div>
        <div class="emg-arrow">←</div>
      </div>

      <!-- CLIENT: Unified tabs (pets + farm) -->
      <div id="client-tabs-bar" style="display:flex;gap:0;background:var(--bg-input);border-radius:12px;padding:3px;margin-bottom:16px;">
        <button id="ctab-pets" onclick="switchClientTab('pets')" style="flex:1;padding:10px 8px;border-radius:10px;border:none;font-size:14px;font-weight:800;font-family:'Tajawal',sans-serif;cursor:pointer;background:var(--bg-card);color:var(--green-700);box-shadow:0 2px 8px rgba(0,0,0,.08);transition:.2s;">🐾 حيواناتي</button>
        <button id="ctab-farm" onclick="switchClientTab('farm')" style="flex:1;padding:10px 8px;border-radius:10px;border:none;font-size:14px;font-weight:800;font-family:'Tajawal',sans-serif;cursor:pointer;background:none;color:var(--text-muted);transition:.2s;">🚜 مزرعتي</button>
      </div>

      <!-- PETS TAB -->
      <div id="client-view-pets">
        <div id="pets-section">
          <div class="section-header">
            <div class="section-title" id="pets-section-title">حيواناتي</div>
            <div class="section-link" onclick="showPage('profile')">عرض الكل</div>
          </div>
          <div class="pets-scroll" id="pets-container"></div>
        </div>
      </div>

      <!-- FARM TAB -->
      <div id="client-view-farm" style="display:none;">
        <div class="section-header">
          <div class="section-title">🚜 مزرعتي</div>
          <div class="section-link" onclick="openAddHerd()">+ إضافة</div>
        </div>
        <div class="herd-list" id="herd-container"></div>
        <button onclick="window.location.href='pages/farm-herds.php'"
          style="width:100%;margin-top:14px;background:linear-gradient(135deg,var(--green-800),var(--green-500));color:#fff;border:none;border-radius:12px;padding:13px;font-size:15px;font-weight:800;font-family:'Tajawal',sans-serif;cursor:pointer;">
          📋 إدارة المزرعة الكاملة
        </button>
      </div>

      <!-- Nearby Vets -->
      <div class="section-header" style="margin-top:8px;">
        <div class="section-title" data-i18n="home_nearby_vets">أطباء قريبون</div>
        <div class="section-link" onclick="showPage('search')" data-i18n="home_view_all">عرض الكل</div>
      </div>
      <div class="vets-list" id="home-vets-container">
        <div class="loader"><div class="spinner"></div></div>
      </div>

      <!-- Health Tips -->
      <div class="section-header" style="margin-top:8px;">
        <div class="section-title" data-i18n="home_health_tips">نصائح صحية</div>
      </div>
      <div id="tips-container"></div>

      <div style="height:24px;"></div>
    </div><!-- /page-home -->

    <!-- ══ PAGE: SEARCH ══ -->
    <div id="page-search" class="page">
      <div class="search-bar-wrap">
        <div class="search-bar">
          <span class="search-icon">🔍</span>
          <input type="text" id="vet-search-input" data-i18n-placeholder="vet_search_placeholder" placeholder="ابحث عن طبيب بيطري..." oninput="debounceSearch()">
        </div>
        <div class="filter-chips">
          <div class="chip active" data-filter="all">الكل</div>
          <div class="chip" data-filter="available">متاح الآن</div>
          <div class="chip" data-filter="home_visit">زيارة منزلية</div>
          <div class="chip" data-filter="emergency">طوارئ</div>
          <div class="chip" data-filter="cattle">مواشي</div>
          <div class="chip" data-filter="pets">حيوانات أليفة</div>
        </div>
      </div>
      <div class="vets-list" id="search-vets-container" style="margin-top:12px;">
        <div class="loader"><div class="spinner"></div></div>
      </div>
      <div style="height:24px;"></div>
    </div><!-- /page-search -->

    <!-- ══ PAGE: APPOINTMENTS ══ -->
    <div id="page-appointments" class="page">
      <div class="tab-bar">
        <div class="tab-item active" onclick="switchApptTab('upcoming', this)" data-i18n="appt_upcoming">القادمة</div>
        <div class="tab-item" onclick="switchApptTab('pending', this)" data-i18n="appt_pending">بانتظار التأكيد</div>
        <div class="tab-item" onclick="switchApptTab('past', this)" data-i18n="appt_past">السابقة</div>
      </div>
      <div class="appt-list" id="appt-container">
        <!-- Populated by JS -->
      </div>
    </div><!-- /page-appointments -->

    <!-- ══ PAGE: PROFILE ══ -->
    <div id="page-profile" class="page">
      <div class="profile-hero">
        <div class="profile-avatar" id="profile-avatar">👤</div>
        <div class="profile-name" id="profile-name"><?php echo h($user["name"] ?? "المستخدم"); ?></div>
        <div class="profile-role" id="profile-role">
<?php
$role_labels = [
    'client'     => 'عميل — حيوان أليف / مزرعة',
    'pet_owner'  => 'عميل — حيوان أليف / مزرعة',
    'farm_owner' => 'عميل — حيوان أليف / مزرعة',
    'vet'        => 'طبيب بيطري',
    'admin'      => 'مشرف المنصة',
];
echo htmlspecialchars($role_labels[$role] ?? 'عميل');
?>
</div>
        <button class="profile-edit-btn" onclick="openEditProfile()">✏️ <span data-i18n="profile_edit">تعديل الملف</span></button>
      </div>

      <div class="settings-card" style="margin-top:-22px;">
        <!-- Theme -->
        <div class="settings-item" onclick="toggleTheme()">
          <div class="si-icon" style="background:var(--green-50);" id="theme-icon">🌙</div>
          <div class="si-text">
            <div class="si-label" data-i18n="profile_dark_mode">الوضع الليلي</div>
            <div class="si-sub" id="theme-sub">وضع النهار</div>
          </div>
          <div class="toggle-switch <?php echo ($theme==='dark'?'on':''); ?>" id="theme-toggle"></div>
        </div>
        <!-- Language -->
        <div class="settings-item">
          <div class="si-icon" style="background:var(--blue-50);">🌐</div>
          <div class="si-text">
            <div class="si-label" data-i18n="profile_language">اللغة</div>
          </div>
          <div class="lang-select">
            <div class="lang-btn active" onclick="setLang('ar')">ع</div>
            <div class="lang-btn" onclick="setLang('fr')">Fr</div>
            <div class="lang-btn" onclick="setLang('en')">En</div>
          </div>
        </div>
        <!-- Notifications -->
        <div class="settings-item">
          <div class="si-icon" style="background:#fef3c7;">🔔</div>
          <div class="si-text">
            <div class="si-label" data-i18n="profile_notifications">الإشعارات</div>
          </div>
          <div class="toggle-switch on" id="notif-toggle" onclick="this.classList.toggle('on')"></div>
        </div>
        <!-- CLIENT items -->
        <?php if ($role === 'client'): ?>
        <div class="settings-item" onclick="showPage('home'); setTimeout(function(){switchClientTab('pets');},100);" style="cursor:pointer;">
          <div class="si-icon" style="background:var(--green-50);">🐾</div>
          <div class="si-text">
            <div class="si-label">حيواناتي</div>
            <div class="si-sub" id="pets-count-label">0 حيوانات</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <div class="settings-item" onclick="showPage('home'); setTimeout(function(){switchClientTab('farm');},100);" style="cursor:pointer;">
          <div class="si-icon" style="background:#fff7ed;">🚜</div>
          <div class="si-text">
            <div class="si-label">مزرعتي</div>
            <div class="si-sub">إدارة القطعان</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <div class="settings-item" onclick="showPage('appointments')" style="cursor:pointer;">
          <div class="si-icon" style="background:var(--blue-50);">📋</div>
          <div class="si-text">
            <div class="si-label">سجل الزيارات</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <?php elseif ($role === 'vet'): ?>
        <!-- VET items -->
        <div class="settings-item" onclick="window.location.href='pages/vet-clinic-setup.php'" style="cursor:pointer;">
          <div class="si-icon" style="background:var(--green-50);">🏥</div>
          <div class="si-text">
            <div class="si-label">إدارة العيادة</div>
            <div class="si-sub">الموقع والمعلومات</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <div class="settings-item" onclick="showPage('home')" style="cursor:pointer;">
          <div class="si-icon" style="background:#eff6ff;">📅</div>
          <div class="si-text">
            <div class="si-label">مواعيدي</div>
            <div class="si-sub">الطلبات والجداول</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <div class="settings-item" onclick="window.location.href='pages/vet-profile.php'" style="cursor:pointer;">
          <div class="si-icon" style="background:#fef3c7;">⭐</div>
          <div class="si-text">
            <div class="si-label">تقييماتي</div>
            <div class="si-sub">آراء العملاء</div>
          </div>
          <div class="si-arrow">←</div>
        </div>
        <?php endif; ?>
        <!-- Logout -->
        <div class="settings-item logout-item" onclick="confirmLogout()">
          <div class="si-icon" style="background:#fff5f5;">🚪</div>
          <div class="si-text">
            <div class="si-label" data-i18n="profile_logout">تسجيل الخروج</div>
          </div>
        </div>
      </div>

      <div style="height:24px;"></div>
    </div><!-- /page-profile -->

    <!-- ══ PAGE: VET DASHBOARD ══ -->
    <div id="page-vet-dashboard" class="page" style="display:none;">
      <div class="dash-stats">
        <div class="dash-stat-card accent">
          <div class="dsc-num">5</div>
          <div class="dsc-label" data-i18n="vet_dash_requests">طلبات جديدة</div>
        </div>
        <div class="dash-stat-card">
          <div class="dsc-num">8</div>
          <div class="dsc-label" data-i18n="vet_dash_today">مواعيد اليوم</div>
        </div>
        <div class="dash-stat-card">
          <div class="dsc-num">4.9⭐</div>
          <div class="dsc-label" data-i18n="vet_rating">التقييم</div>
        </div>
        <div class="dash-stat-card">
          <div class="dsc-num" id="vet-earnings">0</div>
          <div class="dsc-label" data-i18n="vet_dash_earnings">دج</div>
        </div>
      </div>

      <div class="section-header">
        <div class="section-title" data-i18n="vet_dash_requests">طلبات جديدة</div>
      </div>

      <div class="request-card" id="vet-requests-container">
        <!-- Populated by JS -->
      </div>
    </div><!-- /page-vet-dashboard -->

  </div><!-- /page-wrapper -->

  <!-- BOTTOM NAV (Mobile) -->
  <nav id="bottom-nav">
    <div class="nav-item active" onclick="showPage('home')" data-page="home">
      <span class="nav-icon">🏠</span>
      <span class="nav-label" data-i18n="nav_home">الرئيسية</span>
    </div>
    <div class="nav-item" onclick="showPage('search')" data-page="search">
      <span class="nav-icon">🔍</span>
      <span class="nav-label" data-i18n="nav_search">البحث</span>
    </div>
    <div class="nav-item emergency" onclick="openEmergency()">
      <div class="nav-icon-wrap">🚨</div>
      <span class="nav-label" data-i18n="nav_emergency">طوارئ</span>
    </div>
    <div class="nav-item" onclick="showPage('appointments')" data-page="appointments">
      <span class="nav-icon">📅</span>
      <span class="nav-label" data-i18n="nav_appointments">المواعيد</span>
    </div>
    <div class="nav-item" onclick="showPage('profile')" data-page="profile">
      <span class="nav-icon">👤</span>
      <span class="nav-label" data-i18n="nav_profile">حسابي</span>
    </div>
  </nav>

</div><!-- /app -->

<!-- ══════════════════════════════════════════
     BOOKING MODAL
══════════════════════════════════════════ -->
<div class="modal-overlay" id="booking-modal">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <div class="modal-header">
      <div class="modal-title" data-i18n="book_title">حجز موعد</div>
      <div class="modal-close" onclick="closeModal('booking-modal')">✕</div>
    </div>
    <div class="step-indicator">
      <div class="step-dot active" id="sdot-1"></div>
      <div class="step-dot" id="sdot-2"></div>
      <div class="step-dot" id="sdot-3"></div>
    </div>
    <div class="modal-body">
      <!-- Step 1: Choose pet -->
      <div id="book-step-1">
        <div class="form-label" data-i18n="book_select_pet">اختر حيوانك</div>
        <div class="pet-selector" id="book-pet-selector"></div>

        <div class="form-label" style="margin-top:16px;" data-i18n="book_visit_type">نوع الزيارة</div>
        <div class="visit-toggle">
          <div class="visit-opt selected" onclick="selectVisit('clinic', this)">
            <div class="vo-icon">🏥</div>
            <div data-i18n="book_clinic_visit">زيارة عيادة</div>
          </div>
          <div class="visit-opt" onclick="selectVisit('home', this)">
            <div class="vo-icon">🏠</div>
            <div data-i18n="book_home_visit">زيارة منزلية</div>
          </div>
        </div>
        <button class="btn-primary" onclick="bookStep(2)">
          <span data-i18n="next">التالي</span> →
        </button>
      </div>

      <!-- Step 2: Date & Time -->
      <div id="book-step-2" style="display:none;">
        <div class="form-label" data-i18n="book_select_date">اختر التاريخ</div>
        <div class="date-grid" id="date-grid"></div>
        <div class="form-label" data-i18n="book_select_time">اختر الوقت</div>
        <div class="time-grid" id="time-grid"></div>
        <div class="form-group">
          <label class="form-label" data-i18n="book_notes">ملاحظات</label>
          <textarea class="form-textarea" id="book-notes" data-i18n-placeholder="book_notes_placeholder" placeholder="اكتب أعراض الحيوان..."></textarea>
        </div>
        <button class="btn-primary" onclick="bookStep(3)" data-i18n="next">التالي →</button>
        <button class="btn-secondary" onclick="bookStep(1)">← <span data-i18n="back">رجوع</span></button>
      </div>

      <!-- Step 3: Confirm -->
      <div id="book-step-3" style="display:none;">
        <div id="book-summary" style="background:var(--bg-input);border-radius:var(--radius-md);padding:16px;margin-bottom:16px;"></div>
        <button class="btn-primary" onclick="submitBooking()" id="confirm-book-btn">
          ✅ <span data-i18n="book_confirm">تأكيد الحجز</span>
        </button>
        <button class="btn-secondary" onclick="bookStep(2)">← <span data-i18n="back">رجوع</span></button>
      </div>

      <!-- Success -->
      <div class="success-state" id="book-success">
        <div class="success-icon">✅</div>
        <div class="success-title" data-i18n="book_success">تم الحجز بنجاح!</div>
        <p class="success-sub">سيتم إشعارك عند تأكيد الطبيب للموعد.</p>
        <button class="btn-primary" onclick="closeModal('booking-modal')" style="margin-top:20px;" data-i18n="done">تم</button>
      </div>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════════
     EMERGENCY MODAL
══════════════════════════════════════════ -->
<div class="modal-overlay" id="emergency-modal">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <div class="modal-header">
      <div class="modal-title" data-i18n="emergency_title">طلب طوارئ 🚨</div>
      <div class="modal-close" onclick="closeModal('emergency-modal')">✕</div>
    </div>
    <div class="modal-body">
      <div id="emg-form">
        <p style="font-size:13px;color:var(--text-sec);margin-bottom:16px;" data-i18n="emergency_subtitle">
          سيتم إرسال طلبك لأقرب طبيب بيطري متاح فوراً
        </p>

        <div class="form-label" data-i18n="emergency_select_animal">نوع الحيوان</div>
        <div class="emg-animal-grid" id="emg-animal-grid">
          <div class="emg-animal-item" data-animal="cat" onclick="selectAnimal(this)">
            <div class="ea-icon">🐱</div>
            <div class="ea-label" data-i18n="pet_cat">قط</div>
          </div>
          <div class="emg-animal-item" data-animal="dog" onclick="selectAnimal(this)">
            <div class="ea-icon">🐕</div>
            <div class="ea-label" data-i18n="pet_dog">كلب</div>
          </div>
          <div class="emg-animal-item" data-animal="cow" onclick="selectAnimal(this)">
            <div class="ea-icon">🐄</div>
            <div class="ea-label" data-i18n="pet_cow">بقرة</div>
          </div>
          <div class="emg-animal-item" data-animal="sheep" onclick="selectAnimal(this)">
            <div class="ea-icon">🐑</div>
            <div class="ea-label" data-i18n="pet_sheep">خروف</div>
          </div>
          <div class="emg-animal-item" data-animal="horse" onclick="selectAnimal(this)">
            <div class="ea-icon">🐴</div>
            <div class="ea-label" data-i18n="pet_horse">حصان</div>
          </div>
          <div class="emg-animal-item" data-animal="bird" onclick="selectAnimal(this)">
            <div class="ea-icon">🐦</div>
            <div class="ea-label" data-i18n="pet_bird">طائر</div>
          </div>
          <div class="emg-animal-item" data-animal="rabbit" onclick="selectAnimal(this)">
            <div class="ea-icon">🐰</div>
            <div class="ea-label" data-i18n="pet_rabbit">أرنب</div>
          </div>
          <div class="emg-animal-item" data-animal="other" onclick="selectAnimal(this)">
            <div class="ea-icon">🐾</div>
            <div class="ea-label" data-i18n="pet_other">أخرى</div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label" data-i18n="emergency_problem">وصف المشكلة</label>
          <textarea class="form-textarea" id="emg-problem" data-i18n-placeholder="emergency_problem_placeholder"
            placeholder="اكتب الأعراض بسرعة..." rows="3"></textarea>
        </div>

        <div class="location-row" onclick="getEmgLocation()" id="emg-location-btn">
          <span class="loc-icon">📍</span>
          <span class="loc-text" data-i18n="emergency_get_location" id="emg-loc-text">تحديد الموقع تلقائياً</span>
          <span class="loc-badge" id="emg-loc-badge" style="display:none;">✓ تم</span>
        </div>

        <button class="btn-emergency" onclick="submitEmergency()" id="emg-submit-btn">
          🚨 <span data-i18n="emergency_send">إرسال طلب الطوارئ</span>
        </button>
      </div>

      <!-- Emergency Success -->
      <div class="success-state" id="emg-success">
        <div class="success-icon" style="background:linear-gradient(135deg,var(--red-600),var(--red-500));">🚨</div>
        <div class="success-title" data-i18n="emergency_sent">تم إرسال الطلب!</div>
        <p class="success-sub" data-i18n="emergency_vet_notified">
          تم إشعار أقرب طبيب بيطري، سيتصل بك خلال دقائق.
        </p>
        <div id="emg-vet-info" style="margin-top:16px;padding:16px;background:var(--bg-input);border-radius:var(--radius-md);display:none;">
          <div style="font-weight:800;font-size:15px;color:var(--text-primary);" id="emg-vet-name"></div>
          <div style="font-size:13px;color:var(--green-600);margin-top:4px;" id="emg-vet-dist"></div>
        </div>
        <button class="btn-primary" onclick="closeModal('emergency-modal')" style="margin-top:20px;" data-i18n="done">تم</button>
      </div>
    </div>
  </div>
</div>

<!-- ══ ADD PET MODAL ══ -->
<div class="modal-overlay" id="add-pet-modal">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <div class="modal-header">
      <div style="font-size:26px;">🐾</div>
      <div class="modal-title">إضافة حيوان جديد</div>
      <div class="modal-close" onclick="closeModal('add-pet-modal')">✕</div>
    </div>
    <div style="padding:20px;">

      <!-- Species selector -->
      <div style="margin-bottom:18px;">
        <label style="font-size:11px;font-weight:800;color:var(--text-secondary);letter-spacing:.06em;text-transform:uppercase;margin-bottom:10px;display:block;">نوع الحيوان</label>
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;" id="species-grid">
          <button class="species-btn on" data-species="cat" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐱</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">قط</span>
          </button>
          <button class="species-btn" data-species="dog" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐕</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">كلب</span>
          </button>
          <button class="species-btn" data-species="bird" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐦</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">طائر</span>
          </button>
          <button class="species-btn" data-species="rabbit" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐰</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">أرنب</span>
          </button>
          <button class="species-btn" data-species="horse" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐴</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">حصان</span>
          </button>
          <button class="species-btn" data-species="cow" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐄</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">بقرة</span>
          </button>
          <button class="species-btn" data-species="sheep" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐑</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">خروف</span>
          </button>
          <button class="species-btn" data-species="other" onclick="pickSpecies(this)">
            <span style="font-size:26px;">🐾</span>
            <span style="font-size:11px;font-weight:700;margin-top:4px;display:block;">أخرى</span>
          </button>
        </div>
      </div>

      <!-- Name -->
      <div style="margin-bottom:14px;">
        <label style="font-size:11px;font-weight:800;color:var(--text-secondary);letter-spacing:.06em;text-transform:uppercase;margin-bottom:7px;display:block;">
          اسم الحيوان <span style="color:var(--green-500);">*</span>
        </label>
        <div style="position:relative;background:var(--bg-input);border:1.5px solid transparent;border-radius:12px;transition:.2s;" id="pet-name-wrap">
          <input type="text" id="pet-name" maxlength="30"
            style="width:100%;background:none;border:none;padding:13px 46px 13px 16px;font-size:15px;color:var(--text-primary);font-family:'Tajawal',sans-serif;outline:none;"
            placeholder="مثال: لولو، ماكس..."
            oninput="updatePetPreview()"
            onfocus="this.parentElement.style.borderColor='var(--green-500)';this.parentElement.style.boxShadow='0 0 0 3px rgba(16,185,129,.1)'"
            onblur="this.parentElement.style.borderColor='transparent';this.parentElement.style.boxShadow='none'">
          <span style="position:absolute;right:14px;top:50%;transform:translateY(-50%);font-size:18px;opacity:.4;">✏️</span>
        </div>
        <div id="err-pet-name" style="font-size:12px;color:var(--red-500,#ef4444);font-weight:700;margin-top:4px;display:none;">الرجاء إدخال اسم الحيوان</div>
      </div>

      <!-- Breed -->
      <div style="margin-bottom:14px;">
        <label style="font-size:11px;font-weight:800;color:var(--text-secondary);letter-spacing:.06em;text-transform:uppercase;margin-bottom:7px;display:block;">السلالة (اختياري)</label>
        <div style="background:var(--bg-input);border:1.5px solid transparent;border-radius:12px;transition:.2s;">
          <input type="text" id="pet-breed" maxlength="40"
            style="width:100%;background:none;border:none;padding:13px 16px;font-size:15px;color:var(--text-primary);font-family:'Tajawal',sans-serif;outline:none;"
            placeholder="مثال: شيرازي، هاسكي..."
            onfocus="this.parentElement.style.borderColor='var(--green-500)'"
            onblur="this.parentElement.style.borderColor='transparent'">
        </div>
      </div>

      <!-- Age + Weight row -->
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px;">
        <div>
          <label style="font-size:11px;font-weight:800;color:var(--text-secondary);letter-spacing:.06em;text-transform:uppercase;margin-bottom:7px;display:block;">العمر</label>
          <div style="background:var(--bg-input);border:1.5px solid transparent;border-radius:12px;transition:.2s;display:flex;align-items:center;">
            <input type="number" id="pet-age" min="0" max="30" step="0.5"
              style="width:100%;background:none;border:none;padding:13px 10px 13px 14px;font-size:15px;color:var(--text-primary);font-family:'Tajawal',sans-serif;outline:none;"
              placeholder="0"
              onfocus="this.parentElement.style.borderColor='var(--green-500)'"
              onblur="this.parentElement.style.borderColor='transparent'">
            <span style="padding-left:10px;font-size:12px;color:var(--text-muted);font-weight:700;white-space:nowrap;">سنة</span>
          </div>
        </div>
        <div>
          <label style="font-size:11px;font-weight:800;color:var(--text-secondary);letter-spacing:.06em;text-transform:uppercase;margin-bottom:7px;display:block;">الوزن</label>
          <div style="background:var(--bg-input);border:1.5px solid transparent;border-radius:12px;transition:.2s;display:flex;align-items:center;">
            <input type="number" id="pet-weight" min="0" max="999" step="0.1"
              style="width:100%;background:none;border:none;padding:13px 10px 13px 14px;font-size:15px;color:var(--text-primary);font-family:'Tajawal',sans-serif;outline:none;"
              placeholder="0"
              onfocus="this.parentElement.style.borderColor='var(--green-500)'"
              onblur="this.parentElement.style.borderColor='transparent'">
            <span style="padding-left:10px;font-size:12px;color:var(--text-muted);font-weight:700;white-space:nowrap;">كغ</span>
          </div>
        </div>
      </div>

      <!-- Vaccinated toggle -->
      <div style="display:flex;align-items:center;justify-content:space-between;background:var(--bg-input);border-radius:12px;padding:14px 16px;margin-bottom:20px;">
        <div>
          <div style="font-size:14px;font-weight:700;">💉 ملقّح</div>
          <div style="font-size:12px;color:var(--text-muted);margin-top:2px;">هل حيوانك حصل على تطعيماته؟</div>
        </div>
        <button class="toggle-btn" id="vacc-toggle" onclick="this.classList.toggle('on')" style="width:46px;height:26px;border-radius:13px;background:var(--border);position:relative;transition:.2s;flex-shrink:0;">
          <span style="position:absolute;top:3px;right:3px;width:20px;height:20px;background:#fff;border-radius:50%;transition:.2s;box-shadow:0 1px 4px rgba(0,0,0,.2);"></span>
        </button>
      </div>

      <!-- Preview card -->
      <div id="pet-preview" style="background:linear-gradient(135deg,var(--green-800,#065f46),var(--green-600,#059669));border-radius:16px;padding:16px;margin-bottom:20px;display:flex;align-items:center;gap:14px;">
        <div style="width:54px;height:54px;border-radius:16px;background:rgba(255,255,255,.18);border:2px solid rgba(255,255,255,.3);display:flex;align-items:center;justify-content:center;font-size:28px;" id="preview-emoji">🐱</div>
        <div>
          <div style="font-size:16px;font-weight:900;color:#fff;" id="preview-name">اسم الحيوان</div>
          <div style="font-size:12px;color:rgba(255,255,255,.75);margin-top:3px;" id="preview-info">قط</div>
        </div>
      </div>

      <!-- Save button -->
      <button onclick="savePet()" id="save-pet-btn"
        style="width:100%;background:linear-gradient(135deg,#065f46,#10b981);color:#fff;border:none;border-radius:12px;padding:15px;font-size:16px;font-weight:900;cursor:pointer;box-shadow:0 4px 16px rgba(16,185,129,.3);font-family:'Tajawal',sans-serif;transition:.2s;">
        ✅ إضافة الحيوان
      </button>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════════
     SCRIPTS: i18n + Theme + App Logic
══════════════════════════════════════════ -->
<script src="lang/ar.js"></script>
<script src="lang/fr.js"></script>
<script src="lang/en.js"></script>
<script>
// ═══════════════════════════════════════════
// CORE STATE
// ═══════════════════════════════════════════
const App = {
  lang: localStorage.getItem('baitari_lang') || 'ar',
  theme: localStorage.getItem('baitari_theme') || 'light',
  userRole: (function(r){ return r==='vet'||r==='admin' ? r : 'client'; })('<?php echo htmlspecialchars($role); ?>'),
  userName: '<?php echo htmlspecialchars($user["name"] ?? "المستخدم"); ?>',
  currentPage: 'home',
  bookingVet: null,
  selectedPetId: null,
  selectedVisitType: 'clinic',
  selectedDate: null,
  selectedTime: null,
  selectedAnimal: null,
  emgLat: null,
  emgLng: null,
  searchTimer: null,
};

const langs = { ar: lang_ar, fr: lang_fr, en: lang_en };

// ═══════════════════════════════════════════
// i18n ENGINE
// ═══════════════════════════════════════════
function t(key) {
  return langs[App.lang][key] || langs['ar'][key] || key;
}

function applyTranslations() {
  const isRTL = App.lang === 'ar';
  document.documentElement.lang = App.lang;
  document.documentElement.dir = isRTL ? 'rtl' : 'ltr';

  document.querySelectorAll('[data-i18n]').forEach(el => {
    el.textContent = t(el.dataset.i18n);
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    el.placeholder = t(el.dataset.i18nPlaceholder);
  });

  // Update arrows based on direction
  document.querySelectorAll('.emg-arrow').forEach(el => {
    el.textContent = isRTL ? '←' : '→';
  });

  // Update lang buttons
  document.querySelectorAll('.lang-btn').forEach(b => {
    b.classList.toggle('active', b.getAttribute('onclick').includes(`'${App.lang}'`));
  });
}

function setLang(lang) {
  App.lang = lang;
  localStorage.setItem('baitari_lang', lang);
  applyTranslations();
  showToast('info', lang === 'ar' ? 'تم تغيير اللغة' : lang === 'fr' ? 'Langue modifiée' : 'Language changed');
}

// ═══════════════════════════════════════════
// THEME ENGINE
// ═══════════════════════════════════════════
function applyTheme() {
  document.documentElement.setAttribute('data-theme', App.theme);
  const toggle = document.getElementById('theme-toggle');
  if (toggle) toggle.classList.toggle('on', App.theme === 'dark');
}

function toggleTheme() {
  App.theme = App.theme === 'light' ? 'dark' : 'light';
  localStorage.setItem('baitari_theme', App.theme);
  applyTheme();
}

// ═══════════════════════════════════════════
// PAGE ROUTER
// ═══════════════════════════════════════════
function showPage(pageName) {
  // Role-based page routing
  var isVet    = App.userRole === 'vet';
  var isClient = App.userRole !== 'vet' && App.userRole !== 'admin';
  var isAdmin  = App.userRole === 'admin';

  // Vet: home → vet-dashboard
  if (pageName === 'home' && isVet) pageName = 'vet-dashboard';
  // Client: vet-dashboard → home
  if (pageName === 'vet-dashboard' && !isVet) pageName = 'home';

  document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
  const target = document.getElementById(`page-${pageName}`);
  if (target) { target.classList.add('active'); target.style.display = ''; }

  // Update nav indicators
  document.querySelectorAll('.nav-item[data-page]').forEach(n => {
    n.classList.toggle('active', n.dataset.page === pageName);
  });
  document.querySelectorAll('.sidebar-nav-item').forEach(n => {
    n.classList.toggle('active', n.getAttribute('onclick')?.includes(`'${pageName}'`));
  });

  App.currentPage = pageName;

  // Lazy load data per page
  if (pageName === 'search') loadSearchVets();
  if (pageName === 'appointments') loadAppointments();
  if (pageName === 'home') initHome();
}

// ═══════════════════════════════════════════
// GREETING
// ═══════════════════════════════════════════
function getGreeting() {
  const h = new Date().getHours();
  if (h < 12) return t('home_greeting_morning');
  if (h < 18) return t('home_greeting_afternoon');
  return t('home_greeting_evening');
}

// ═══════════════════════════════════════════
// DATA — loaded from API
// ═══════════════════════════════════════════
const MOCK_PETS         = []; // filled by loadPets()
const MOCK_HERDS        = []; // filled by loadHerds()
const MOCK_VETS         = []; // filled by loadVets()
const MOCK_APPOINTMENTS = []; // filled by loadAppointments()
const MOCK_VET_REQUESTS = []; // filled by loadVetRequests()

const HEALTH_TIPS = [
  { icon:'💉', title:'التطعيمات السنوية', text:'تأكد من تطعيم حيوانك ضد الأمراض الشائعة قبل كل موسم.' },
  { icon:'🦷', title:'صحة الأسنان', text:'ينبغي تنظيف أسنان القطط والكلاب مرة أسبوعياً.' },
  { icon:'🥗', title:'التغذية السليمة', text:'تجنب إطعام حيوانك البصل والشوكولاتة والعنب.' },
];

// ═══════════════════════════════════════════
// HOME INIT
// ═══════════════════════════════════════════
function initHome() {
  // Greeting
  var greetEl = document.getElementById('greeting-text');
  if (greetEl) greetEl.textContent = getGreeting();

  var isClient = App.userRole !== 'vet' && App.userRole !== 'admin';
  var isVet    = App.userRole === 'vet';
  var isAdmin  = App.userRole === 'admin';

  // Show/hide client tabs bar
  var tabsBar = document.getElementById('client-tabs-bar');
  if (tabsBar) tabsBar.style.display = isClient ? 'flex' : 'none';

  // Show/hide vet dashboard vs client home
  var pageHome = document.getElementById('page-home');
  var pageVet  = document.getElementById('page-vet-dashboard');

  if (isVet) {
    // Vet sees vet dashboard
    if (pageHome) pageHome.style.display = 'none';
    if (pageVet)  { pageVet.style.display = ''; renderVetDashboard(); }
  } else {
    // Client sees home
    if (pageHome) pageHome.style.display = '';
    if (pageVet)  pageVet.style.display  = 'none';

    if (isClient) {
      renderPets();
      renderHomeVets();
      renderTips();
    }
  }
}

// ═══════════════════════════════════════════
// RENDER PETS
// ═══════════════════════════════════════════
async function renderPets() {
  const container = document.getElementById('pets-container');
  if (!container) return;
  container.innerHTML = '<div style="display:flex;gap:10px;padding:4px 2px;"><div style="width:100px;height:120px;border-radius:16px;background:var(--border);animation:shimmer 1.4s ease infinite;"></div><div style="width:100px;height:120px;border-radius:16px;background:var(--border);animation:shimmer 1.4s ease infinite;"></div></div>';

  try {
    var res = await fetch('api/index.php', {
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=get_pets'
    });
    var data = await res.json();
    var pets = (data.success && data.pets) ? data.pets : [];
    MOCK_PETS.length = 0;
    pets.forEach(p => MOCK_PETS.push(p));
  } catch(e) { var pets = []; }

  container.innerHTML = '';
  var SPECIES_EMOJI = {cat:'🐱',dog:'🐕',bird:'🐦',rabbit:'🐰',horse:'🐴',cow:'🐄',sheep:'🐑',other:'🐾'};
  pets.forEach(function(pet) {
    var card = document.createElement('div');
    card.className = 'pet-card';
    card.innerHTML =
      '<div class="pet-status-dot ok"></div>' +
      '<div class="pet-avatar">' + (SPECIES_EMOJI[pet.species] || '🐾') + '</div>' +
      '<div class="pet-name">' + (pet.name || '') + '</div>' +
      '<div class="pet-breed">' + (pet.breed || pet.species || '') + '</div>';
    card.onclick = function() { showToast('info', (pet.name || '') + ' — ' + (pet.breed || '')); };
    container.appendChild(card);
  });

  var statPets = document.getElementById('stat-pets');
  var countLabel = document.getElementById('pets-count-label');
  if (statPets) statPets.textContent = pets.length;
  if (countLabel) countLabel.textContent = pets.length + ' حيوانات';

  // Add Pet button
  const addCard = document.createElement('div');
  addCard.className = 'add-pet-card';
  addCard.innerHTML = `
    <div class="add-icon">➕</div>
    <div class="add-label">${t('home_add_pet')}</div>
  `;
  addCard.onclick = () => openAddPetModal();
  container.appendChild(addCard);


}

// ═══════════════════════════════════════════
// RENDER HERDS (Farm Owner)
// ═══════════════════════════════════════════
function renderHerds() {
  const container = document.getElementById('herd-container');
  if (!container) return;
  container.innerHTML = '';

  MOCK_HERDS.forEach(h => {
    const statusMap = {
      healthy: { cls: 'healthy', label: t('farm_healthy') },
      needs_attention: { cls: 'needs-attention', label: t('farm_needs_attention') },
      critical: { cls: 'critical', label: t('farm_critical') },
    };
    const s = statusMap[h.health_status];

    const card = document.createElement('div');
    card.className = 'herd-card';
    card.innerHTML = `
      <div class="herd-icon ${h.species}">${h.emoji}</div>
      <div class="herd-info">
        <div class="herd-name">${h.name}</div>
        <div class="herd-count">${h.count} ${t('farm_herd_size')}</div>
      </div>
      <div class="herd-badge ${s.cls}">${s.label}</div>
    `;
    card.onclick = () => showToast('info', `${h.name}: ${h.count} رأس`);
    container.appendChild(card);
  });

  var statPets2 = document.getElementById('stat-pets'); if(statPets2) statPets2.textContent = MOCK_HERDS.reduce(function(s,h){return s+(h.count||0);},0);
  document.getElementById('pets-section-title') &&
    (document.getElementById('pets-section-title').textContent = t('home_my_herd'));
}

// ═══════════════════════════════════════════
// RENDER VETS (Home Preview)
// ═══════════════════════════════════════════
async async function renderHomeVets() {
  const c = document.getElementById('home-vets-container');
  if (!c) return;
  c.innerHTML = '<div class="loader"><div class="spinner"></div></div>';

  try {
    var res = await fetch('api/index.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'action=get_vets'
    });
    var data = await res.json();
    var vets = (data.vets && data.vets.length > 0) ? data.vets : [];
    if (data.error) console.error('VetNet API error:', data.error);
    // Store in MOCK_VETS for booking
    MOCK_VETS.length = 0;
    vets.forEach(function(v) {
      v.is_available  = !!v.is_available;
      v.home_visits   = !!v.home_visits;
      v.accepts_emergency = !!v.accepts_emergency;
      v.rating        = parseFloat(v.rating) || 0;
      v.reviews       = parseInt(v.reviews)  || 0;
      v.emoji         = '👨‍⚕️';
      MOCK_VETS.push(v);
    });
    // Update stat
    var sv = document.getElementById('stat-vets');
    if (sv) sv.textContent = vets.length;

    c.innerHTML = '';
    if (vets.length === 0) {
      c.innerHTML = '<div class="empty-state"><div style="font-size:40px">👨‍⚕️</div><p>لا يوجد أطباء متاحون حالياً</p></div>';
      return;
    }
    vets.slice(0, 3).forEach(function(v) { c.appendChild(buildVetCard(v)); });
  } catch(e) {
    console.error('renderHomeVets error:', e);
    c.innerHTML = '<div class="empty-state" style="text-align:center;padding:20px;color:var(--text-muted);">' +
      '<div style="font-size:32px;margin-bottom:8px;">👨‍⚕️</div>' +
      '<p style="font-size:13px;">تعذّر تحميل الأطباء</p>' +
      '<button onclick="renderHomeVets()" style="margin-top:8px;padding:6px 16px;border:1px solid var(--border);border-radius:8px;background:none;cursor:pointer;font-family:inherit;">إعادة المحاولة</button>' +
      '</div>';
    var sv = document.getElementById('stat-vets');
    if (sv) sv.textContent = '0';
  }
}

function buildVetCard(v) {
  const avail = v.is_available ? { cls:'available', label: t('vet_available') }
              : { cls:'offline',   label: t('vet_offline') };
  const stars = '⭐'.repeat(Math.round(v.rating)) + ` ${v.rating}`;

  const card = document.createElement('div');
  card.className = 'vet-card';
  card.innerHTML = `
    <div class="vet-card-top">
      <div class="vet-avatar">${v.emoji}</div>
      <div class="vet-info">
        <div class="vet-name">${v.name}</div>
        <div class="vet-specialty">${v.specialty}</div>
        <div class="vet-meta">
          <div class="vet-meta-item vet-rating-stars">${stars}</div>
          <div class="vet-meta-item">(${v.reviews} ${t('vet_reviews')})</div>
          <div class="distance-chip"><span class="icon">📍</span>${v.distance_km} ${t('km_away')}</div>
          <div class="availability-badge ${avail.cls}">${avail.label}</div>
        </div>
      </div>
    </div>
    <div class="vet-card-actions">
      <div class="btn-book" onclick="openBooking(${v.id})">${t('vet_book_now')}</div>
      <div class="btn-profile" onclick="showToast('info','${v.name}')">👁</div>
    </div>
  `;
  return card;
}

// ═══════════════════════════════════════════
// RENDER TIPS
// ═══════════════════════════════════════════
function renderTips() {
  const c = document.getElementById('tips-container');
  if (!c) return;
  c.innerHTML = '';
  HEALTH_TIPS.forEach(tip => {
    const el = document.createElement('div');
    el.className = 'tip-card';
    el.innerHTML = `
      <div class="tip-icon">${tip.icon}</div>
      <div class="tip-text"><h4>${tip.title}</h4><p>${tip.text}</p></div>
    `;
    c.appendChild(el);
  });
}

// ═══════════════════════════════════════════
// SEARCH PAGE
// ═══════════════════════════════════════════
let searchQuery = '';
let activeFilter = 'all';

function loadSearchVets(query = '') {
  const c = document.getElementById('search-vets-container');
  if (!c) return;
  c.innerHTML = '<div class="loader"><div class="spinner"></div></div>';

  setTimeout(() => {
    c.innerHTML = '';
    let results = MOCK_VETS;

    if (query) {
      results = results.filter(v =>
        v.name.includes(query) || v.specialty.includes(query)
      );
    }
    if (activeFilter === 'available')   results = results.filter(v => v.is_available);
    if (activeFilter === 'home_visit')  results = results.filter(v => v.home_visits);
    if (activeFilter === 'emergency')   results = results.filter(v => v.accepts_emergency);

    if (!results.length) {
      c.innerHTML = `<div class="empty-state"><div class="empty-icon">🔍</div><p>لا توجد نتائج</p></div>`;
      return;
    }
    results.forEach(v => c.appendChild(buildVetCard(v)));
  }, 400);
}

function debounceSearch() {
  clearTimeout(App.searchTimer);
  App.searchTimer = setTimeout(() => {
    loadSearchVets(document.getElementById('vet-search-input').value);
  }, 350);
}

// Filter chips
document.querySelectorAll('.filter-chips .chip').forEach(chip => {
  chip.addEventListener('click', () => {
    document.querySelectorAll('.filter-chips .chip').forEach(c => c.classList.remove('active'));
    chip.classList.add('active');
    activeFilter = chip.dataset.filter;
    loadSearchVets(document.getElementById('vet-search-input')?.value || '');
  });
});

// ═══════════════════════════════════════════
// APPOINTMENTS
// ═══════════════════════════════════════════
let currentApptTab = 'upcoming';

function loadAppointments() {
  const c = document.getElementById('appt-container');
  if (!c) return;
  c.innerHTML = '';

  const statusMap = {
    confirmed: t('appt_confirmed'),
    pending: t('appt_pending'),
    completed: t('appt_completed'),
    cancelled: t('appt_cancelled'),
  };

  if (!MOCK_APPOINTMENTS.length) {
    c.innerHTML = `<div class="empty-state"><div class="empty-icon">📅</div><p>${t('home_no_appointments')}</p></div>`;
    return;
  }

  MOCK_APPOINTMENTS.forEach(a => {
    const el = document.createElement('div');
    el.className = 'appt-card';
    el.innerHTML = `
      <div class="appt-date-block">
        <div class="appt-day">${a.day}</div>
        <div class="appt-month">${a.month}</div>
      </div>
      <div class="appt-info">
        <div class="appt-vet-name">${a.vet_name}</div>
        <div class="appt-time">⏰ ${a.time}</div>
        <div class="appt-pet">🐾 ${a.pet_name}</div>
        <div class="appt-status ${a.status}">${statusMap[a.status] || a.status}</div>
      </div>
    `;
    c.appendChild(el);
  });
}

function switchApptTab(tab, el) {
  document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
  el.classList.add('active');
  currentApptTab = tab;
  loadAppointments();
}

// ═══════════════════════════════════════════
// BOOKING MODAL
// ═══════════════════════════════════════════
function openBooking(vetId) {
  App.bookingVet = MOCK_VETS.find(v => v.id === vetId);
  App.selectedPetId = null;
  App.selectedDate  = null;
  App.selectedTime  = null;
  App.selectedVisitType = 'clinic';

  // Reset modal
  ['1','2','3'].forEach(n => {
    document.getElementById(`book-step-${n}`).style.display = n === '1' ? '' : 'none';
  });
  document.getElementById('book-success').classList.remove('show');
  updateStepDots(1);

  // Populate pets
  const ps = document.getElementById('book-pet-selector');
  ps.innerHTML = '';
  MOCK_PETS.forEach(pet => {
    const el = document.createElement('div');
    el.className = 'pet-select-item';
    el.dataset.id = pet.id;
    el.innerHTML = `<div class="ps-icon">${pet.emoji}</div><div class="ps-name">${pet.name}</div>`;
    el.onclick = () => {
      document.querySelectorAll('.pet-select-item').forEach(e => e.classList.remove('selected'));
      el.classList.add('selected');
      App.selectedPetId = pet.id;
    };
    ps.appendChild(el);
  });

  // Build date grid (next 7 days)
  buildDateGrid();
  buildTimeGrid();

  openModal('booking-modal');
}

function buildDateGrid() {
  const grid = document.getElementById('date-grid');
  grid.innerHTML = '';
  const days = ['أحد','إث','ثلا','أرب','خمس','جمع','سبت'];
  for (let i = 0; i < 7; i++) {
    const d = new Date();
    d.setDate(d.getDate() + i);
    const cell = document.createElement('div');
    cell.className = 'date-cell';
    if (i === 0) cell.classList.add('selected');
    cell.innerHTML = `
      <div class="dc-day">${days[d.getDay()]}</div>
      <div class="dc-num">${d.getDate()}</div>
    `;
    cell.dataset.date = d.toISOString().split('T')[0];
    cell.onclick = () => {
      document.querySelectorAll('.date-cell').forEach(c => c.classList.remove('selected'));
      cell.classList.add('selected');
      App.selectedDate = cell.dataset.date;
    };
    if (i === 0) App.selectedDate = cell.dataset.date;
    grid.appendChild(cell);
  }
}

function buildTimeGrid() {
  const grid = document.getElementById('time-grid');
  grid.innerHTML = '';
  const times = ['08:00','09:00','10:00','11:00','14:00','15:00','16:00','17:00'];
  const taken  = ['11:00','15:00'];
  times.forEach(t => {
    const slot = document.createElement('div');
    slot.className = 'time-slot' + (taken.includes(t) ? ' taken' : '');
    slot.textContent = t;
    slot.onclick = () => {
      document.querySelectorAll('.time-slot:not(.taken)').forEach(s => s.classList.remove('selected'));
      slot.classList.add('selected');
      App.selectedTime = t;
    };
    grid.appendChild(slot);
  });
}

function selectVisit(type, el) {
  document.querySelectorAll('.visit-opt').forEach(o => o.classList.remove('selected'));
  el.classList.add('selected');
  App.selectedVisitType = type;
}

function bookStep(step) {
  if (step === 2 && !App.selectedPetId && MOCK_PETS.length > 0) {
    showToast('error', 'الرجاء اختيار الحيوان أولاً');
    return;
  }
  if (step === 3) {
    if (!App.selectedDate || !App.selectedTime) {
      showToast('error', 'الرجاء اختيار التاريخ والوقت');
      return;
    }
    buildBookSummary();
  }

  ['1','2','3'].forEach(n => {
    document.getElementById(`book-step-${n}`).style.display = n == step ? '' : 'none';
  });
  updateStepDots(step);
}

function buildBookSummary() {
  const vet  = App.bookingVet;
  const pet  = MOCK_PETS.find(p => p.id === App.selectedPetId);
  const fee  = App.selectedVisitType === 'home' ? vet.fee_home : vet.fee_clinic;
  document.getElementById('book-summary').innerHTML = `
    <div style="display:grid;gap:10px;">
      <div style="display:flex;justify-content:space-between;">
        <span style="color:var(--text-sec);">${t('vet_view_profile')}</span>
        <span style="font-weight:800;">${vet.name}</span>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <span style="color:var(--text-sec);">الحيوان</span>
        <span style="font-weight:800;">${pet ? pet.name : '—'}</span>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <span style="color:var(--text-sec);">${t('book_visit_type')}</span>
        <span style="font-weight:800;">${App.selectedVisitType === 'clinic' ? t('book_clinic_visit') : t('book_home_visit')}</span>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <span style="color:var(--text-sec);">التاريخ</span>
        <span style="font-weight:800;">${App.selectedDate} — ${App.selectedTime}</span>
      </div>
      <div style="border-top:1px solid var(--border);padding-top:10px;display:flex;justify-content:space-between;">
        <span style="color:var(--text-sec);">${t('book_fee')}</span>
        <span style="font-weight:900;color:var(--green-600);font-size:17px;">${fee.toLocaleString()} ${t('dz_currency')}</span>
      </div>
    </div>
  `;
}

function updateStepDots(active) {
  [1,2,3].forEach(n => {
    const d = document.getElementById(`sdot-${n}`);
    d.className = 'step-dot' + (n < active ? ' done' : n == active ? ' active' : '');
  });
}

async function submitBooking() {
  const btn = document.getElementById('confirm-book-btn');
  btn.disabled = true;
  btn.textContent = t('loading');

  // Simulate API call
  await new Promise(r => setTimeout(r, 1200));

  ['1','2','3'].forEach(n => {
    document.getElementById(`book-step-${n}`).style.display = 'none';
  });
  document.getElementById('book-success').classList.add('show');
  showToast('success', t('book_success'));
}

// ═══════════════════════════════════════════
// EMERGENCY MODAL
// ═══════════════════════════════════════════
function handleEmergencyBtn() {
  if (App.userRole === 'vet') {
    showPage('vet-dashboard');
    showToast('info', 'طلبات الطوارئ في لوحة تحكمك ⬆️');
  } else {
    openEmergency();
  }
}

function openEmergency() {
  // Vet sees their emergency requests, not the client form
  if (App.userRole === 'vet') {
    showToast('info', '🚨 طلبات الطوارئ تظهر في لوحة تحكمك أعلاه');
    return;
  }
  App.selectedAnimal = null;
  App.emgLat = null; App.emgLng = null;

  document.getElementById('emg-form').style.display = '';
  document.getElementById('emg-success').classList.remove('show');
  document.getElementById('emg-submit-btn').disabled = false;
  document.getElementById('emg-submit-btn').innerHTML = `🚨 <span>${t('emergency_send')}</span>`;
  document.getElementById('emg-problem').value = '';
  document.querySelectorAll('.emg-animal-item').forEach(i => i.classList.remove('selected'));
  document.getElementById('emg-loc-badge').style.display = 'none';
  document.getElementById('emg-loc-text').textContent = t('emergency_get_location');

  openModal('emergency-modal');
}

function selectAnimal(el) {
  document.querySelectorAll('.emg-animal-item').forEach(i => i.classList.remove('selected'));
  el.classList.add('selected');
  App.selectedAnimal = el.dataset.animal;
}

function getEmgLocation() {
  const btn = document.getElementById('emg-location-btn');
  document.getElementById('emg-loc-text').textContent = 'جارٍ تحديد الموقع...';

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(pos => {
      App.emgLat = pos.coords.latitude;
      App.emgLng = pos.coords.longitude;
      document.getElementById('emg-loc-text').textContent = `${App.emgLat.toFixed(4)}, ${App.emgLng.toFixed(4)}`;
      document.getElementById('emg-loc-badge').style.display = '';
      showToast('success', 'تم تحديد موقعك بنجاح');
    }, () => {
      document.getElementById('emg-loc-text').textContent = t('emergency_get_location');
      showToast('error', 'تعذّر تحديد الموقع');
    });
  } else {
    // Fallback mock
    App.emgLat = 36.7538; App.emgLng = 3.0588;
    document.getElementById('emg-loc-text').textContent = 'الجزائر العاصمة';
    document.getElementById('emg-loc-badge').style.display = '';
  }
}

async function submitEmergency() {
  if (!App.selectedAnimal) { showToast('error', 'الرجاء اختيار نوع الحيوان'); return; }
  const problem = document.getElementById('emg-problem').value.trim();
  if (!problem) { showToast('error', 'الرجاء وصف المشكلة'); return; }

  const btn = document.getElementById('emg-submit-btn');
  btn.disabled = true;
  btn.textContent = t('emergency_sending');

  // Simulate API
  await new Promise(r => setTimeout(r, 1500));

  // Show success
  document.getElementById('emg-form').style.display = 'none';
  document.getElementById('emg-success').classList.add('show');

  // Show nearest vet info
  const nearest = MOCK_VETS.find(v => v.accepts_emergency);
  if (nearest) {
    document.getElementById('emg-vet-info').style.display = '';
    document.getElementById('emg-vet-name').textContent = `🩺 ${nearest.name}`;
    document.getElementById('emg-vet-dist').textContent = `📍 ${nearest.distance_km} ${t('km_away')} — يتصل بك الآن`;
  }

  showToast('success', t('emergency_sent'));
}

// ═══════════════════════════════════════════
// VET DASHBOARD
// ═══════════════════════════════════════════
function renderVetDashboard() {
  const c = document.getElementById('vet-requests-container');
  if (!c) return;
  c.innerHTML = '';

  MOCK_VET_REQUESTS.forEach(req => {
    const card = document.createElement('div');
    card.innerHTML = `
      <div class="request-header">
        <div class="request-user">👤 ${req.user}</div>
        <div class="request-time">${req.time}</div>
      </div>
      <div class="request-detail">🐾 ${req.animal}<br>⚠️ ${req.problem}</div>
      <div class="request-actions">
        <div class="btn-accept" onclick="acceptRequest(${req.id})">✅ ${t('vet_dash_accept')}</div>
        <div class="btn-reject" onclick="rejectRequest(${req.id})">✕ ${t('vet_dash_reject')}</div>
      </div>
    `;
    c.appendChild(card);
  });
}

function acceptRequest(id) { showToast('success', 'تم قبول الطلب'); }
function rejectRequest(id) { showToast('error', 'تم رفض الطلب'); }

// ═══════════════════════════════════════════
// ADD PET MODAL (Quick)
// ═══════════════════════════════════════════
function openAddPetModal() {
  // Reset form
  document.getElementById('pet-name').value = '';
  document.getElementById('pet-breed').value = '';
  document.getElementById('pet-age').value = '';
  document.getElementById('pet-weight').value = '';
  document.getElementById('vacc-toggle').classList.remove('on');
  // Reset species
  document.querySelectorAll('.species-btn').forEach(b => b.classList.remove('on'));
  var first = document.querySelector('.species-btn[data-species="cat"]');
  if (first) first.classList.add('on');
  updatePetPreview();
  openModal('add-pet-modal');
}

function pickSpecies(el) {
  document.querySelectorAll('.species-btn').forEach(b => b.classList.remove('on'));
  el.classList.add('on');
  updatePetPreview();
}

function getSelectedSpecies() {
  var btn = document.querySelector('.species-btn.on');
  return btn ? btn.dataset.species : 'cat';
}

var SPECIES_MAP = {
  cat:'🐱قط', dog:'🐕كلب', bird:'🐦طائر', rabbit:'🐰أرنب',
  horse:'🐴حصان', cow:'🐄بقرة', sheep:'🐑خروف', other:'🐾أخرى'
};

function updatePetPreview() {
  var sp   = getSelectedSpecies();
  var info = SPECIES_MAP[sp] || '🐾';
  var emoji = info.charAt(0) + (info.charCodeAt(0) > 127 ? info.charAt(1) : '');
  // Better: split emoji from label
  var parts = { cat:['🐱','قط'], dog:['🐕','كلب'], bird:['🐦','طائر'],
    rabbit:['🐰','أرنب'], horse:['🐴','حصان'], cow:['🐄','بقرة'],
    sheep:['🐑','خروف'], other:['🐾','أخرى'] };
  var p = parts[sp] || ['🐾','أخرى'];
  document.getElementById('preview-emoji').textContent = p[0];
  var name = document.getElementById('pet-name').value.trim() || 'اسم الحيوان';
  document.getElementById('preview-name').textContent = name;
  var breed = document.getElementById('pet-breed').value.trim();
  document.getElementById('preview-info').textContent = p[1] + (breed ? ' · ' + breed : '');
}

async function savePet() {
  var name    = document.getElementById('pet-name').value.trim();
  var species = getSelectedSpecies();
  var breed   = document.getElementById('pet-breed').value.trim();
  var age     = document.getElementById('pet-age').value;
  var weight  = document.getElementById('pet-weight').value;
  var vaccinated = document.getElementById('vacc-toggle').classList.contains('on') ? 1 : 0;
  var errDiv  = document.getElementById('err-pet-name');

  if (!name) {
    errDiv.style.display = 'block';
    document.getElementById('pet-name').focus();
    return;
  }
  errDiv.style.display = 'none';

  var btn = document.getElementById('save-pet-btn');
  btn.disabled = true;
  btn.textContent = '⏳ جارٍ الحفظ...';

  try {
    var res = await fetch('api/index.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'action=add_pet'
        + '&name='    + encodeURIComponent(name)
        + '&species=' + encodeURIComponent(species)
        + '&breed='   + encodeURIComponent(breed)
        + '&birth_date=' + (age ? encodeURIComponent(getBirthYear(age)) : '')
        + '&weight_kg='  + encodeURIComponent(weight || 0)
        + '&is_vaccinated=' + vaccinated
    });
    var data = await res.json();
    if (data.success) {
      showToast('success', '✅ تمت إضافة ' + name + ' بنجاح!');
      closeModal('add-pet-modal');
      // Refresh pets section
      setTimeout(function() { initHome(); }, 500);
    } else {
      showToast('error', data.error || 'خطأ في الحفظ');
      btn.disabled = false;
      btn.textContent = '✅ إضافة الحيوان';
    }
  } catch(e) {
    console.error('savePet error:', e);
    showToast('error', 'خطأ في الاتصال: ' + e.message);
    btn.disabled = false;
    btn.textContent = '+ إضافة الحيوان';
  }
}

function getBirthYear(ageYears) {
  var year = new Date().getFullYear() - Math.round(parseFloat(ageYears));
  return year + '-01-01';
}

function openAddHerd() {
  showToast('info', 'نافذة إضافة قطيع — قريباً');
}

// ═══════════════════════════════════════════
// MODAL HELPERS
// ═══════════════════════════════════════════
function openModal(id) {
  const m = document.getElementById(id);
  if (m) { m.classList.add('open'); document.body.style.overflow = 'hidden'; }
}
function closeModal(id) {
  const m = document.getElementById(id);
  if (m) { m.classList.remove('open'); document.body.style.overflow = ''; }
}

// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(overlay => {
  overlay.addEventListener('click', e => {
    if (e.target === overlay) closeModal(overlay.id);
  });
});

// ═══════════════════════════════════════════
// TOAST SYSTEM
// ═══════════════════════════════════════════
function showToast(type, message) {
  const icons = { success:'✅', error:'❌', info:'ℹ️' };
  const container = document.getElementById('toast-container');
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.innerHTML = `<span class="toast-icon">${icons[type]}</span><span class="toast-msg">${message}</span>`;
  container.appendChild(toast);
  setTimeout(() => {
    toast.classList.add('removing');
    setTimeout(() => toast.remove(), 300);
  }, 3000);
}

// ═══════════════════════════════════════════
// LOGOUT
// ═══════════════════════════════════════════
function openEditProfile() {
  var name = prompt('اسمك الجديد:', App.userName || '');
  if (!name || !name.trim()) return;
  fetch('api/index.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: 'action=update_profile&name=' + encodeURIComponent(name.trim())
  }).then(function(r){ return r.json(); })
    .then(function(data) {
      if (data.success) {
        App.userName = name.trim();
        var pn = document.getElementById('profile-name');
        var un = document.getElementById('user-name-display');
        if (pn) pn.textContent = name.trim();
        if (un) un.textContent = name.trim() + ' 👋';
        showToast('success', '✅ تم تحديث الاسم');
      } else {
        showToast('error', data.error || 'خطأ في التحديث');
      }
    }).catch(function(){ showToast('error', 'خطأ في الاتصال'); });
}

async function confirmLogout() {
  if (!confirm('هل تريد تسجيل الخروج؟')) return;
  // Use logout.php which destroys session server-side then redirects
  window.location.href = 'logout.php';
}

// ═══════════════════════════════════════════
// ROLE SWITCHER (Demo purposes)
// ═══════════════════════════════════════════
function switchRole(role) {
  App.userRole = role;
  localStorage.setItem('baitari_role', role);
  document.documentElement.setAttribute('data-user-role', role);
  showPage('home');
  initHome();
}

// ═══════════════════════════════════════════
// KEYBOARD SHORTCUT (Dev)
// ═══════════════════════════════════════════
document.addEventListener('keydown', e => {
  if (e.altKey && e.key === 'r') {
    const roles = ['client','client','vet','admin'];
    const next = roles[(roles.indexOf(App.userRole) + 1) % roles.length];
    switchRole(next);
    showToast('info', `Role: ${next}`);
  }
});

// ═══════════════════════════════════════════
// BOOT
// ═══════════════════════════════════════════
(function boot() {
  applyTheme();
  applyTranslations();
  initHome();
  loadSearchVets();

  // Simulate notification dot
  setTimeout(() => {
    const dot = document.getElementById('notif-dot');
    if (dot) dot.style.display = '';
  }, 2000);

  // Set user info
  var nameDisplay = document.getElementById('user-name-display');
  var profileName = document.getElementById('profile-name');
  if (nameDisplay) nameDisplay.textContent = App.userName + ' 👋';
  if (profileName) profileName.textContent = App.userName;
  
  // Set time-based greeting
  var hour = new Date().getHours();
  var greet = hour < 12 ? 'صباح الخير' : hour < 17 ? 'مساء الخير' : 'مساء النور';
  var greetEl = document.getElementById('greeting-text');
  if (greetEl) greetEl.textContent = greet;

  // Render vet dashboard if role = vet
  if (App.userRole === 'vet') renderVetDashboard();
})();
</script>
<script>
// PWA Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then(reg => {
      console.log('[PWA] SW registered:', reg.scope);
    }).catch(err => console.warn('[PWA] SW failed:', err));
  });
}
// Quick links to new pages
function openVetProfile(id) { window.location.href = 'pages/vet-profile.php?id=' + id; }
function openEmergencyMap() { window.location.href = 'pages/emergency-map.php'; }

function switchClientTab(tab) {
  var pets    = document.getElementById('client-view-pets');
  var farm    = document.getElementById('client-view-farm');
  var btnPets = document.getElementById('ctab-pets');
  var btnFarm = document.getElementById('ctab-farm');
  if (!pets || !farm) return;

  pets.style.display = tab === 'pets' ? '' : 'none';
  farm.style.display = tab === 'farm' ? '' : 'none';

  var active = 'background:var(--bg-card);color:var(--green-700);box-shadow:0 2px 8px rgba(0,0,0,.08);';
  var inactive = 'background:none;color:var(--text-muted);box-shadow:none;';

  if (btnPets) btnPets.style.cssText += tab === 'pets' ? active : inactive;
  if (btnFarm) btnFarm.style.cssText += tab === 'farm' ? active : inactive;

  // Load farm herds if switching to farm tab for first time
  if (tab === 'farm') loadHomeHerds();
}

async function loadHomeHerds() {
  var container = document.getElementById('herd-container');
  if (!container || container.dataset.loaded) return;
  container.innerHTML = '<div class="loader"><div class="spinner"></div></div>';
  try {
    var res = await fetch('api/index.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=get_herds'
    });
    var data = await res.json();
    container.dataset.loaded = '1';
    if (data.success && data.herds && data.herds.length) {
      container.innerHTML = data.herds.map(function(h) {
        return '<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:14px;padding:14px 16px;margin-bottom:10px;display:flex;align-items:center;gap:12px;">' +
          '<div style="font-size:28px;">' + (h.type==='cow'?'🐄':h.type==='sheep'?'🐑':h.type==='goat'?'🐐':'🐾') + '</div>' +
          '<div style="flex:1;"><div style="font-size:15px;font-weight:800;">' + h.name + '</div>' +
          '<div style="font-size:12px;color:var(--text-muted);margin-top:2px;">' + (h.count||0) + ' رأس</div></div>' +
          '<div style="font-size:11px;font-weight:800;padding:4px 10px;border-radius:20px;background:var(--green-100);color:var(--green-700);">' + (h.health_status||'سليم') + '</div>' +
        '</div>';
      }).join('');
    } else {
      container.innerHTML = '<div style="text-align:center;padding:32px;color:var(--text-muted);"><div style="font-size:40px;margin-bottom:10px;">🚜</div><div style="font-size:14px;font-weight:700;">لا توجد قطعان بعد</div></div>';
    }
  } catch(e) {
    container.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted);">تعذّر تحميل البيانات</div>';
    container.dataset.loaded = '';
  }
}
function openAdminPanel() { window.location.href = 'pages/admin.php'; }
</script>
</body>
</html>
