<%
  const isEditClient = mode === 'edit';
  const clientData = isEditClient && client ? client : {};
  const clientCountries = Array.isArray(countries) ? countries : [];
  const formLocale = typeof lang === 'string' && lang.toLowerCase().startsWith('en') ? 'en' : 'ar';
  const rawAvatar = clientData && typeof clientData.avatar === 'string' ? clientData.avatar.trim() : '';
  const hasUnsafeAvatarSegment = /(?:^|\/)(?:undefined|null)(?:[?#]|$)/i.test(rawAvatar);
  const avatarUrl = !hasUnsafeAvatarSegment && /^(?:https?:\/\/|\/(?!\/))/i.test(rawAvatar)
    ? rawAvatar
    : '';
  const avatarName = clientData && clientData.name ? clientData.name : (formLocale === 'ar' ? 'مستخدم' : 'User');
  const avatarInitial = avatarName
    .trim()
    .split(/\s+/)
    .slice(0, 2)
    .map((part) => Array.from(part)[0] || '')
    .join('') || (formLocale === 'ar' ? 'م' : 'U');
  const formText = formLocale === 'ar'
    ? {
        avatarTitle: 'صورة المستخدم',
        avatarHelper: 'PNG / JPG / JPEG فقط — ستبقى الصورة الحالية عند رفض الملف.',
        chooseImage: 'اختيار صورة',
        invalidImage: 'اختر صورة بصيغة PNG أو JPG أو JPEG فقط',
        name: 'الاسم الكامل',
        namePlaceholder: 'اكتب اسم المستخدم',
        nameRequired: 'اسم المستخدم مطلوب',
        email: 'البريد الإلكتروني',
        emailPlaceholder: 'name@example.com',
        emailRequired: 'البريد الإلكتروني مطلوب',
        emailInvalid: 'أدخل بريدًا إلكترونيًا صحيحًا',
        countryCode: 'مفتاح الدولة',
        countryPlaceholder: 'اختر مفتاح الدولة',
        countryRequired: 'مفتاح الدولة مطلوب',
        noCountries: 'لا توجد دول متاحة',
        phone: 'رقم الجوال',
        phonePlaceholder: '5xxxxxxxx',
        phoneRequired: 'رقم الجوال مطلوب',
        phoneInvalid: 'أدخل رقم جوال صحيحًا',
        password: isEditClient ? 'كلمة مرور جديدة' : 'كلمة المرور',
        passwordPlaceholder: isEditClient ? 'اتركها فارغة للاحتفاظ بالحالية' : 'أدخل كلمة مرور قوية',
        passwordRequired: 'كلمة المرور مطلوبة',
        passwordInvalid: 'استخدم 8 أحرف على الأقل: كبيرة وصغيرة ورقم ورمز',
        optional: 'اختياري'
      }
    : {
        avatarTitle: 'User photo',
        avatarHelper: 'PNG / JPG / JPEG only — the current image stays when a file is rejected.',
        chooseImage: 'Choose image',
        invalidImage: 'Choose a PNG, JPG, or JPEG image only',
        name: 'Full name',
        namePlaceholder: 'Enter user name',
        nameRequired: 'User name is required',
        email: 'Email address',
        emailPlaceholder: 'name@example.com',
        emailRequired: 'Email is required',
        emailInvalid: 'Enter a valid email address',
        countryCode: 'Country code',
        countryPlaceholder: 'Select country code',
        countryRequired: 'Country code is required',
        noCountries: 'No countries available',
        phone: 'Phone number',
        phonePlaceholder: '5xxxxxxxx',
        phoneRequired: 'Phone number is required',
        phoneInvalid: 'Enter a valid phone number',
        password: isEditClient ? 'New password' : 'Password',
        passwordPlaceholder: isEditClient ? 'Leave blank to keep the current password' : 'Enter a strong password',
        passwordRequired: 'Password is required',
        passwordInvalid: 'Use at least 8 characters with uppercase, lowercase, number, and symbol',
        optional: 'Optional'
      };
%>

<% if (isEditClient) { %>
  <div class="kt-people-upload" data-people-upload>
    <span class="kt-people-upload__preview">
      <img
        <%- avatarUrl ? `src="${avatarUrl.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}"` : '' %>
        alt=""
        data-people-upload-preview
        data-people-image
        <%= avatarUrl ? '' : 'hidden' %>
      >
      <span
        class="kt-people-avatar__fallback kt-people-avatar__fallback--upload"
        data-people-avatar-fallback
        aria-hidden="true"
        <%= avatarUrl ? 'hidden' : '' %>
      ><%= avatarInitial %></span>
    </span>
    <span class="kt-people-upload__copy">
      <strong><%= formText.avatarTitle %></strong>
      <span><%= formText.avatarHelper %></span>
      <small data-people-upload-name></small>
      <small class="kt-people-field__error" data-people-upload-error hidden></small>
    </span>
    <label class="kt-people-btn kt-people-btn--secondary" for="client-avatar">
      <i class="ti ti-photo-up" aria-hidden="true"></i>
      <span><%= formText.chooseImage %></span>
    </label>
    <input
      id="client-avatar"
      type="file"
      name="avatar"
      accept="image/png,image/jpeg,image/jpg"
      data-people-upload-input
      data-invalid-file-message="<%= formText.invalidImage %>"
    >
  </div>
  <input type="hidden" name="countryCode" value="<%= clientData.countryCode || '' %>">
<% } %>

<div class="kt-people-form__grid">
  <div class="kt-people-field" data-people-field>
    <label for="client-name"><%= formText.name %></label>
    <input
      class="kt-people-field__control"
      id="client-name"
      type="text"
      name="name"
      value="<%= clientData.name || '' %>"
      placeholder="<%= formText.namePlaceholder %>"
      minlength="2"
      maxlength="120"
      required
      autocomplete="name"
      data-required-message="<%= formText.nameRequired %>"
      data-invalid-message="<%= formText.nameRequired %>"
    >
    <small class="kt-people-field__error" data-people-field-error hidden></small>
  </div>

  <div class="kt-people-field" data-people-field>
    <label for="client-email"><%= formText.email %></label>
    <input
      class="kt-people-field__control"
      id="client-email"
      type="email"
      name="email"
      value="<%= clientData.email || '' %>"
      placeholder="<%= formText.emailPlaceholder %>"
      required
      autocomplete="email"
      dir="ltr"
      data-required-message="<%= formText.emailRequired %>"
      data-invalid-message="<%= formText.emailInvalid %>"
    >
    <small class="kt-people-field__error" data-people-field-error hidden></small>
  </div>

  <% if (!isEditClient) { %>
    <div class="kt-people-field" data-people-field>
      <label id="client-country-label"><%= formText.countryCode %></label>
      <div class="kt-people-select" data-people-select data-placeholder="<%= formText.countryPlaceholder %>">
        <select
          name="countryCode"
          required
          data-people-native-select
          aria-labelledby="client-country-label"
          data-required-message="<%= formText.countryRequired %>"
        >
          <option value=""><%= formText.countryPlaceholder %></option>
          <% clientCountries.forEach((country) => { %>
            <%
              const code = country && country.code ? String(country.code) : '';
              const countryName = country && country.name && typeof country.name === 'object'
                ? (country.name[formLocale] || country.name.ar || country.name.en || '')
                : (country && country.name ? country.name : '');
            %>
            <option value="<%= code %>"><%= countryName %> <%= code %></option>
          <% }) %>
        </select>
        <button
          class="kt-people-select__trigger"
          type="button"
          role="combobox"
          aria-haspopup="listbox"
          aria-expanded="false"
          aria-labelledby="client-country-label client-country-value"
          data-people-select-trigger
        >
          <span class="kt-people-select__value">
            <span class="kt-people-select__value-dot" aria-hidden="true"></span>
            <span id="client-country-value" data-people-select-value><%= formText.countryPlaceholder %></span>
          </span>
          <span class="kt-people-select__chevron" aria-hidden="true"><i class="ti ti-chevron-down"></i></span>
        </button>
        <div class="kt-people-select__menu" role="listbox" data-people-select-menu hidden>
          <% if (!clientCountries.length) { %>
            <span class="kt-people-select__option"><%= formText.noCountries %></span>
          <% } %>
          <% clientCountries.forEach((country, index) => { %>
            <%
              const code = country && country.code ? String(country.code) : '';
              const countryName = country && country.name && typeof country.name === 'object'
                ? (country.name[formLocale] || country.name.ar || country.name.en || '')
                : (country && country.name ? country.name : '');
            %>
            <button
              class="kt-people-select__option"
              id="client-country-option-<%= index %>"
              type="button"
              role="option"
              tabindex="-1"
              data-people-select-option
              data-value="<%= code %>"
              aria-selected="false"
            >
              <span><%= countryName %> <bdi><%= code %></bdi></span>
              <i class="ti ti-check kt-people-select__check" aria-hidden="true"></i>
            </button>
          <% }) %>
        </div>
      </div>
      <small class="kt-people-field__error" data-people-field-error hidden></small>
    </div>
  <% } %>

  <div class="kt-people-field" data-people-field>
    <label for="client-phone"><%= formText.phone %></label>
    <input
      class="kt-people-field__control"
      id="client-phone"
      type="tel"
      name="phone"
      value="<%= clientData.phone || '' %>"
      placeholder="<%= formText.phonePlaceholder %>"
      inputmode="numeric"
      pattern="[0-9]{9,10}"
      minlength="9"
      maxlength="10"
      required
      autocomplete="tel"
      dir="ltr"
      data-required-message="<%= formText.phoneRequired %>"
      data-invalid-message="<%= formText.phoneInvalid %>"
    >
    <small class="kt-people-field__error" data-people-field-error hidden></small>
  </div>

  <div class="kt-people-field <%= isEditClient ? 'kt-people-field--full' : '' %>" data-people-field>
    <label for="client-password">
      <%= formText.password %>
      <% if (isEditClient) { %><small>(<%= formText.optional %>)</small><% } %>
    </label>
    <div class="kt-people-password">
      <input
        class="kt-people-field__control"
        id="client-password"
        type="password"
        name="password"
        placeholder="<%= formText.passwordPlaceholder %>"
        <%= isEditClient ? '' : 'required' %>
        autocomplete="new-password"
        data-required-message="<%= formText.passwordRequired %>"
        data-invalid-message="<%= formText.passwordInvalid %>"
      >
      <button
        class="kt-people-password__toggle"
        type="button"
        data-people-password-toggle
        aria-label="<%= formText.password %>"
        aria-pressed="false"
      ><i class="ti ti-eye" aria-hidden="true"></i></button>
    </div>
    <small class="kt-people-field__hint"><%= formText.passwordInvalid %></small>
    <small class="kt-people-field__error" data-people-field-error hidden></small>
  </div>
</div>
