<template>
  <section :id="embedded ? undefined : 'upload'" :class="[embedded ? '' : 'py-12 sm:py-20 bg-white relative']">
    <div v-if="!embedded" class="absolute inset-0 bg-gradient-glow opacity-50" />
    
    <div :class="[embedded ? '' : 'container mx-auto px-4 relative z-10']">
      <div v-if="!embedded" class="text-center mb-10 sm:mb-12">
        <span class="text-primary font-display text-xs font-bold tracking-[0.2em] uppercase">{{ t("upload.badge") }}</span>
        <h2 class="font-display text-3xl sm:text-4xl lg:text-5xl font-extrabold mt-4 mb-4 tracking-tight">
          {{ t("upload.title") }} <span class="text-primary">{{ t("upload.titleGradient") }}</span>
        </h2>
        <p class="text-foreground/60 max-w-xl mx-auto text-base font-medium">{{ t("upload.description") }}</p>
      </div>

      <div :class="[embedded ? '' : 'max-w-3xl mx-auto space-y-6 sm:space-y-8']">
        <!-- Contact -->
        <div class="grid sm:grid-cols-2 gap-6">
          <div class="space-y-1.5">
            <label for="upload-first-name" class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
              {{ t("upload.firstName") }} *
            </label>
            <input id="upload-first-name" v-model="firstName" type="text" required :placeholder="t('upload.firstName')"
              class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
          </div>
          <div class="space-y-1.5">
            <label for="upload-last-name" class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
              {{ t("upload.lastName") }} *
            </label>
            <input id="upload-last-name" v-model="lastName" type="text" required :placeholder="t('upload.lastName')"
              class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
          </div>
        </div>

        <div class="grid sm:grid-cols-2 gap-6">
          <div class="space-y-1.5">
            <label for="upload-email" class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
              {{ t("upload.email") }} *
            </label>
            <input id="upload-email" v-model="email" type="email" required :placeholder="t('upload.email')"
              class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
          </div>
          <div class="space-y-1.5">
            <label for="upload-phone" class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
              {{ t("upload.phone") }} *
            </label>
            <input id="upload-phone" v-model="phone" type="tel" required :placeholder="t('upload.phone')"
              class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
          </div>
        </div>

        <div class="space-y-1.5">
          <label for="upload-address" class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
            {{ t("upload.shippingAddress") }} *
          </label>
          <textarea id="upload-address" v-model="address" required :placeholder="t('upload.addressPlaceholder')" rows="2"
            class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium resize-none" />
        </div>

        <!-- Account Type Toggle -->
        <div class="space-y-4 p-5 bg-secondary/30 rounded-[2rem] border border-black/[0.02]">
          <h3 class="text-[10px] font-bold uppercase tracking-[0.2em] text-foreground/40 flex items-center gap-2 px-1">
            {{ t("auth.fields.accountType") }}
          </h3>
          <div class="flex p-1 bg-white border border-black/[0.03] rounded-2xl gap-1">
            <button type="button" @click="isCompany = false"
              :class="['flex-1 px-4 py-2.5 rounded-xl text-xs font-bold transition-all', !isCompany ? 'bg-primary text-primary-foreground shadow-lg' : 'text-foreground/40 hover:bg-black/5']">
              {{ t("auth.fields.individual") }}
            </button>
            <button type="button" @click="isCompany = true"
              :class="['flex-1 px-4 py-2.5 rounded-xl text-xs font-bold transition-all', isCompany ? 'bg-primary text-primary-foreground shadow-lg' : 'text-foreground/40 hover:bg-black/5']">
              {{ t("auth.fields.company") }}
            </button>
          </div>
        </div>

        <!-- Company Fields -->
        <Transition enter-active-class="transition duration-300" enter-from-class="opacity-0 -translate-y-4" enter-to-class="opacity-100 translate-y-0">
          <div v-if="isCompany" class="space-y-6 sm:space-y-8 p-6 bg-secondary/20 rounded-[2.5rem] border border-primary/10">
            <div class="grid sm:grid-cols-2 gap-6">
              <div class="space-y-1.5">
                <label class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
                  {{ t("auth.fields.companyName") }} *
                </label>
                <input v-model="companyName" type="text" :required="isCompany" :placeholder="t('auth.fields.companyName')"
                  class="w-full bg-white border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
              </div>
              <div class="space-y-1.5">
                <label class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
                  {{ t("auth.fields.companyPIB") }} *
                </label>
                <input v-model="companyPib" type="text" :required="isCompany" placeholder="PIB / Tax ID"
                  class="w-full bg-white border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
              </div>
            </div>
            <div class="space-y-1.5">
              <label class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
                {{ t("auth.fields.companyAddress") }}
              </label>
              <textarea v-model="companyAddress" rows="2" :placeholder="t('auth.fields.companyAddress')"
                class="w-full bg-white border border-black/[0.03] rounded-2xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium resize-none" />
            </div>
          </div>
        </Transition>

        <!-- Material Selection -->
        <div class="space-y-4 p-5 bg-secondary/30 rounded-[2rem] border border-black/[0.02]">
          <h3 class="text-[10px] font-bold uppercase tracking-[0.2em] text-foreground/40 flex items-center gap-2 px-1">
            {{ t("upload.selectMaterial") }}
          </h3>
          <div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <button
              v-for="m in materials"
              :key="m.id"
              type="button"
              @click="selectedMaterial = String(m.id)"
              :class="[
                'p-4 rounded-2xl border text-left transition-all duration-300',
                selectedMaterial === String(m.id)
                  ? 'bg-white border-primary shadow-lg scale-[1.02] ring-1 ring-primary/20'
                  : 'bg-white/50 border-black/[0.04] hover:border-primary/20 grayscale opacity-70 hover:opacity-100 hover:grayscale-0'
              ]"
            >
              <p class="font-extrabold text-xs mb-0.5 tracking-tight uppercase">{{ m['name_' + locale] || m.name_en }}</p>
              <p class="text-[10px] text-foreground/40 leading-tight font-medium line-clamp-1">{{ m['desc_' + locale] || m.desc_en }}</p>
            </button>
          </div>
        </div>

        <!-- Color Selection (Strict) -->
        <Transition enter-active-class="transition duration-300" enter-from-class="opacity-0 scale-95" enter-to-class="opacity-100 scale-100">
          <div v-if="selectedMaterialColors.length" class="space-y-4 p-5 bg-secondary/30 rounded-[2rem] border border-black/[0.02]">
            <h3 class="text-[10px] font-bold uppercase tracking-[0.2em] text-foreground/40 flex items-center gap-2 px-1">
              {{ t("upload.selectColor") }}
            </h3>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="color in selectedMaterialColors"
                :key="color"
                type="button"
                @click="selectedColor = color"
                :class="[
                  'px-6 py-2.5 rounded-2xl border text-xs font-bold transition-all duration-300 capitalize',
                  selectedColor === color
                    ? 'bg-primary text-primary-foreground border-primary shadow-glow scale-105'
                    : 'bg-white border-black/[0.05] text-foreground/60 hover:border-primary/30 hover:text-primary'
                ]"
              >
                {{ color }}
              </button>
            </div>
          </div>
        </Transition>

        <!-- Quantity & Model Link -->
        <div class="grid sm:grid-cols-5 gap-6">
          <div class="space-y-1.5 sm:col-span-3">
            <label class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
              {{ t("upload.modelLink") }}
            </label>
            <div class="relative group">
              <input v-model="modelLink" type="url" :placeholder="t('upload.modelLinkPlaceholder')"
                class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-2.5 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium" />
            </div>
          </div>
        </div>

        <!-- Notes -->
        <div class="space-y-1.5">
          <label class="flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-foreground/40 ml-1">
            {{ t("upload.notes") }}
          </label>
          <textarea v-model="notes" :placeholder="t('upload.notesPlaceholder')" rows="2"
            class="w-full bg-secondary/50 border border-black/[0.03] rounded-2xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-sm font-medium resize-none" />
        </div>

        <!-- Drop Zone -->
        <div
          @dragover.prevent="isDragging = true"
          @dragleave.prevent="isDragging = false"
          @drop.prevent="handleDrop"
          :class="[
            'relative border border-dashed rounded-[2rem] p-10 text-center transition-all duration-500',
            isDragging ? 'border-primary bg-primary/5 shadow-lg' : 'border-black/10 hover:border-primary/30 hover:bg-secondary/20'
          ]"
        >
          <input type="file" multiple accept=".stl,.obj,.3mf,.step" @change="handleFileSelect"
            class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
          <div class="flex flex-col items-center gap-3">
            <div :class="['w-14 h-14 rounded-2xl flex items-center justify-center transition-all duration-500',
              isDragging ? 'bg-primary text-primary-foreground scale-110' : 'bg-primary/5 text-primary']">
              <Upload class="w-7 h-7" />
            </div>
            <div>
              <p class="font-display text-lg font-extrabold tracking-tight mb-1">
                {{ isDragging ? t("upload.dropzoneActive") : t("upload.dropzone") }}
              </p>
              <p class="text-xs font-medium text-foreground/40">
                {{ t("common.or") }} <span class="text-primary underline cursor-pointer">{{ t("upload.browse") }}</span>
              </p>
            </div>
          </div>
        </div>


        <!-- File list -->
        <div v-if="files.length" class="space-y-3">
          <h3 class="font-display text-lg font-semibold mb-4">{{ t("upload.uploadedFiles") }} ({{ files.length }})</h3>
          <div v-for="file in files" :key="file.id"
            class="flex items-center gap-4 p-4 bg-gradient-card rounded-xl border border-border/50 hover:border-primary/30 transition-colors">
            <div class="w-24 h-24 bg-primary/5 rounded-xl border border-black/[0.05] flex items-center justify-center relative overflow-hidden shrink-0">
              <StlViewer v-if="file.name.toLowerCase().endsWith('.stl') && file.file" :file="file.file" :color="selectedColor" />
              <FileBox v-else class="w-10 h-10 text-primary opacity-50" />
            </div>
            <div class="flex-1 min-w-0">
              <div class="flex items-center gap-2">
                <p class="font-medium truncate">{{ file.name }}</p>
                <div v-if="file.isUploading" class="w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
              </div>
              <div class="flex items-center gap-2 text-sm text-muted-foreground">
                <div v-if="file.printTime || file.filamentG || file.dimensions" class="flex flex-wrap gap-2 mt-2">
                  <div v-if="file.dimensions" class="flex items-center gap-1 bg-primary/10 text-primary px-2 py-0.5 rounded-full text-[10px] font-bold">
                    <div class="w-1 h-1 rounded-full bg-current" />
                    {{ file.dimensions }}
                  </div>
                  <div v-if="file.printTime" class="flex items-center gap-1 bg-secondary text-foreground/60 px-2 py-0.5 rounded-full text-[10px] font-bold">
                    <div class="w-1 h-1 rounded-full bg-current" />
                    {{ file.printTime }}
                  </div>
                  <div v-if="file.filamentG" class="flex items-center gap-1 bg-secondary text-foreground/60 px-2 py-0.5 rounded-full text-[10px] font-bold">
                    <div class="w-1 h-1 rounded-full bg-current" />
                    {{ file.filamentG.toFixed(1) }}g
                  </div>
                </div>
                <span>{{ file.type }} • {{ formatFileSize(file.size) }}</span>
                <span v-if="file.basePrice" class="font-semibold text-primary ml-2 bg-primary/10 px-2 py-0.5 rounded-md">
                  ~{{ (file.basePrice * file.quantity).toFixed(2) }} EUR
                </span>
              </div>
              <div v-if="SHOW_ADVANCED_METRICS && file.printTime" class="flex gap-3 text-xs text-muted-foreground mt-0.5 opacity-80">
                <span v-if="file.dimensions">📏 {{ file.dimensions }}</span>
                <span v-if="file.printTime">⏱️ {{ file.printTime }}</span>
                <span v-if="file.filamentG">⚖️ {{ file.filamentG.toFixed(1) }}g</span>
              </div>
            </div>
            <!-- Per-file quantity control -->
            <div class="flex items-center gap-1 bg-card/50 border border-border/50 rounded-lg p-1">
              <button type="button" @click.prevent="file.quantity > 1 && file.quantity--" class="w-8 h-8 rounded-md flex items-center justify-center hover:bg-muted text-muted-foreground transition-colors">-</button>
              <input type="number" v-model.number="file.quantity" min="1" step="1" class="w-12 text-center bg-transparent border-none text-sm font-medium focus:ring-0 [&::-webkit-inner-spin-button]:appearance-none" />
              <button type="button" @click.prevent="file.quantity++" class="w-8 h-8 rounded-md flex items-center justify-center hover:bg-muted text-muted-foreground transition-colors">+</button>
            </div>
            <div class="flex items-center gap-2">
              <div class="w-8 h-8 bg-green-500/10 rounded-full flex items-center justify-center">
                <Check class="w-4 h-4 text-green-500" />
              </div>
              <button @click="removeFile(file.id)"
                class="w-8 h-8 hover:bg-destructive/10 rounded-full flex items-center justify-center transition-colors group">
                <X class="w-4 h-4 text-muted-foreground group-hover:text-destructive" />
              </button>
            </div>
          </div>
        </div>

        <!-- Portfolio consent -->
        <div class="flex items-start gap-4 p-4 mt-6 bg-primary/5 border border-primary/20 rounded-2xl cursor-pointer hover:bg-primary/10 transition-all active:scale-[0.99] group"
          @click="allowPortfolio = !allowPortfolio">
          <div :class="['mt-0.5 w-5 h-5 rounded border flex items-center justify-center transition-all',
            allowPortfolio ? 'bg-primary border-primary' : 'bg-background border-border group-hover:border-primary/50']">
            <Check v-if="allowPortfolio" class="w-3.5 h-3.5 text-primary-foreground" />
          </div>
          <div class="flex-1 space-y-1">
            <p class="text-sm font-medium leading-none">{{ t("upload.allowPortfolio") }}</p>
            <p class="text-xs text-muted-foreground leading-relaxed">{{ t("upload.allowPortfolioDesc") }}</p>
          </div>
          <ShieldCheck :class="['w-5 h-5 transition-colors', allowPortfolio ? 'text-primary' : 'text-muted-foreground/30']" />
        </div>

        <!-- Nuances consent (Mandatory) -->
        <div class="flex items-start gap-4 p-4 mt-3 bg-secondary/30 border border-black/[0.03] rounded-2xl cursor-pointer hover:bg-secondary/50 transition-all active:scale-[0.99] group"
          @click="agreeToNuances = !agreeToNuances">
          <div :class="['mt-0.5 w-5 h-5 rounded border flex items-center justify-center transition-all',
            agreeToNuances ? 'bg-primary border-primary' : 'bg-background border-border group-hover:border-primary/50']">
            <Check v-if="agreeToNuances" class="w-3.5 h-3.5 text-primary-foreground" />
          </div>
          <div class="flex-1">
            <p class="text-sm font-medium leading-relaxed">
              {{ t("upload.agreeToNuances") }} 
              <RouterLink 
                :to="{ name: 'nuances', params: { lang: locale } }" 
                target="_blank" 
                class="text-primary underline hover:text-primary/80 transition-colors"
                @click.stop
              >
                {{ t("upload.nuancesLink") }}
              </RouterLink>
            </p>
          </div>
          <FileText :class="['w-5 h-5 transition-colors', agreeToNuances ? 'text-primary' : 'text-muted-foreground/30']" />
        </div>

        <!-- Estimate -->
        <Transition enter-active-class="transition duration-300" enter-from-class="opacity-0 translate-y-2" enter-to-class="opacity-100 translate-y-0">
          <div v-if="estimatedPrice !== null"
            class="p-6 bg-gradient-to-br from-primary/20 via-primary/5 to-background border border-primary/30 rounded-2xl flex items-center justify-between">
            <div>
              <p class="text-[10px] font-bold uppercase tracking-widest text-primary/80 mb-1">{{ t("upload.estimatedTotal") }}</p>
              <p class="text-xs text-muted-foreground">{{ t("upload.priceDisclaimer") }}</p>
            </div>
            <div class="text-right">
              <span class="text-3xl font-display font-bold text-primary">{{ estimatedPrice }}</span>
              <span class="text-xs font-bold text-primary ml-1 uppercase">EUR</span>
              <p class="text-[9px] text-muted-foreground mt-1 opacity-60">incl. 21% PDV</p>
            </div>
          </div>
        </Transition>

        <Button variant="hero" class="w-full mt-8 shadow-lg hover:shadow-primary/20"
          :disabled="!isFormValid || isSubmitting" @click="handleSubmit">
          <div v-if="isSubmitting" class="flex items-center gap-2">
            <Loader2 class="w-5 h-5 animate-spin" />{{ t("upload.submitting") }}
          </div>
          <span v-else>{{ t("upload.continue") }}</span>
        </Button>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
const props = defineProps<{
  embedded?: boolean;
}>();

const emit = defineEmits<{
  (e: 'success'): void;
}>();

import { ref, computed, watch, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { toast } from "vue-sonner";
import { Upload, FileBox, X, Check, Link as LinkIcon, MapPin, User, Phone, Mail, Loader2, ShieldCheck, Hash, FileText } from "lucide-vue-next";
import Button from "./ui/button.vue";
import { defineAsyncComponent } from "vue";
const StlViewer = defineAsyncComponent(() => import("@/components/StlViewer.vue"));
import { submitOrder, getCurrentUser, getMaterials, getPriceEstimate, uploadFilesToServer } from "@/lib/api";

interface UploadedFile { id: string; dbId?: number; name: string; size: number; type: string; file?: File; quantity: number; basePrice?: number; isUploading?: boolean; printTime?: string; filamentG?: number; dimensions?: string; }

// --- CONFIGURATION ---
// Set to false to hide the hardcore slicing data (time and weight) from the end-user
const SHOW_ADVANCED_METRICS = true;

const { t, locale } = useI18n();
const files = ref<UploadedFile[]>([]);
const isDragging = ref(false);
const isSubmitting = ref(false);
const modelLink = ref("");
const address = ref("");
const firstName = ref("");
const lastName = ref("");
const phone = ref("");
const email = ref("");
const isCompany = ref(false);
const companyName = ref("");
const companyPib = ref("");
const companyAddress = ref("");
const allowPortfolio = ref(false);
const agreeToNuances = ref(false);
const materials = ref<any[]>([]);
const selectedMaterial = ref("1");
const selectedColor = ref("");
const selectedMaterialColors = computed(() => {
  const mat = materials.value.find(m => String(m.id) === selectedMaterial.value);
  return mat?.available_colors || [];
});

watch(selectedMaterial, (newVal) => {
  const mat = materials.value.find(m => String(m.id) === newVal);
  if (mat?.available_colors?.length) {
    selectedColor.value = mat.available_colors[0];
  } else {
    selectedColor.value = "";
  }
});
const estimatedPrice = computed(() => {
  if (files.value.length === 0) return null;
  const total = files.value.reduce((acc, f) => acc + ((f.basePrice || 0) * f.quantity), 0);
  return parseFloat(total.toFixed(2));
});
const notes = ref("");

onMounted(async () => {
  try {
    const materialData = await getMaterials();
    materials.value = materialData;
    if (materialData.length > 0) selectedMaterial.value = String(materialData[0].id);
    const token = localStorage.getItem("token");
    if (token) {
      const user = await getCurrentUser();
      if (user) {
        firstName.value = user.first_name ?? "";
        lastName.value = user.last_name ?? "";
        phone.value = user.phone ?? "";
        email.value = user.email ?? "";
        address.value = user.shipping_address ?? "";
        isCompany.value = user.is_company ?? false;
        companyName.value = user.company_name ?? "";
        companyPib.value = user.company_pib ?? "";
        companyAddress.value = user.company_address ?? "";
      }
    }
  } catch (e) { console.error("Failed to load initial data:", e); }
});

watch([() => files.value.length, selectedMaterial, modelLink], async () => {
  if ((files.value.length > 0) && selectedMaterial.value) {
    try {
      const res = await getPriceEstimate({
        material_id: parseInt(selectedMaterial.value),
        file_sizes: files.value.map(f => f.size),
        file_quantities: files.value.map(f => 1), // Only get base unit cost
      });
      // Assign individual prices to files for local quantity multiplication
      if (res.file_prices && Array.isArray(res.file_prices)) {
        files.value.forEach((f, i) => {
          f.basePrice = res.file_prices[i];
        });
        // Force reactivity update
        files.value = [...files.value];
      }
    } catch { /* silent */ }
  }
});

const isFormValid = computed(() =>
  firstName.value.trim() !== "" && lastName.value.trim() !== "" &&
  phone.value.trim() !== "" && email.value.trim() !== "" &&
  address.value.trim() !== "" && selectedMaterial.value !== "" &&
  agreeToNuances.value &&
  (files.value.length > 0 || modelLink.value.trim() !== "") &&
  (!isCompany.value || (companyName.value.trim() !== "" && companyPib.value.trim() !== ""))
);

async function addFiles(rawFiles: File[]) {
  const valid = rawFiles.filter(f => /\.(stl|obj|3mf|step)$/i.test(f.name));
  
  const newFiles: UploadedFile[] = valid.map(f => ({
    id: Math.random().toString(36).substring(7),
    name: f.name,
    size: f.size,
    type: f.name.split(".").pop()?.toUpperCase() ?? "UNKNOWN",
    file: f,
    quantity: 1,
    basePrice: 0,
    isUploading: true,
  }));
  
  files.value.push(...newFiles);
  
  if (newFiles.length > 0) {
    try {
      const fd = new FormData();
      newFiles.forEach(f => {
        if (f.file) fd.append("files", f.file);
      });
      const res = await uploadFilesToServer(fd);
      
      if (res.uploaded) {
        res.uploaded.forEach((u: any, idx: number) => {
          newFiles[idx].dbId = u.id;
          newFiles[idx].isUploading = false;
          if (u.print_time) newFiles[idx].printTime = u.print_time;
          if (u.filament_g) newFiles[idx].filamentG = u.filament_g;
          if (u.dimensions) newFiles[idx].dimensions = u.dimensions;
        });
      }
    } catch (err) {
      console.error("Failed to upload files initially", err);
      newFiles.forEach(f => f.isUploading = false);
    }
    // Deep reactivity trigger
    files.value = [...files.value];
  }
}
function handleDrop(e: DragEvent) { isDragging.value = false; addFiles(Array.from(e.dataTransfer?.files ?? [])); }

async function handleFileSelect(e: Event) { addFiles(Array.from((e.target as HTMLInputElement).files ?? [])); }
function removeFile(id: string) { files.value = files.value.filter(f => f.id !== id); }
function formatFileSize(bytes: number) {
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
  return (bytes / 1048576).toFixed(1) + " MB";
}

async function handleSubmit() {
  if (!isFormValid.value) return;
  isSubmitting.value = true;
  const fd = new FormData();
  fd.append("first_name", firstName.value);
  fd.append("last_name", lastName.value);
  fd.append("phone", phone.value);
  fd.append("email", email.value);
  fd.append("shipping_address", address.value);
  fd.append("model_link", modelLink.value);
  fd.append("allow_portfolio", String(allowPortfolio.value));
  fd.append("notes", notes.value);
  fd.append("material_id", selectedMaterial.value);
  if (selectedColor.value) fd.append("color_name", selectedColor.value);
  fd.append("is_company", String(isCompany.value));
  if (isCompany.value) {
    fd.append("company_name", companyName.value);
    fd.append("company_pib", companyPib.value);
    fd.append("company_address", companyAddress.value);
  }
  
  const uploadedFiles = files.value.filter(f => f.dbId);
  fd.append("file_ids", JSON.stringify(uploadedFiles.map(f => f.dbId)));
  fd.append("file_quantities", JSON.stringify(uploadedFiles.map(f => f.quantity)));
  try {
    await submitOrder(fd);
    toast.success(t("upload.success"));
    files.value = []; firstName.value = ""; lastName.value = ""; phone.value = "";
    email.value = ""; address.value = ""; modelLink.value = "";
    allowPortfolio.value = false;
    agreeToNuances.value = false;
    notes.value = "";
    emit('success');
  } catch (err: any) {
    toast.error(err.message || t("upload.error"));
  } finally {
    isSubmitting.value = false;
  }
}
</script>
