<!DOCTYPE html>
<html lang="ar" dir="rtl" data-theme="light">
<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">
<title>بيطري — تسجيل الدخول</title>
<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">
<style>
:root {
  --green-50:#f0faf5;--green-100:#d6f2e5;--green-400:#4aba8a;
  --green-500:#1a9f6a;--green-600:#1a7f5a;--green-700:#155f44;
  --blue-500:#3b82f6;--red-500:#ef4444;
  --bg:#f7faf9;--bg-card:#ffffff;--bg-input:#f3f7f5;
  --border:#e0ece7;--text-primary:#0e2d20;--text-sec:#4a7060;--text-muted:#8aaa9a;
  --shadow-md:0 4px 20px rgba(0,60,30,.10);--shadow-xl:0 20px 60px rgba(0,60,30,.20);
  --radius-sm:10px;--radius-md:16px;--radius-lg:24px;
  --transition:.22s cubic-bezier(.4,0,.2,1);
}
[data-theme="dark"]{
  --bg:#0a1a12;--bg-card:#122010;--bg-input:#1a2e1e;
  --border:#1e3828;--text-primary:#e0f2e9;--text-sec:#8abfa0;--text-muted:#4a7060;
  --green-50:#0d1f14;--green-100:#112918;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
html,body{height:100%;-webkit-tap-highlight-color:transparent;}
body{
  font-family:'Tajawal','Nunito',sans-serif;
  background:var(--bg);color:var(--text-primary);
  min-height:100dvh;-webkit-font-smoothing:antialiased;
  overflow-x:hidden;
}
button{cursor:pointer;border:none;background:none;font-family:inherit;}
input{font-family:inherit;font-size:inherit;outline:none;border:none;}
a{text-decoration:none;color:inherit;}

/* LAYOUT */
.auth-wrapper{
  min-height:100dvh;
  display:flex;flex-direction:column;
  max-width:480px;margin:0 auto;
}

/* HERO */
.auth-hero{
  background:linear-gradient(160deg,var(--green-700) 0%,var(--green-500) 55%,var(--blue-500) 100%);
  padding:60px 32px 80px;
  text-align:center;position:relative;overflow:hidden;
  flex-shrink:0;
}
.auth-hero::before{
  content:'';position:absolute;top:-60px;right:-60px;
  width:240px;height:240px;
  background:rgba(255,255,255,.06);border-radius:50%;
}
.auth-hero::after{
  content:'';position:absolute;bottom:-80px;left:-40px;
  width:280px;height:280px;
  background:rgba(255,255,255,.04);border-radius:50%;
}
.hero-logo{
  width:72px;height:72px;
  background:rgba(255,255,255,.18);
  border-radius:22px;
  display:flex;align-items:center;justify-content:center;
  font-size:36px;margin:0 auto 18px;
  border:2px solid rgba(255,255,255,.3);
  backdrop-filter:blur(8px);
  position:relative;z-index:1;
}
.hero-title{
  font-size:32px;font-weight:900;color:#fff;
  position:relative;z-index:1;
}
.hero-subtitle{
  font-size:15px;color:rgba(255,255,255,.8);
  margin-top:8px;font-weight:500;
  position:relative;z-index:1;
}

/* FORM CARD */
.auth-card{
  background:var(--bg-card);
  border-radius:32px 32px 0 0;
  margin-top:-32px;
  padding:32px 24px 40px;
  flex:1;
  box-shadow:0 -4px 40px rgba(0,0,0,.1);
  position:relative;z-index:5;
}
.auth-tabs{
  display:flex;gap:0;
  background:var(--bg-input);
  border-radius:var(--radius-sm);
  padding:4px;
  margin-bottom:28px;
}
.auth-tab{
  flex:1;padding:10px;
  border-radius:8px;
  text-align:center;
  font-size:15px;font-weight:700;
  color:var(--text-muted);
  cursor:pointer;
  transition:var(--transition);
}
.auth-tab.active{
  background:var(--bg-card);
  color:var(--green-700);
  box-shadow:var(--shadow-md);
}

/* FORM ELEMENTS */
.form-group{margin-bottom:16px;position:relative;}
.form-label{
  font-size:13px;font-weight:700;
  color:var(--text-sec);
  margin-bottom:6px;display:block;
}
.input-wrap{
  position:relative;
  display:flex;align-items:center;
}
.input-icon{
  position:absolute;right:14px;
  font-size:18px;color:var(--text-muted);
  pointer-events:none;
}
[dir="ltr"] .input-icon{right:auto;left:14px;}
.form-input{
  width:100%;
  background:var(--bg-input);
  border:1.5px solid var(--border);
  border-radius:var(--radius-sm);
  padding:13px 44px 13px 14px;
  font-size:15px;color:var(--text-primary);
  transition:var(--transition);
  -webkit-appearance:none;
}
[dir="ltr"] .form-input{padding:13px 14px 13px 44px;}
.form-input:focus{
  border-color:var(--green-500);
  background:var(--bg-card);
  box-shadow:0 0 0 3px rgba(26,159,106,.1);
}
.form-input::placeholder{color:var(--text-muted);}

/* Password toggle */
.pwd-toggle{
  position:absolute;left:14px;
  font-size:18px;color:var(--text-muted);
  cursor:pointer;
  transition:var(--transition);
}
[dir="ltr"] .pwd-toggle{left:auto;right:14px;}
.pwd-toggle:hover{color:var(--green-600);}

/* Error */
.field-error{
  font-size:12px;color:var(--red-500);
  margin-top:5px;display:none;
  font-weight:600;
}
.field-error.show{display:block;}
.form-input.error{border-color:var(--red-500);}

/* Remember / Forgot */
.form-row{
  display:flex;align-items:center;justify-content:space-between;
  margin-bottom:20px;
}
.checkbox-label{
  display:flex;align-items:center;gap:8px;
  cursor:pointer;font-size:13px;font-weight:600;color:var(--text-sec);
}
.custom-check{
  width:20px;height:20px;
  background:var(--bg-input);
  border:1.5px solid var(--border);
  border-radius:6px;
  display:flex;align-items:center;justify-content:center;
  font-size:12px;transition:var(--transition);
  flex-shrink:0;
}
.checkbox-label input{display:none;}
.checkbox-label input:checked + .custom-check{
  background:var(--green-600);border-color:var(--green-600);color:#fff;
}
.forgot-link{
  font-size:13px;color:var(--green-600);
  font-weight:700;cursor:pointer;
}
.forgot-link:hover{text-decoration:underline;}

/* MAIN BUTTON */
.btn-auth{
  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 20px rgba(26,127,90,.3);
  position:relative;overflow:hidden;
}
.btn-auth::after{
  content:'';position:absolute;inset:0;
  background:rgba(255,255,255,0);transition:var(--transition);
}
.btn-auth:hover::after{background:rgba(255,255,255,.08);}
.btn-auth:active{transform:scale(.98);}
.btn-auth:disabled{opacity:.6;pointer-events:none;}
.btn-auth .btn-spinner{
  display:none;width:20px;height:20px;
  border:2px solid rgba(255,255,255,.4);
  border-top-color:white;border-radius:50%;
  animation:spin .7s linear infinite;
  margin:0 auto;
}
@keyframes spin{to{transform:rotate(360deg);}}
.btn-auth.loading span{display:none;}
.btn-auth.loading .btn-spinner{display:block;}

/* DIVIDER */
.divider{
  display:flex;align-items:center;gap:12px;
  margin:20px 0;
  color:var(--text-muted);font-size:12px;font-weight:600;
}
.divider::before,.divider::after{
  content:'';flex:1;height:1px;background:var(--border);
}

/* SOCIAL BUTTONS */
.social-row{display:flex;gap:10px;}
.btn-social{
  flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
  padding:12px;
  background:var(--bg-input);
  border:1.5px solid var(--border);
  border-radius:var(--radius-sm);
  font-size:14px;font-weight:700;color:var(--text-sec);
  transition:var(--transition);cursor:pointer;
}
.btn-social:hover{border-color:var(--green-400);color:var(--green-700);}
.social-icon{font-size:20px;}

/* FOOTER */
.auth-footer{
  text-align:center;margin-top:24px;
  font-size:14px;color:var(--text-sec);
}
.auth-footer a{color:var(--green-600);font-weight:700;cursor:pointer;}

/* ── REGISTER FORM ── */
/* User type selector */
.user-type-grid{
  display:grid;grid-template-columns:1fr 1fr;gap:10px;
  margin-bottom:20px;
}
.type-card{
  padding:16px 10px;
  background:var(--bg-input);
  border:2px solid var(--border);
  border-radius:var(--radius-md);
  text-align:center;cursor:pointer;
  transition:var(--transition);
}
.type-card.selected{
  border-color:var(--green-500);
  background:var(--green-50);
}
.type-card .tc-icon{font-size:30px;margin-bottom:8px;}
.type-card .tc-label{font-size:13px;font-weight:800;color:var(--text-primary);}
.type-card .tc-sub{font-size:11px;color:var(--text-muted);margin-top:3px;}

/* Wilaya select */
.form-select{
  width:100%;
  background:var(--bg-input);
  border:1.5px solid var(--border);
  border-radius:var(--radius-sm);
  padding:13px 44px 13px 14px;
  font-size:15px;color:var(--text-primary);
  transition:var(--transition);
  -webkit-appearance:none;
  cursor:pointer;
}
.form-select:focus{border-color:var(--green-500);background:var(--bg-card);}

/* Progress bar for register */
.reg-progress{
  display:flex;gap:6px;margin-bottom:24px;
}
.rp-step{
  flex:1;height:4px;border-radius:2px;
  background:var(--border);transition:var(--transition);
}
.rp-step.done{background:var(--green-400);}
.rp-step.active{background:var(--green-600);}

/* Vet license upload */
.upload-zone{
  border:2px dashed var(--border);
  border-radius:var(--radius-md);
  padding:24px;text-align:center;
  cursor:pointer;transition:var(--transition);
  background:var(--bg-input);
}
.upload-zone:hover{border-color:var(--green-400);background:var(--green-50);}
.upload-zone .up-icon{font-size:32px;margin-bottom:8px;}
.upload-zone p{font-size:13px;color:var(--text-sec);font-weight:600;}
.upload-zone input{display:none;}

/* Toast */
#toast{
  position:fixed;top:16px;left:50%;transform:translateX(-50%);
  background:var(--bg-card);border-radius:var(--radius-md);
  padding:14px 20px;
  display:flex;align-items:center;gap:10px;
  box-shadow:var(--shadow-xl);
  border:1px solid var(--border);
  font-size:13px;font-weight:700;
  z-index:9999;
  opacity:0;pointer-events:none;
  transition:opacity .3s;
  width:90%;max-width:360px;
}
#toast.show{opacity:1;pointer-events:auto;}

/* Top float bar */
.top-float-bar{
  position:fixed;top:14px;left:50%;transform:translateX(-50%);
  z-index:200;display:flex;align-items:center;gap:8px;
}

/* Language switcher */
.lang-switcher{position:relative;}
.lang-active-btn{
  display:flex;align-items:center;gap:6px;
  background:rgba(255,255,255,.18);
  border:1px solid rgba(255,255,255,.3);
  border-radius:22px;padding:7px 14px;
  color:#fff;font-size:13px;font-weight:700;
  cursor:pointer;transition:var(--transition);
  backdrop-filter:blur(10px);
  font-family:'Tajawal',sans-serif;
}
.lang-active-btn:hover{background:rgba(255,255,255,.28);}
.lang-flag{font-size:16px;line-height:1;}
.lang-code{font-weight:800;}
.lang-chevron{font-size:10px;opacity:.7;transition:var(--transition);}
.lang-switcher.open .lang-chevron{transform:rotate(180deg);}

.lang-dropdown{
  position:absolute;top:calc(100% + 8px);left:50%;transform:translateX(-50%);
  background:var(--bg-card);
  border:1px solid var(--border);
  border-radius:14px;
  padding:6px;
  min-width:150px;
  box-shadow:0 8px 32px rgba(0,0,0,.2);
  display:none;
  animation:dropIn .2s ease both;
  z-index:300;
}
.lang-switcher.open .lang-dropdown{display:block;}
@keyframes dropIn{
  from{opacity:0;transform:translateX(-50%) translateY(-8px);}
  to{opacity:1;transform:translateX(-50%) translateY(0);}
}
.lang-opt{
  display:flex;align-items:center;gap:10px;
  padding:10px 12px;border-radius:10px;
  font-size:14px;font-weight:700;color:var(--text-primary);
  cursor:pointer;transition:var(--transition);
}
.lang-opt:hover{background:var(--green-50);color:var(--green-700);}
.lang-check{margin-right:auto;color:var(--green-600);font-weight:900;}

/* Theme mini button */
.theme-btn-mini{
  width:40px;height:40px;
  background:rgba(255,255,255,.18);
  border:1px solid rgba(255,255,255,.3);
  border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  font-size:18px;cursor:pointer;
  backdrop-filter:blur(10px);
  transition:var(--transition);
}
.theme-btn-mini:hover{background:rgba(255,255,255,.3);}
[data-theme="dark"] .theme-btn-mini{background:rgba(255,255,255,.1);}
</style>
</head>
<body>

<!-- ── TOP FLOATING BAR ── -->
<div class="top-float-bar">
  <!-- Language switcher -->
  <div class="lang-switcher" id="lang-switcher">
    <button class="lang-active-btn" onclick="toggleLangMenu()" id="lang-active-btn">
      <span class="lang-flag" id="lang-flag">🇩🇿</span>
      <span class="lang-code" id="lang-code">عر</span>
      <span class="lang-chevron">▾</span>
    </button>
    <div class="lang-dropdown" id="lang-dropdown">
      <div class="lang-opt" onclick="setLang('ar','🇩🇿','عر','ar','rtl')">
        <span>🇩🇿</span> العربية
        <span class="lang-check" id="lc-ar">✓</span>
      </div>
      <div class="lang-opt" onclick="setLang('fr','🇫🇷','Fr','fr','ltr')">
        <span>🇫🇷</span> Français
        <span class="lang-check" id="lc-fr" style="display:none">✓</span>
      </div>
      <div class="lang-opt" onclick="setLang('en','🇬🇧','En','en','ltr')">
        <span>🇬🇧</span> English
        <span class="lang-check" id="lc-en" style="display:none">✓</span>
      </div>
    </div>
  </div>

  <!-- Theme toggle -->
  <button class="theme-btn-mini" onclick="toggleTheme()" id="theme-btn-mini" title="تبديل المظهر">🌙</button>
</div>
<div id="toast">
  <span id="toast-icon">✅</span>
  <span id="toast-msg"></span>
</div>

<div class="auth-wrapper">

  <!-- HERO -->
  <div class="auth-hero">
    <div class="hero-logo">🐾</div>
    <div class="hero-title">بيطري</div>
    <div class="hero-subtitle">منصة الرعاية البيطرية في الجزائر</div>
  </div>

  <!-- CARD -->
  <div class="auth-card">

    <!-- TABS -->
    <div class="auth-tabs">
      <div class="auth-tab active" id="tab-login" onclick="switchTab('login')">تسجيل الدخول</div>
      <div class="auth-tab" id="tab-register" onclick="switchTab('register')">حساب جديد</div>
    </div>

    <!-- ══ LOGIN FORM ══ -->
    <div id="form-login">
      <div class="form-group">
        <label class="form-label">رقم الهاتف</label>
        <div class="input-wrap">
          <span class="input-icon">📱</span>
          <input type="tel" class="form-input" id="login-phone"
            placeholder="05XX XX XX XX" maxlength="10" inputmode="tel"
            oninput="this.value=this.value.replace(/\D/g,'')">
        </div>
        <div class="field-error" id="err-login-phone">أدخل رقم هاتف صحيح</div>
      </div>

      <div class="form-group">
        <label class="form-label">كلمة المرور</label>
        <div class="input-wrap">
          <span class="input-icon">🔒</span>
          <input type="password" class="form-input" id="login-pass"
            placeholder="••••••••" autocomplete="current-password">
          <span class="pwd-toggle" onclick="togglePwd('login-pass', this)">👁</span>
        </div>
        <div class="field-error" id="err-login-pass">أدخل كلمة المرور</div>
      </div>

      <div class="form-row">
        <label class="checkbox-label">
          <input type="checkbox" id="remember-me">
          <div class="custom-check" id="check-remember"></div>
          تذكّرني
        </label>
        <span class="forgot-link" onclick="showForgot()">نسيت كلمة المرور؟</span>
      </div>

      <button class="btn-auth" id="login-btn" onclick="submitLogin()">
        <span>دخول</span>
        <div class="btn-spinner"></div>
      </button>

      <div class="divider">أو</div>
      <div class="social-row">
        <button class="btn-social" onclick="showToast('info','Google — قريباً')">
          <span class="social-icon">🌐</span> Google
        </button>
        <button class="btn-social" onclick="showToast('info','Facebook — قريباً')">
          <span class="social-icon">📘</span> Facebook
        </button>
      </div>
    </div>

    <!-- ══ REGISTER FORM ══ -->
    <div id="form-register" style="display:none;">

      <!-- Progress -->
      <div class="reg-progress" id="reg-progress">
        <div class="rp-step active" id="rp1"></div>
        <div class="rp-step" id="rp2"></div>
        <div class="rp-step" id="rp3"></div>
      </div>

      <!-- Step 1: User Type -->
      <div id="reg-step-1">
        <div class="form-label" style="font-size:15px;margin-bottom:14px;">اختر نوع حسابك</div>
        <div class="user-type-grid">
          <div class="type-card" data-role="pet_owner" onclick="selectRole(this)">
            <div class="tc-icon">🐾</div>
            <div class="tc-label">صاحب حيوان أليف</div>
            <div class="tc-sub">قط، كلب، طائر...</div>
          </div>
          <div class="type-card" data-role="farm_owner" onclick="selectRole(this)">
            <div class="tc-icon">🚜</div>
            <div class="tc-label">مربي / مزرعة</div>
            <div class="tc-sub">أبقار، أغنام، خيول...</div>
          </div>
          <div class="type-card" data-role="vet" onclick="selectRole(this)">
            <div class="tc-icon">👨‍⚕️</div>
            <div class="tc-label">طبيب بيطري</div>
            <div class="tc-sub">تسجيل كمقدّم خدمة</div>
          </div>
          <div class="type-card" data-role="farm_owner" onclick="selectRole(this)">
            <div class="tc-icon">🏪</div>
            <div class="tc-label">عيادة / مركز</div>
            <div class="tc-sub">إدارة فريق أطباء</div>
          </div>
        </div>
        <div class="field-error show" id="err-role" style="display:none;">الرجاء اختيار نوع الحساب</div>
        <button class="btn-auth" onclick="regStep(2)">
          <span>التالي ←</span><div class="btn-spinner"></div>
        </button>
      </div>

      <!-- Step 2: Basic Info -->
      <div id="reg-step-2" style="display:none;">
        <div class="form-group">
          <label class="form-label">الاسم الكامل</label>
          <div class="input-wrap">
            <span class="input-icon">👤</span>
            <input type="text" class="form-input" id="reg-name" placeholder="سارة بن علي">
          </div>
          <div class="field-error" id="err-reg-name">أدخل اسمك الكامل</div>
        </div>
        <div class="form-group">
          <label class="form-label">رقم الهاتف</label>
          <div class="input-wrap">
            <span class="input-icon">📱</span>
            <input type="tel" class="form-input" id="reg-phone"
              placeholder="05XX XX XX XX" maxlength="10" inputmode="tel"
              oninput="this.value=this.value.replace(/\D/g,'')">
          </div>
          <div class="field-error" id="err-reg-phone">أدخل رقم هاتف صحيح (10 أرقام)</div>
        </div>
        <div class="form-group">
          <label class="form-label">البريد الإلكتروني (اختياري)</label>
          <div class="input-wrap">
            <span class="input-icon">📧</span>
            <input type="email" class="form-input" id="reg-email" placeholder="example@gmail.com">
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">الولاية</label>
          <div class="input-wrap">
            <span class="input-icon">📍</span>
            <select class="form-select" id="reg-wilaya"></select>
          </div>
        </div>
        <button class="btn-auth" onclick="regStep(3)">
          <span>التالي ←</span><div class="btn-spinner"></div>
        </button>
        <button style="width:100%;margin-top:10px;padding:12px;background:var(--bg-input);border-radius:var(--radius-sm);font-size:14px;font-weight:700;color:var(--text-sec);cursor:pointer;" onclick="regStep(1)">
          → رجوع
        </button>
      </div>

      <!-- Step 3: Password + (Vet extras) -->
      <div id="reg-step-3" style="display:none;">
        <div class="form-group">
          <label class="form-label">كلمة المرور</label>
          <div class="input-wrap">
            <span class="input-icon">🔒</span>
            <input type="password" class="form-input" id="reg-pass" placeholder="8 أحرف على الأقل"
              autocomplete="new-password" oninput="checkPassStrength()">
            <span class="pwd-toggle" onclick="togglePwd('reg-pass', this)">👁</span>
          </div>
          <div class="field-error" id="err-reg-pass">كلمة المرور يجب أن تكون 8 أحرف على الأقل</div>
          <!-- Strength bar -->
          <div style="margin-top:8px;height:4px;background:var(--border);border-radius:2px;">
            <div id="pass-strength-bar" style="height:100%;border-radius:2px;width:0%;transition:all .3s;"></div>
          </div>
          <div id="pass-strength-label" style="font-size:11px;margin-top:4px;color:var(--text-muted);font-weight:600;"></div>
        </div>
        <div class="form-group">
          <label class="form-label">تأكيد كلمة المرور</label>
          <div class="input-wrap">
            <span class="input-icon">🔒</span>
            <input type="password" class="form-input" id="reg-pass2" placeholder="••••••••"
              autocomplete="new-password">
            <span class="pwd-toggle" onclick="togglePwd('reg-pass2', this)">👁</span>
          </div>
          <div class="field-error" id="err-reg-pass2">كلمات المرور غير متطابقة</div>
        </div>

        <!-- Vet extra fields -->
        <div id="vet-extras" style="display:none;">
          <div class="form-group">
            <label class="form-label">رقم رخصة مزاولة المهنة</label>
            <div class="input-wrap">
              <span class="input-icon">📋</span>
              <input type="text" class="form-input" id="vet-license" placeholder="VET-XXXX-XXXX">
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">الشهادة / الترخيص المهني</label>
            <div class="upload-zone" onclick="document.getElementById('vet-doc').click()">
              <div class="up-icon">📄</div>
              <p id="upload-label">انقر لرفع صورة الشهادة (PDF أو صورة)</p>
              <input type="file" id="vet-doc" accept=".pdf,image/*" onchange="handleUpload(this)">
            </div>
          </div>
        </div>

        <!-- Terms -->
        <label class="checkbox-label" style="margin-bottom:16px;">
          <input type="checkbox" id="terms-check">
          <div class="custom-check" id="check-terms"></div>
          <span>أوافق على <a href="#" style="color:var(--green-600);">شروط الاستخدام</a> و<a href="#" style="color:var(--green-600);">سياسة الخصوصية</a></span>
        </label>

        <button class="btn-auth" id="register-btn" onclick="submitRegister()">
          <span>إنشاء الحساب ✓</span>
          <div class="btn-spinner"></div>
        </button>
        <button style="width:100%;margin-top:10px;padding:12px;background:var(--bg-input);border-radius:var(--radius-sm);font-size:14px;font-weight:700;color:var(--text-sec);cursor:pointer;" onclick="regStep(2)">
          → رجوع
        </button>
      </div>
    </div><!-- /form-register -->

    <div class="auth-footer" id="auth-footer">
      ليس لديك حساب؟ <a onclick="switchTab('register')">سجّل الآن</a>
    </div>

  </div><!-- /auth-card -->
</div>

<script>
// ══ STATE ══
let currentTab = 'login';
let regCurrentStep = 1;
let selectedRole = null;
const WILAYAS = ['الجزائر','وهران','قسنطينة','عنابة','سطيف','البليدة','تلمسان','باتنة','بجاية','الجلفة','سيدي بلعباس','بسكرة','مسيلة','تبسة','سكيكدة','الشلف','تيارت','بومرداس','مستغانم','جيجل','تيزي وزو','المدية','الأغواط','خنشلة','أم البواقي','أدرار','بشار','إليزي','تمنراست','تندوف'];

// ══ THEME ══
const theme = localStorage.getItem('baitari_theme') || 'light';
document.documentElement.setAttribute('data-theme', theme);
// ── LANG SYSTEM ──
const LANG_LABELS = {
  ar: { flag:'🇩🇿', code:'عر', dir:'rtl', html:'ar' },
  fr: { flag:'🇫🇷', code:'Fr', dir:'ltr', html:'fr' },
  en: { flag:'🇬🇧', code:'En', dir:'ltr', html:'en' },
};

let currentLang = localStorage.getItem('baitari_lang') || 'ar';

function applyLang(lang) {
  const L = LANG_LABELS[lang] || LANG_LABELS.ar;
  document.documentElement.lang = L.html;
  document.documentElement.dir  = L.dir;
  document.documentElement.setAttribute('data-lang', lang);
  document.getElementById('lang-flag').textContent = L.flag;
  document.getElementById('lang-code').textContent = L.code;
  // Check marks
  ['ar','fr','en'].forEach(l => {
    const el = document.getElementById('lc-'+l);
    if (el) el.style.display = l === lang ? '' : 'none';
  });
  // Dynamic text updates
  applyI18n(lang);
}

const I18N = {
  ar: {
    phone_label:'رقم الهاتف', pass_label:'كلمة المرور',
    remember:'تذكّرني', forgot:'نسيت كلمة المرور؟',
    login_btn:'دخول', tab_login:'تسجيل الدخول', tab_register:'حساب جديد',
    tagline:'منصة الرعاية البيطرية في الجزائر',
    register_btn:'إنشاء الحساب ✓', next_btn:'التالي ←',
    choose_type:'اختر نوع حسابك',
    footer_login:'ليس لديك حساب؟', footer_login_link:'سجّل الآن',
    footer_register:'لديك حساب بالفعل؟', footer_register_link:'سجّل الدخول',
  },
  fr: {
    phone_label:'Numéro de téléphone', pass_label:'Mot de passe',
    remember:'Se souvenir', forgot:'Mot de passe oublié ?',
    login_btn:'Connexion', tab_login:'Se connecter', tab_register:'Créer un compte',
    tagline:'Plateforme vétérinaire en Algérie',
    register_btn:'Créer mon compte ✓', next_btn:'Suivant →',
    choose_type:'Choisissez votre type de compte',
    footer_login:'Pas de compte ?', footer_login_link:'S'inscrire',
    footer_register:'Déjà un compte ?', footer_register_link:'Se connecter',
  },
  en: {
    phone_label:'Phone number', pass_label:'Password',
    remember:'Remember me', forgot:'Forgot password?',
    login_btn:'Sign in', tab_login:'Sign in', tab_register:'Create account',
    tagline:'Veterinary care platform in Algeria',
    register_btn:'Create account ✓', next_btn:'Next →',
    choose_type:'Choose your account type',
    footer_login:'No account?', footer_login_link:'Sign up',
    footer_register:'Already have an account?', footer_register_link:'Sign in',
  },
};

function applyI18n(lang) {
  const T = I18N[lang] || I18N.ar;
  const set = (id, val) => { const el = document.getElementById(id); if(el) el.textContent = val; };
  const setPlh = (id, val) => { const el = document.getElementById(id); if(el) el.placeholder = val; };

  set('tab-login', T.tab_login);
  set('tab-register', T.tab_register);
  setPlh('login-phone', lang === 'ar' ? '05XX XX XX XX' : '05XX XX XX XX');
  // Tagline
  const tl = document.querySelector('.hero-subtitle');
  if (tl) tl.textContent = T.tagline;
  // Labels
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const k = el.dataset.i18n;
    if (T[k]) el.textContent = T[k];
  });
}

function setLang(lang, flag, code, html, dir) {
  currentLang = lang;
  localStorage.setItem('baitari_lang', lang);
  document.cookie = 'baitari_lang=' + lang + ';path=/;max-age=' + (365*24*3600);
  applyLang(lang);
  toggleLangMenu();
}

function toggleLangMenu() {
  document.getElementById('lang-switcher').classList.toggle('open');
}
// Close on outside click
document.addEventListener('click', e => {
  if (!e.target.closest('#lang-switcher')) {
    document.getElementById('lang-switcher')?.classList.remove('open');
  }
});

function toggleTheme() {
  const t = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', t);
  localStorage.setItem('baitari_theme', t);
  document.cookie = 'baitari_theme=' + t + ';path=/;max-age=' + (365*24*3600);
  document.getElementById('theme-btn-mini').textContent = t === 'dark' ? '☀️' : '🌙';
}

// Boot lang
applyLang(currentLang);
// Boot theme icon
const _th = localStorage.getItem('baitari_theme') || 'light';
if (_th === 'dark') document.getElementById('theme-btn-mini').textContent = '☀️';

// ══ WILAYA POPULATE ══
(function(){
  const sel = document.getElementById('reg-wilaya');
  WILAYAS.forEach(w => {
    const opt = document.createElement('option');
    opt.value = w; opt.textContent = w;
    sel.appendChild(opt);
  });
})();

// ══ TABS ══
function switchTab(tab) {
  currentTab = tab;
  document.getElementById('form-login').style.display = tab === 'login' ? '' : 'none';
  document.getElementById('form-register').style.display = tab === 'register' ? '' : 'none';
  document.getElementById('tab-login').classList.toggle('active', tab === 'login');
  document.getElementById('tab-register').classList.toggle('active', tab === 'register');
  document.getElementById('auth-footer').innerHTML = tab === 'login'
    ? 'ليس لديك حساب؟ <a onclick="switchTab(\'register\')">سجّل الآن</a>'
    : 'لديك حساب بالفعل؟ <a onclick="switchTab(\'login\')">سجّل الدخول</a>';
}

// ══ REGISTER STEPS ══
function selectRole(el) {
  document.querySelectorAll('.type-card').forEach(c => c.classList.remove('selected'));
  el.classList.add('selected');
  selectedRole = el.dataset.role;
}

function regStep(step) {
  if (step === 2 && !selectedRole) {
    showToast('error', 'الرجاء اختيار نوع الحساب');
    return;
  }
  if (step === 3) {
    const name = document.getElementById('reg-name').value.trim();
    const phone = document.getElementById('reg-phone').value.trim();
    if (!name) { document.getElementById('err-reg-name').classList.add('show'); return; }
    if (phone.length !== 10) { document.getElementById('err-reg-phone').classList.add('show'); return; }
    document.getElementById('err-reg-name').classList.remove('show');
    document.getElementById('err-reg-phone').classList.remove('show');
    // Show vet extras
    document.getElementById('vet-extras').style.display = selectedRole === 'vet' ? '' : 'none';
  }

  [1,2,3].forEach(n => {
    document.getElementById(`reg-step-${n}`).style.display = n === step ? '' : 'none';
    const dot = document.getElementById(`rp${n}`);
    if (n < step) dot.className = 'rp-step done';
    else if (n === step) dot.className = 'rp-step active';
    else dot.className = 'rp-step';
  });
  regCurrentStep = step;
}

function handleUpload(input) {
  if (input.files[0]) {
    document.getElementById('upload-label').textContent = '✅ ' + input.files[0].name;
    showToast('success', 'تم رفع الملف بنجاح');
  }
}

// ══ PASSWORD STRENGTH ══
function checkPassStrength() {
  const pass = document.getElementById('reg-pass').value;
  const bar  = document.getElementById('pass-strength-bar');
  const lbl  = document.getElementById('pass-strength-label');
  let score = 0;
  if (pass.length >= 8) score++;
  if (/[A-Z]/.test(pass)) score++;
  if (/[0-9]/.test(pass)) score++;
  if (/[^A-Za-z0-9]/.test(pass)) score++;
  const levels = [
    {w:'0%',    c:'transparent', t:''},
    {w:'30%',   c:'#ef4444',     t:'ضعيفة'},
    {w:'55%',   c:'#f59e0b',     t:'متوسطة'},
    {w:'80%',   c:'#22c55e',     t:'جيدة'},
    {w:'100%',  c:'#15803d',     t:'ممتازة'},
  ];
  const l = levels[score] || levels[0];
  bar.style.width = l.w;
  bar.style.background = l.c;
  lbl.textContent = l.t;
  lbl.style.color = l.c;
}

// ══ PASSWORD TOGGLE ══
function togglePwd(inputId, icon) {
  const inp = document.getElementById(inputId);
  const isPass = inp.type === 'password';
  inp.type = isPass ? 'text' : 'password';
  icon.textContent = isPass ? '🙈' : '👁';
}

// ══ SUBMIT LOGIN ══
async function submitLogin() {
  const phone = document.getElementById('login-phone').value.trim();
  const pass  = document.getElementById('login-pass').value;
  let valid = true;

  if (phone.length !== 10) {
    document.getElementById('err-login-phone').classList.add('show');
    document.getElementById('login-phone').classList.add('error');
    valid = false;
  } else {
    document.getElementById('err-login-phone').classList.remove('show');
    document.getElementById('login-phone').classList.remove('error');
  }
  if (!pass) {
    document.getElementById('err-login-pass').classList.add('show');
    document.getElementById('login-pass').classList.add('error');
    valid = false;
  } else {
    document.getElementById('err-login-pass').classList.remove('show');
    document.getElementById('login-pass').classList.remove('error');
  }
  if (!valid) return;

  const btn = document.getElementById('login-btn');
  btn.classList.add('loading');
  btn.disabled = true;

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

  // Demo: redirect based on hardcoded phone
  const roleMap = {
    '0661112233': 'pet_owner',
    '0770003344': 'farm_owner',
    '0550554455': 'vet',
    '0550001122': 'admin',
  };
  const role = roleMap[phone] || 'pet_owner';
  localStorage.setItem('baitari_role', role);
  localStorage.setItem('baitari_user', JSON.stringify({ phone, role, name: 'المستخدم' }));

  showToast('success', 'تم الدخول بنجاح! 🎉');
  setTimeout(() => { window.location.href = 'index.php'; }, 1000);
}

// ══ SUBMIT REGISTER ══
async function submitRegister() {
  const pass  = document.getElementById('reg-pass').value;
  const pass2 = document.getElementById('reg-pass2').value;
  if (pass.length < 8) {
    document.getElementById('err-reg-pass').classList.add('show'); return;
  }
  if (pass !== pass2) {
    document.getElementById('err-reg-pass2').classList.add('show'); return;
  }
  if (!document.getElementById('terms-check').checked) {
    showToast('error', 'الرجاء الموافقة على الشروط'); return;
  }

  const btn = document.getElementById('register-btn');
  btn.classList.add('loading'); btn.disabled = true;

  await new Promise(r => setTimeout(r, 1600));

  if (selectedRole === 'vet') {
    showToast('info', 'تم إرسال طلبك! سيتم مراجعته خلال 24 ساعة.');
  } else {
    showToast('success', 'تم إنشاء حسابك بنجاح! 🎉');
    localStorage.setItem('baitari_role', selectedRole);
    setTimeout(() => { window.location.href = 'index.php'; }, 1200);
  }
}

// ══ FORGOT ══
function showForgot() {
  showToast('info', 'سيتم إرسال رابط إعادة التعيين على هاتفك');
}

// ══ CHECKBOX VISUAL ══
document.querySelectorAll('.checkbox-label input').forEach(inp => {
  inp.addEventListener('change', () => {
    const check = inp.nextElementSibling;
    check.textContent = inp.checked ? '✓' : '';
  });
});

// ══ TOAST ══
function showToast(type, msg) {
  const t = document.getElementById('toast');
  const icons = { success:'✅', error:'❌', info:'ℹ️' };
  document.getElementById('toast-icon').textContent = icons[type];
  document.getElementById('toast-msg').textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3000);
}
</script>
</body>
</html>
