<template>
  <div v-if="authStore.isLoading" />
  <div v-else-if="!authStore.user || authStore.user.role !== 'admin'">
    <RouterLink to="/auth" /><!-- redirect handled in onMounted -->
  </div>

  <div v-else class="min-h-screen bg-background text-foreground">
    <Header />
    <main class="container mx-auto px-4 pt-32 pb-20">


      <!-- Admin Header -->
      <div class="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12">
        <div>
          <span class="text-primary font-display text-sm tracking-widest uppercase mb-2 block">{{ t("admin.managementCenter") }}</span>
          <h1 class="font-display text-4xl font-bold">Admin <span class="text-gradient">{{ t("admin.dashboard") }}</span></h1>
        </div>
        <div class="flex bg-card/40 backdrop-blur-md border border-border/50 rounded-2xl p-1 gap-1">
          <button v-for="tab in tabs" :key="tab.id" @click="activeTab = tab.id" :class="[
            'px-6 py-2.5 rounded-xl text-sm font-bold transition-all whitespace-nowrap',
            activeTab === tab.id ? 'bg-primary text-primary-foreground shadow-glow' : 'text-muted-foreground hover:bg-white/5 hover:text-foreground'
          ]">
            {{ t('admin.tabs.' + tab.id) }}
          </button>
        </div>
      </div>

      <!-- Global Search & Quick Actions -->
      <div class="flex flex-col gap-4 mb-8">
        <div class="flex flex-col sm:flex-row gap-4">
          <div class="relative flex-1">
            <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input type="text" v-model="searchQuery" :placeholder="t('admin.searchPlaceholder', { tab: activeTab })"
              class="w-full bg-card/40 border border-border/50 rounded-xl pl-10 pr-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all text-sm" />
          </div>
          <Button v-if="activeTab !== 'orders' && activeTab !== 'audit' && activeTab !== 'warehouse'" variant="hero" class="gap-2 sm:px-8" @click="handleAddNew">
            <Plus class="w-4 h-4" />{{ t("admin.addNew") }}
          </Button>
        </div>
      </div>

      <!-- Content Loader -->
      <div v-if="isLoading || isTranslationsLoading" class="flex items-center justify-center py-20">
        <RefreshCw class="w-8 h-8 text-primary animate-spin" />
      </div>

      <!-- Modular Sections -->
      <div v-else>
        <OrdersSection 
          v-if="activeTab === 'orders'"
          :orders="orders"
          :statusConfig="STATUS_CONFIG"
          :resourcesBaseUrl="RESOURCES_BASE_URL"
          :adminChatId="adminChatId"
          :notifyStatusMap="notifyStatusMap"
          :fiscalFormMap="fiscalFormMap"
          :searchQuery="searchQuery"
          @update-status="handleUpdateStatus"
          @delete-order="handleDeleteOrder"
          @attach-file="handleAttachFiles"
          @upload-photo="handleUploadPhoto"
          @delete-file="handleDeleteFile"
          @delete-photo="handleDeletePhoto"
          @toggle-photo-public="handleTogglePhotoPublic"
          @approve-review="handleApproveReview"
          @open-chat="toggleAdminChat"
          @close-chat="adminChatId = null"
          @update-notify="(id, val) => notifyStatusMap[id] = val"
          @update-fiscal="handleUpdateFiscal"
          @edit-order="handleEditOrder"
        />

        <MaterialsSection
          v-if="activeTab === 'materials'"
          :materials="materials"
          :searchQuery="searchQuery"
          @edit="m => { editingMaterial = m; Object.assign(matForm, m); showAddModal = true; }"
          @delete="handleDeleteMaterial"
          @toggle-active="toggleMaterialActive"
        />

        <ServicesSection
          v-if="activeTab === 'services'"
          :services="services"
          :searchQuery="searchQuery"
          @edit="s => { editingService = s; Object.assign(svcForm, s); showAddModal = true; }"
          @delete="handleDeleteService"
          @toggle-active="toggleServiceActive"
        />

        <UsersSection
          v-if="activeTab === 'users'"
          :users="usersResult.users"
          :total="usersResult.total"
          :currentPage="userPage"
          v-model:searchQuery="userSearch"
          @toggle-chat="handleToggleUserChat"
          @toggle-active="handleToggleUserActive"
          @reset-password="handleResetPassword"
          @toggle-role="handleUpdateUserRole"
          @update-page="p => { userPage = p; fetchUsers(); }"
        />

        <PostsSection
          v-if="activeTab === 'posts'"
          :posts="posts"
          :searchQuery="searchQuery"
          @edit="p => { editingPost = p; Object.assign(postForm, p); showAddModal = true; }"
          @delete="handleDeletePost"
          @toggle-publish="togglePostActive"
        />

        <PortfolioSection
          v-if="activeTab === 'portfolio'"
          :portfolioItems="portfolioItems"
          :resourcesBaseUrl="RESOURCES_BASE_URL"
          @delete="handleDeletePhoto"
          @refresh="fetchData"
        />

        <ScansSection
          v-if="activeTab === 'scans'"
          :resourcesBaseUrl="RESOURCES_BASE_URL"
        />

        <AuditSection
          v-if="activeTab === 'audit'"
          :auditLogs="auditLogs"
          :total="auditTotal"
          :currentPage="auditPage"
          @update-page="p => { auditPage = p; fetchAuditLogs(); }"
        />

        <ReviewsSection
          v-if="activeTab === 'reviews'"
        />
        <WarehouseSection
          v-if="activeTab === 'warehouse'"
          :materials="materials"
        />
      </div>
    </main>

    <!-- DEDICATED ORDER EDIT MODAL -->
    <div v-if="showOrderEditModal" class="fixed inset-0 z-[99999] flex items-center justify-center p-4" @keydown.esc="closeModals">
      <div class="absolute inset-0 bg-background/90 backdrop-blur-md" @click="showOrderEditModal = false" />
      <div class="relative w-full max-w-2xl bg-card border border-primary/30 rounded-3xl p-8 shadow-2xl overflow-y-auto max-h-[90vh]">
         <div class="flex justify-between items-center mb-6">
           <h3 class="text-2xl font-black font-display text-gradient">{{ t('admin.labels.editOrder') }} #{{ editingOrder?.id }}</h3>
           <button @click="showOrderEditModal = false" class="p-2 hover:bg-white/5 rounded-full transition-colors"><X class="w-6 h-6" /></button>
         </div>
         
         <form v-if="editingOrder" @submit.prevent="handleSaveOrder" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-4">
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.firstName") }}</label>
                    <input v-model="orderForm.first_name" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm focus:ring-2 ring-primary/20 outline-none" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.lastName") }}</label>
                    <input v-model="orderForm.last_name" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm focus:ring-2 ring-primary/20 outline-none" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.email") }}</label>
                    <input v-model="orderForm.email" type="email" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm focus:ring-2 ring-primary/20 outline-none" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.phone") }}</label>
                    <input v-model="orderForm.phone" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm focus:ring-2 ring-primary/20 outline-none" />
                  </div>
                </div>

                <div class="space-y-4">
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.shippingAddress") }}</label>
                    <input v-model="orderForm.shipping_address" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm focus:ring-2 ring-primary/20 outline-none" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase text-muted-foreground ml-1">{{ t("admin.fields.projectNotes") }}</label>
                    <textarea v-model="orderForm.notes" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm h-[132px] focus:ring-2 ring-primary/20 outline-none resize-none" />
                  </div>
                </div>
            </div>

            <div class="p-6 bg-primary/5 rounded-2xl border border-primary/10 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase text-primary/60 ml-1">{{ t("admin.fields.totalPrice") }} (EUR)</label>
                  <input v-model.number="orderForm.total_price" type="number" step="0.01" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2.5 text-sm font-black text-primary" />
                </div>
                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase text-primary/60 ml-1">{{ t("admin.fields.quantity") }} ({{ t('orders.labels.quantity') }})</label>
                  <input v-model.number="orderForm.quantity" type="number" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2.5 text-sm font-bold" />
                </div>
            </div>

            <div class="p-6 bg-muted/20 rounded-2xl border border-border/10 grid grid-cols-1 md:grid-cols-2 gap-6">

                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase text-primary/60 ml-1">{{ t("admin.fields.material") }}</label>
                  <select v-model="orderForm.material_name" class="w-full bg-background border border-border/50 rounded-xl px-3 py-2 text-sm">
                    <option value="">{{ t("admin.fields.material") }}...</option>
                    <option v-for="m in activeMaterials" :key="m.id" :value="m.name_en">{{ m.name_en }} ({{ m.name_ru }})</option>
                  </select>
                </div>
                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase text-primary/60 ml-1">{{ t("admin.fields.colors") }}</label>
                  <select v-model="orderForm.color_name" class="w-full bg-background border border-border/50 rounded-xl px-3 py-2 text-sm" :disabled="!orderForm.material_name">
                    <option value="">{{ t("admin.fields.colors") }}...</option>
                    <option v-for="c in materialColors" :key="c" :value="c">{{ c }}</option>
                    <option v-if="orderForm.color_name && !materialColors.includes(orderForm.color_name)" :value="orderForm.color_name">{{ orderForm.color_name }} ({{ t('admin.labels.current') }})</option>
                  </select>
                </div>
            </div>

            <!-- Review Feedback -->
            <div v-if="orderForm.review_text" class="p-4 bg-amber-500/5 border border-amber-500/20 rounded-2xl space-y-3">
               <div class="flex justify-between items-center">
                 <label class="text-[10px] font-bold uppercase text-amber-500 ml-1">{{ t('admin.labels.reviewContent') }}</label>
                 <div class="flex gap-1">
                    <Star v-for="i in 5" :key="i" class="w-3 h-3" :class="orderForm.rating >= i ? 'text-amber-500 fill-amber-500' : 'text-muted-foreground/20'" />
                 </div>
               </div>
               <textarea v-model="orderForm.review_text" class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-3 text-xs h-20 italic" />
            </div>

            <!-- Management Sections (Files & Photos) -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
               <!-- Files Section -->
               <div class="p-4 bg-muted/30 rounded-2xl border border-border/20 space-y-4">
                  <div class="flex items-center justify-between">
                    <span class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">{{ t("admin.fields.sourceFiles") }}</span>
                    <label class="p-1.5 bg-blue-500/10 text-blue-500 rounded-lg cursor-pointer hover:bg-blue-500 hover:text-white transition-all shadow-sm">
                      <Plus class="w-3.5 h-3.5" />
                      <input type="file" class="hidden" multiple @change="e => handleAttachFiles(editingOrder.id, (e.target as HTMLInputElement).files)" />
                    </label>
                  </div>
                  <div class="space-y-2 max-h-[200px] overflow-y-auto pr-1 custom-scrollbar">
                    <div v-for="f in (editingOrder?.files || [])" :key="f.id" class="flex items-center justify-between p-2 bg-background/50 rounded-xl border border-border/50 text-[11px] gap-2">
                       <span class="truncate flex-1 font-medium">{{ f.filename }}</span>
                       <div class="flex items-center gap-2">
                          <div class="flex items-center bg-muted/50 rounded-lg px-2 py-1 border border-border/50">
                             <span class="text-[9px] font-bold text-muted-foreground mr-1">COPIES:</span>
                             <input 
                               type="number" 
                               v-model.number="f.quantity" 
                               @change="adminUpdateFile(editingOrder.id, f.id, { quantity: f.quantity })"
                               class="w-8 bg-transparent text-center font-black outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" 
                             />
                          </div>
                          <a :href="`${RESOURCES_BASE_URL}/${f.file_path}`" target="_blank" class="p-1.5 hover:bg-primary/10 rounded-md text-primary transition-colors"><Database class="w-3 h-3" /></a>
                          <button type="button" @click="handleDeleteFile(editingOrder.id, f.id, f.filename)" class="p-1.5 hover:bg-rose-500/10 rounded-md text-rose-500 transition-colors"><Trash2 class="w-3 h-3" /></button>
                       </div>
                    </div>
                    <p v-if="!editingOrder?.files?.length" class="text-[10px] text-muted-foreground italic text-center py-4">{{ t('admin.labels.noFiles') }}</p>
                  </div>
               </div>

               <!-- Photos Section -->
               <div class="p-4 bg-muted/30 rounded-2xl border border-border/20 space-y-4">
                  <div class="flex items-center justify-between">
                    <span class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">{{ t("admin.fields.photoReport") }}</span>
                    <label class="p-1.5 bg-emerald-500/10 text-emerald-500 rounded-lg cursor-pointer hover:bg-emerald-500 hover:text-white transition-all shadow-sm">
                      <Plus class="w-3.5 h-3.5" />
                      <input type="file" class="hidden" accept="image/*" @change="e => handleUploadPhoto(editingOrder.id, (e.target as HTMLInputElement).files?.[0])" />
                    </label>
                  </div>
                  <div class="flex flex-wrap gap-2 max-h-[200px] overflow-y-auto pr-1">
                     <div v-for="p in (editingOrder?.photos || [])" :key="p.id" class="relative group">
                        <img :src="`${RESOURCES_BASE_URL}/${p.file_path}`" class="w-12 h-12 object-cover rounded-lg border border-border/50 shadow-sm" />
                        <button type="button" @click="handleDeletePhoto(p.id)" class="absolute -top-1 -right-1 p-0.5 bg-rose-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity shadow-lg">
                           <X class="w-2.5 h-2.5" />
                        </button>
                     </div>
                     <p v-if="!editingOrder?.photos?.length" class="text-[10px] text-muted-foreground italic text-center py-4 w-full">{{ t('admin.labels.noPhotos') }}</p>
                  </div>
               </div>
            </div>

            <div class="flex gap-4 pt-4">
              <Button type="button" variant="hero" class="flex-1 rounded-2xl h-12 bg-muted hover:bg-muted/80 text-foreground" @click="showOrderEditModal = false">{{ t("admin.actions.cancel") }}</Button>
              <Button type="submit" variant="hero" class="flex-[2] rounded-2xl h-12 shadow-glow">{{ t("admin.actions.save") }}</Button>
            </div>
         </form>
      </div>
    </div>

    <!-- Global Modals -->
    <div v-if="showAddModal" class="fixed inset-0 z-[99999] flex items-center justify-center p-4" @keydown.esc="closeModals">
      <div class="absolute inset-0 bg-background/80 backdrop-blur-sm" @click="closeModals" />
      <div class="relative w-full max-w-lg bg-card border border-border/50 rounded-3xl p-8 shadow-2xl overflow-y-auto max-h-[90vh]">
         <h3 class="text-xl font-bold font-display mb-6">{{ editingMaterial || editingService || editingPost ? t('admin.actions.edit') : t("admin.addNew") }}</h3>
         
              <!-- Material Modal Form -->
              <form v-if="activeTab === 'materials'" @submit.prevent="handleSaveMaterial" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameEn") }}</label><input v-model="matForm.name_en" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameRu") }}</label><input v-model="matForm.name_ru" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameMe") }}</label><input v-model="matForm.name_me" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameUa") }}</label><input v-model="matForm.name_ua" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                </div>

                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.technology") }}</label>
                  <select v-model="matForm.service_id" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm">
                    <option :value="null">{{ t("admin.fields.selectTechnology") }}...</option>
                    <option v-for="s in services" :key="s.id" :value="s.id">{{ s.name_en }} ({{ s.tech_type }})</option>
                  </select>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.longDescEn") }}</label><textarea v-model="matForm.long_desc_en" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2 text-xs h-20 resize-none" /></div>
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.longDescRu") }}</label><textarea v-model="matForm.long_desc_ru" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2 text-xs h-20 resize-none" /></div>
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.longDescMe") }}</label><textarea v-model="matForm.long_desc_me" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2 text-xs h-20 resize-none" /></div>
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.longDescUa") }}</label><textarea v-model="matForm.long_desc_ua" class="w-full bg-background border border-border/50 rounded-xl px-4 py-2 text-xs h-20 resize-none" /></div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.pricePerCm3") }}</label>
                    <input v-model.number="matForm.price_per_cm3" type="number" step="any" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.pricePerHour") }} ({{ t("admin.fields.override") }})</label>
                    <input v-model.number="matForm.price_per_hour" type="number" step="any" class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" />
                  </div>
                  <div class="space-y-1">
                    <label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.speedCoeff") }}</label>
                    <input v-model.number="matForm.speed_coeff" type="number" step="0.01" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" />
                  </div>
                </div>
                
                <div class="space-y-1">
                  <label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.colors") }}</label>
                  <div class="flex gap-2">
                    <input v-model="newColor" @keydown.enter.prevent="addColor" class="flex-1 bg-background border border-border/50 rounded-xl px-4 py-2 text-sm" placeholder="e.g. Red" />
                    <Button type="button" variant="hero" @click="addColor">{{ t('admin.actions.add') }}</Button>
                  </div>
                  <div class="flex flex-wrap gap-2 mt-3">
                    <div v-for="(c, idx) in matForm.available_colors" :key="idx" class="flex items-center gap-2 bg-background/50 border border-border/50 px-3 py-1.5 rounded-xl text-xs group transition-all hover:border-primary/30">
                      <div class="w-3 h-3 rounded-full border border-white/10 shadow-sm" :style="{ backgroundColor: c.toLowerCase() }"></div>
                      <span class="font-medium">{{ c }}</span>
                      <button type="button" @click="removeColor(idx)" class="text-muted-foreground hover:text-rose-500 transition-colors ml-1 opacity-0 group-hover:opacity-100"><X class="w-3 h-3" /></button>
                    </div>
                  </div>
                </div>

                <div class="flex gap-3 pt-6 border-t border-border/10">
                  <Button type="button" variant="ghost" class="flex-1" @click="closeModals">{{ t("admin.actions.cancel") }}</Button>
                  <Button type="submit" variant="hero" class="flex-1">{{ t("admin.actions.save") }}</Button>
                </div>
              </form>

              <!-- Service Modal Form -->
              <form v-if="activeTab === 'services'" @submit.prevent="handleSaveService" class="space-y-4">
                <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameEn") }}</label><input v-model="svcForm.name_en" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.nameRu") }}</label><input v-model="svcForm.name_ru" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                <div class="grid grid-cols-2 gap-4">
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.techType") }}</label><input v-model="svcForm.tech_type" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                  <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.pricePerHour") }}</label><input v-model.number="svcForm.price_per_hour" type="number" step="any" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                </div>
                <div class="flex gap-3 pt-6 border-t border-border/10">
                  <Button type="button" variant="ghost" class="flex-1" @click="closeModals">{{ t("admin.actions.cancel") }}</Button>
                  <Button type="submit" variant="hero" class="flex-1">{{ t("admin.actions.save") }}</Button>
                </div>
              </form>

              <!-- User Creation Form -->
              <form v-if="activeTab === 'users'" @submit.prevent="handleSaveUser" class="space-y-4">
                <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.email") }}</label><input v-model="userForm.email" type="email" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.password") }}</label><input v-model="userForm.password" type="password" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                <div class="grid grid-cols-2 gap-4">
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.firstName") }}</label><input v-model="userForm.first_name" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                   <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.lastName") }}</label><input v-model="userForm.last_name" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                </div>
                <div class="space-y-1"><label class="text-[10px] font-bold uppercase ml-1">{{ t("admin.fields.phone") }}</label><input v-model="userForm.phone" required class="w-full bg-background border border-border/50 rounded-xl px-4 py-3 text-sm" /></div>
                <div class="flex gap-3 pt-6 border-t border-border/10">
                  <Button type="button" variant="ghost" class="flex-1" @click="closeModals">{{ t("admin.actions.cancel") }}</Button>
                  <Button type="submit" variant="hero" class="flex-1">{{ t("admin.actions.save") }}</Button>
                </div>
              </form>
           </div>
         </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, computed, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute, RouterLink } from "vue-router";
import { useI18n } from "vue-i18n";
import i18n, { loadAdminTranslations } from "@/i18n";
import { toast } from "vue-sonner";

// Icons
import { 
  Package, Clock, RefreshCw, Search, Layers, Plus, Database, 
  Newspaper, History, X, Users, ImageIcon, Truck, CheckCircle2, XCircle, Star,
  Trash2, MessageCircle, Edit2
} from "lucide-vue-next";

// UI Components
import Button from "@/components/ui/button.vue";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";

// Admin Sections
import OrdersSection from "@/components/admin/OrdersSection.vue";
import MaterialsSection from "@/components/admin/MaterialsSection.vue";
import ServicesSection from "@/components/admin/ServicesSection.vue";
import UsersSection from "@/components/admin/UsersSection.vue";
import PostsSection from "@/components/admin/PostsSection.vue";
import PortfolioSection from "@/components/admin/PortfolioSection.vue";
import ScansSection from "@/components/admin/ScansSection.vue";
import AuditSection from "@/components/admin/AuditSection.vue";
import ReviewsSection from "@/components/admin/ReviewsSection.vue";
import WarehouseSection from "@/components/admin/WarehouseSection.vue";

// API & Stores
import { useAuthStore } from "@/stores/auth";
import { 
  adminGetOrders, adminUpdateOrder, adminGetMaterials, adminUpdateMaterial, 
  adminDeleteMaterial, adminCreateMaterial, adminGetServices, adminUpdateService, 
  adminDeleteService, adminCreateService, adminUploadOrderPhoto, adminUpdatePhotoStatus, 
  adminDeletePhoto, adminGetAllPhotos, adminAttachFile, adminUpdateFile, adminDeleteFile, adminDeleteOrder, 
  getBlogPosts, adminUpdatePost, adminDeletePost, adminCreatePost, 
  adminGetUsers, adminUpdateUser, adminCreateUser, 
  adminGetAuditLogs, approveOrderReview, RESOURCES_BASE_URL 
} from "@/lib/api";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

// Status Configuration shared with OrdersSection
const STATUS_CONFIG: Record<string, { color: string; icon: any }> = {
  pending:    { color: "text-amber-500 bg-amber-500/10",   icon: Clock },
  processing: { color: "text-blue-500 bg-blue-500/10",    icon: RefreshCw },
  shipped:    { color: "text-purple-500 bg-purple-500/10", icon: Truck },
  completed:  { color: "text-emerald-500 bg-emerald-500/10", icon: CheckCircle2 },
  cancelled:  { color: "text-rose-500 bg-rose-500/10",    icon: XCircle },
};

// State
const isLoading = ref(true);
const isTranslationsLoading = ref(false);
const searchQuery = ref("");
const adminChatId = ref<any>(null);

// Records
const orders = ref<any[]>([]);
const materials = ref<any[]>([]);
const services = ref<any[]>([]);
const posts = ref<any[]>([]);
const portfolioItems = ref<any[]>([]);
const auditLogs = ref<any[]>([]);
const auditTotal = ref(0);
const auditPage = ref(1);
const usersResult = ref({ users: [] as any[], total: 0, page: 1, size: 50 });
const userSearch = ref("");
const userPage = ref(1);

// Maps for reactive UI state
const notifyStatusMap = ref<Record<number, boolean>>({});
const fiscalFormMap = ref<Record<number, { fiscal_qr_url: string; ikof: string; jikr: string }>>({});

const tabs: { id: Tab }[] = [
  { id: "orders" },
  { id: "materials" },
  { id: "services" },
  { id: "portfolio" },
  { id: "scans" },
  { id: "reviews" },
  { id: "users" },
  { id: "posts" },
  { id: "audit" },
  { id: "warehouse" },
];

type Tab = "orders" | "materials" | "services" | "posts" | "users" | "portfolio" | "scans" | "audit" | "reviews" | "warehouse";

function getValidTab(val: any): Tab {
  const t = val?.toString();
  return ["orders", "materials", "services", "posts", "users", "portfolio", "scans", "audit", "reviews", "warehouse"].includes(t) ? (t as Tab) : "orders";
}

const activeTab = ref<Tab>(getValidTab(route.query.tab));

// Watchers
watch(activeTab, (newTab) => {
  if (route.query.tab !== newTab) {
    router.replace({ query: { ...route.query, tab: newTab } });
  }
  fetchData();
});

// React to language changes
watch(() => (i18n.global as any).locale.value, async (newLang) => {
  isTranslationsLoading.value = true;
  await loadAdminTranslations(newLang);
  isTranslationsLoading.value = false;
}, { immediate: true });

watch([searchQuery], () => {
  if (activeTab.value === 'orders') debouncedFetchData();
  else fetchData();
});

// Modals State & Forms
const showAddModal = ref(false);
const showOrderEditModal = ref(false);
const editingMaterial = ref<any | null>(null);
const editingService = ref<any | null>(null);
const editingPost = ref<any | null>(null);
const editingOrder = ref<any | null>(null);

const matForm = reactive({ 
  name_en: "", name_ru: "", name_ua: "", name_me: "", 
  desc_en: "", desc_ru: "", desc_ua: "", desc_me: "", 
  long_desc_en: "", long_desc_ru: "", long_desc_ua: "", long_desc_me: "",
  service_id: null as number | null,
  price_per_cm3: 0, price_per_hour: 0, speed_coeff: 1.0, available_colors: [] as string[], is_active: true 
});
const svcForm = reactive({ name_en: "", name_ru: "", name_ua: "", name_me: "", desc_en: "", desc_ru: "", desc_ua: "", desc_me: "", tech_type: "", price_per_hour: 0, is_active: true });
const postForm = reactive({ slug: "", title_en: "", title_me: "", title_ru: "", title_ua: "", category: "Technology", image_url: "", is_published: true });
const userForm = reactive({ email: "", password: "", first_name: "", last_name: "", phone: "" });
const orderForm = reactive({ total_price: 0, material_name: "", color_name: "", quantity: 1, first_name: "", last_name: "", email: "", phone: "", shipping_address: "", notes: "", review_text: "", rating: 0 });

const handleEditOrder = (order: any) => {
  editingOrder.value = order;
  Object.assign(orderForm, {
    total_price: Number(order.invoice_amount || 0),
    material_name: order.material_name || "",
    color_name: order.color_name || "",
    quantity: order.quantity || 1,
    first_name: order.first_name || "",
    last_name: order.last_name || "",
    email: order.email || "",
    phone: order.phone || "",
    shipping_address: order.shipping_address || "",
    notes: order.notes || "",
    review_text: order.review_text || "",
    rating: order.rating || 0
  });
  showOrderEditModal.value = true;
};

const handleEditOrderEvent = (e: any) => {
  if (e.detail) handleEditOrder(e.detail);
};

const handleGlobalEsc = (e: KeyboardEvent) => {
  if (e.key === 'Escape') {
    closeModals();
  }
};

onUnmounted(() => {
  window.removeEventListener('admin-edit-order', handleEditOrderEvent);
  window.removeEventListener('keydown', handleGlobalEsc);
});

const newColor = ref("");

const activeMaterials = computed(() => materials.value.filter((m: any) => m.is_active || m.is_active === 1));
const selectedMaterialObj = computed(() => activeMaterials.value.find((m: any) => m.name_en === orderForm.material_name || m.name_ru === orderForm.material_name));
const materialColors = computed(() => {
  if (!selectedMaterialObj.value) return [];
  try {
    return Array.isArray(selectedMaterialObj.value.available_colors) 
      ? selectedMaterialObj.value.available_colors 
      : JSON.parse(selectedMaterialObj.value.available_colors || "[]");
  } catch { return []; }
});

// Fetching Logic
let fetchTimeout: any = null;
function debouncedFetchData() {
  clearTimeout(fetchTimeout);
  fetchTimeout = setTimeout(fetchData, 400);
}

async function fetchData() {
  isLoading.value = true;
  try {
    const tab = activeTab.value;
    if (tab === "orders") {
      orders.value = await adminGetOrders({ search: searchQuery.value });
      orders.value.forEach(o => {
        if (notifyStatusMap.value[o.id] === undefined) notifyStatusMap.value[o.id] = true;
        if (!fiscalFormMap.value[o.id]) fiscalFormMap.value[o.id] = { fiscal_qr_url: o.fiscal_qr_url || "", ikof: o.ikof || "", jikr: o.jikr || "" };
      });
    }
    else if (tab === "materials") materials.value = await adminGetMaterials();
    else if (tab === "services")  services.value  = await adminGetServices();
    else if (tab === "posts")     posts.value     = await getBlogPosts(false);
    else if (tab === "portfolio") portfolioItems.value = await adminGetAllPhotos();
    else if (tab === "users")     await fetchUsers();
    else if (tab === "audit")     await fetchAuditLogs();
    else if (tab === "warehouse") {
      // Stock is handled inside WarehouseSection.vue onMounted, 
      // but we need materials list here too
      materials.value = await adminGetMaterials();
    }
  } catch (err: any) {
    toast.error(err.message || "Failed to load data");
  } finally {
    isLoading.value = false;
  }
}

async function fetchUsers() {
  usersResult.value = await adminGetUsers(userPage.value, 50, userSearch.value);
}

async function fetchAuditLogs() {
  const res = await adminGetAuditLogs(auditPage.value);
  auditLogs.value = res.logs; auditTotal.value = res.total;
}

// Global Handlers
const toggleAdminChat = (id: number) => adminChatId.value = adminChatId.value === id ? null : id;

const handleUpdateStatus = async (id: number, status: string) => {
  try {
    await adminUpdateOrder(id, { status, send_notification: notifyStatusMap.value[id] });
    toast.success("Status updated"); fetchData();
  } catch (err: any) { toast.error(err.message); }
};

const handleUpdateFiscal = async (id: number, data: any) => {
  try {
    await adminUpdateOrder(id, data); toast.success("Fiscal data saved"); fetchData();
  } catch (err: any) { toast.error(err.message); }
};


const handleApproveReview = async (id: number) => {
  try {
    await approveOrderReview(id); toast.success("Review approved"); fetchData();
  } catch (err: any) { toast.error(err.message); }
};

const handleDeleteOrder = async (id: number) => {
  if (confirm(`Delete Order #${id}?`)) { 
    try { await adminDeleteOrder(id); toast.success("Order deleted"); fetchData(); }
    catch (err: any) { toast.error(err.message); }
  }
};

const handleAttachFiles = async (orderId: number, files: FileList | File | null) => {
  if (!files || !orderId) {
    console.error("DEBUG: handleAttachFiles called with missing data:", { orderId, files });
    return;
  }
  
  const id = orderId;
  const fileArray = files instanceof FileList ? Array.from(files) : [files];
  
  const toastId = toast.loading(`Uploading ${fileArray.length} file(s)...`);

  try {
    // Perform parallel uploads for speed
    await Promise.all(fileArray.map(async (file) => {
      console.log(`DEBUG: Starting upload for: ${file.name} to order: ${id}`);
      const fd = new FormData();
      fd.append("file", file);
      return adminAttachFile(id, fd);
    }));
    
    toast.success(`${fileArray.length} file(s) attached successfully`, { id: toastId });
    await fetchData();
    
    // Re-sync editingOrder if open to show new files immediately
    if (editingOrder.value?.id === id) {
      const updatedOrder = orders.value.find(o => o.id === id);
      if (updatedOrder) editingOrder.value = updatedOrder;
    }
  } catch (err: any) { 
    console.error("DEBUG: handleAttachFiles failed:", err);
    toast.error(`Failed to attach files: ${err.message}`, { id: toastId }); 
  }
};

const handleUploadPhoto = async (id: number, file?: File) => {
  if (!file) return;
  try {
    const fd = new FormData(); fd.append("file", file);
    await adminUploadOrderPhoto(id, fd); toast.success("Photo added"); fetchData();
  } catch (err: any) { toast.error(err.message); }
};

const handleDeleteFile = async (id: number, fid: number, fname: string) => {
  if (confirm(`Delete ${fname}?`)) { 
    try { await adminDeleteFile(id, fid); fetchData(); }
    catch (err: any) { toast.error(err.message); }
  }
};

const handleDeletePhoto = async (photoId: number) => {
  if (confirm(`Delete photo?`)) { 
    try { 
      await adminDeletePhoto(photoId); 
      await fetchData();
      if (editingOrder.value) {
        const updated = orders.value.find(o => o.id === editingOrder.value?.id);
        if (updated) editingOrder.value = updated;
      }
    }
    catch (err: any) { toast.error(err.message); }
  }
};

const handleTogglePhotoPublic = async (id: number, current: boolean) => {
  try { await adminUpdatePhotoStatus(id, { is_public: !current }); fetchData(); }
  catch (err: any) { toast.error(err.message); }
};

const toggleMaterialActive = async (m: any) => { try { await adminUpdateMaterial(m.id, { is_active: !m.is_active }); fetchData(); } catch (err: any) { toast.error(err.message); } };
const toggleServiceActive = async (s: any) => { try { await adminUpdateService(s.id, { is_active: !s.is_active }); fetchData(); } catch (err: any) { toast.error(err.message); } };
const togglePostActive = async (p: any) => { try { await adminUpdatePost(p.id, { ...p, is_published: !p.is_published }); fetchData(); } catch (err: any) { toast.error(err.message); } };

const handleDeleteMaterial = async (id: number, name: string) => { if (confirm(`Delete ${name}?`)) { try { await adminDeleteMaterial(id); fetchData(); } catch (err: any) { toast.error(err.message); } } };
const handleDeleteService = async (id: number, name: string) => { if (confirm(`Delete ${name}?`)) { try { await adminDeleteService(id); fetchData(); } catch (err: any) { toast.error(err.message); } } };
const handleDeletePost = async (id: number, title: string) => { if (confirm(`Delete ${title}?`)) { try { await adminDeletePost(id); fetchData(); } catch (err: any) { toast.error(err.message); } } };

const handleToggleUserChat = async (id: number, current: boolean) => { try { await adminUpdateUser(id, { can_chat: !current }); fetchUsers(); } catch (err: any) { toast.error(err.message); } };
const handleToggleUserActive = async (id: number, current: boolean) => { if (confirm(`Toggle active?`)) { try { await adminUpdateUser(id, { is_active: !current }); fetchUsers(); } catch (err: any) { toast.error(err.message); } } };
const handleUpdateUserRole = async (id: number, role: string) => { try { await adminUpdateUser(id, { role }); fetchUsers(); } catch (err: any) { toast.error(err.message); } };
const handleResetPassword = async (id: number) => {
  const p = prompt("New password:"); if (p) { try { await adminUpdateUser(id, { password: p }); toast.success("Updated"); } catch (err: any) { toast.error(err.message); } }
};

// Modal Actions
const handleAddNew = () => { closeModals(); showAddModal.value = true; };

function closeModals() {
  showAddModal.value = false;
  showOrderEditModal.value = false;
  adminChatId.value = null;
  editingMaterial.value = null;
  editingService.value = null; 
  editingPost.value = null; 
  editingOrder.value = null;
  Object.assign(matForm, { 
    name_en: "", name_ru: "", name_me: "", name_ua: "", 
    desc_en: "", desc_ru: "", desc_ua: "", desc_me: "", 
    long_desc_en: "", long_desc_ru: "", long_desc_ua: "", long_desc_me: "",
    service_id: null,
    price_per_cm3: 0, price_per_hour: 0, speed_coeff: 1.0, available_colors: [], is_active: true 
  });
  Object.assign(svcForm, { name_en: "", name_ru: "", name_me: "", name_ua: "", desc_en: "", desc_ru: "", desc_ua: "", desc_me: "", tech_type: "", price_per_hour: 0, is_active: true });
  Object.assign(userForm, { email: "", password: "", first_name: "", last_name: "", phone: "" });
  Object.assign(postForm, { slug: "", title_en: "", title_me: "", title_ru: "", title_ua: "", category: "Technology", image_url: "", is_published: true });
  Object.assign(orderForm, { total_price: 0, material_name: "", color_name: "", quantity: 1, first_name: "", last_name: "", email: "", phone: "", shipping_address: "", notes: "", review_text: "", rating: 0 });
}

function addColor() { if (newColor.value) { matForm.available_colors.push(newColor.value); newColor.value = ""; } }
function removeColor(idx: number) { matForm.available_colors.splice(idx, 1); }

async function handleSaveMaterial() { 
  try {
    if (editingMaterial.value) await adminUpdateMaterial(editingMaterial.value.id, matForm);
    else await adminCreateMaterial(matForm);
    closeModals(); fetchData();
  } catch (err: any) { toast.error(err.message); }
}
async function handleSaveService() { 
  try {
    if (editingService.value) await adminUpdateService(editingService.value.id, svcForm);
    else await adminCreateService(svcForm);
    closeModals(); fetchData();
  } catch (err: any) { toast.error(err.message); }
}
async function handleSavePost() { 
  try {
    if (editingPost.value) await adminUpdatePost(editingPost.value.id, postForm);
    else await adminCreatePost(postForm);
    closeModals(); fetchData();
  } catch (err: any) { toast.error(err.message); }
}
async function handleSaveOrder() {
  const order = editingOrder.value;
  if (!order) return;
  
  try {
    await adminUpdateOrder(order.id, orderForm);
    
    // Optimistic local update with safety checks
    if (editingOrder.value && editingOrder.value.id === order.id) {
      editingOrder.value.invoice_amount = orderForm.total_price;
    }
    
    const idx = orders.value.findIndex(o => o.id === order.id);
    if (idx !== -1) {
      orders.value[idx].invoice_amount = orderForm.total_price;
      orders.value[idx].quantity = orderForm.quantity;
    }
    
    closeModals(); 
    toast.success("Order updated");
    
    // Refresh to be sure
    setTimeout(fetchData, 300);
  } catch (err: any) { 
    console.error("Save order error:", err);
    toast.error(err.message || "Failed to save order"); 
  }
}

async function handleSaveUser() { try { await adminCreateUser(userForm); closeModals(); fetchUsers(); } catch (err: any) { toast.error(err.message); } }

// Lifecycle
onMounted(async () => {
  if (!authStore.user || authStore.user.role !== "admin") { router.push("/auth"); return; }
  
  window.addEventListener('admin-edit-order', handleEditOrderEvent);
  window.addEventListener('keydown', handleGlobalEsc);
  
  await loadAdminTranslations();
  fetchData();
  // Ensure materials are loaded for order edit selectors
  adminGetMaterials().then(res => materials.value = res).catch(() => {});
});
</script>
