import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { SetupStepProps } from '../types';
import { useIngredients, useCreateIngredient, useUpdateIngredient, useSoftDeleteIngredient, useBulkAddStock } from '../../../../api/hooks/inventory';
import { useSuppliers } from '../../../../api/hooks/suppliers';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import { UnitOfMeasure, IngredientCategory, ProductionStage } from '../../../../api/types/inventory';
import type { IngredientCreate, IngredientUpdate, StockCreate } from '../../../../api/types/inventory';
import { ESSENTIAL_INGREDIENTS, COMMON_INGREDIENTS, PACKAGING_ITEMS, type IngredientTemplate, templateToIngredientCreate } from '../data/ingredientTemplates';
import { useAutoSaveDraft, useStepDraft, useDeleteStepDraft } from '../../../../api/hooks/onboarding';

const STEP_NAME = 'inventory-setup';

export const InventorySetupStep: React.FC<SetupStepProps> = ({ onUpdate, onComplete, onPrevious, canContinue }) => {
  const { t } = useTranslation();

  // Get tenant ID
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id || '';

  // Fetch ingredients
  const { data: ingredientsData, isLoading } = useIngredients(tenantId);
  const ingredients = ingredientsData || [];

  // Fetch suppliers for stock entry
  const { data: suppliersData } = useSuppliers(tenantId, { limit: 100 }, { enabled: !!tenantId });
  const suppliers = (suppliersData || []).filter(s => s.status === 'active');

  // Mutations
  const createIngredientMutation = useCreateIngredient();
  const updateIngredientMutation = useUpdateIngredient();
  const deleteIngredientMutation = useSoftDeleteIngredient();
  const bulkAddStockMutation = useBulkAddStock();

  // Draft auto-save hooks
  const { data: draftData, isLoading: isLoadingDraft } = useStepDraft(STEP_NAME);
  const { saveDraft, saveDraftImmediately, cancelPendingSave } = useAutoSaveDraft(STEP_NAME, 2000);
  const deleteStepDraft = useDeleteStepDraft();
  const draftRestoredRef = useRef(false);
  const stepCompletedRef = useRef(false); // Track if step has been completed to prevent draft saves after completion

  // Form state
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    category: IngredientCategory.OTHER,
    unit_of_measure: UnitOfMeasure.KILOGRAMS,
    brand: '',
    standard_cost: '',
    low_stock_threshold: '',
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Template state
  const [showTemplates, setShowTemplates] = useState(ingredients.length === 0);
  const [isImporting, setIsImporting] = useState(false);

  // Stock entry state
  const [addingStockForId, setAddingStockForId] = useState<string | null>(null);
  const [stockFormData, setStockFormData] = useState({
    current_quantity: '',
    expiration_date: '',
    supplier_id: '',
    batch_number: '',
    lot_number: '',
  });
  const [stockErrors, setStockErrors] = useState<Record<string, string>>({});

  // Track pending stocks to be submitted in batch (for display and batch submission)
  const [pendingStocks, setPendingStocks] = useState<StockCreate[]>([]);
  // Track stocks display per ingredient (using StockCreate for pending, before API submission)
  const [ingredientStocks, setIngredientStocks] = useState<Record<string, Array<StockCreate & { _tempId: string }>>>({});

  // Restore draft data on mount (only once)
  useEffect(() => {
    if (!isLoadingDraft && draftData?.draft_data && !draftRestoredRef.current) {
      draftRestoredRef.current = true;
      const draft = draftData.draft_data;

      if (draft.pendingStocks && Array.isArray(draft.pendingStocks)) {
        setPendingStocks(draft.pendingStocks);
      }

      if (draft.ingredientStocks && typeof draft.ingredientStocks === 'object') {
        setIngredientStocks(draft.ingredientStocks);
      }

      console.log('✅ Restored inventory-setup draft:', draft);
    }
  }, [isLoadingDraft, draftData]);

  // Auto-save draft when pendingStocks or ingredientStocks change
  useEffect(() => {
    // CRITICAL: Do not save drafts after the step has been completed
    // This prevents overwriting completed status with draft data
    if (stepCompletedRef.current) {
      console.log('⏸️  Skipping draft save - step already completed');
      return;
    }

    // Only save after initial draft restoration
    if (!draftRestoredRef.current) return;

    // Save draft with current stock data
    const draftPayload = {
      pendingStocks,
      ingredientStocks,
    };

    saveDraft(draftPayload);
  }, [pendingStocks, ingredientStocks, saveDraft]);

  // Notify parent when count changes
  useEffect(() => {
    const count = ingredients.length;
    onUpdate?.({
      itemsCount: count,
      canContinue: count >= 3,
    });
  }, [ingredients.length, onUpdate]);

  // Validation
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = t('setup_wizard:inventory.errors.name_required', 'Name is required');
    }

    if (formData.standard_cost && isNaN(Number(formData.standard_cost))) {
      newErrors.standard_cost = t('setup_wizard:inventory.errors.cost_invalid', 'Cost must be a valid number');
    }

    if (formData.low_stock_threshold && isNaN(Number(formData.low_stock_threshold))) {
      newErrors.low_stock_threshold = t('setup_wizard:inventory.errors.threshold_invalid', 'Threshold must be a valid number');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Form handlers
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    try {
      if (editingId) {
        // Update existing ingredient
        await updateIngredientMutation.mutateAsync({
          tenantId,
          ingredientId: editingId,
          updateData: {
            name: formData.name,
            category: formData.category,
            unit_of_measure: formData.unit_of_measure,
            brand: formData.brand || null,
            standard_cost: formData.standard_cost ? Number(formData.standard_cost) : null,
            low_stock_threshold: formData.low_stock_threshold ? Number(formData.low_stock_threshold) : null,
          } as IngredientUpdate,
        });
        setEditingId(null);
      } else {
        // Create new ingredient
        await createIngredientMutation.mutateAsync({
          tenantId,
          ingredientData: {
            name: formData.name,
            category: formData.category,
            unit_of_measure: formData.unit_of_measure,
            brand: formData.brand || undefined,
            standard_cost: formData.standard_cost ? Number(formData.standard_cost) : undefined,
            low_stock_threshold: formData.low_stock_threshold ? Number(formData.low_stock_threshold) : undefined,
          } as IngredientCreate,
        });
      }

      // Reset form
      resetForm();
    } catch (error) {
      console.error('Error saving ingredient:', error);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      category: IngredientCategory.OTHER,
      unit_of_measure: UnitOfMeasure.KILOGRAMS,
      brand: '',
      standard_cost: '',
      low_stock_threshold: '',
    });
    setErrors({});
    setIsAdding(false);
    setEditingId(null);
  };

  const handleEdit = (ingredient: any) => {
    setFormData({
      name: ingredient.name,
      category: (ingredient.category as IngredientCategory) || IngredientCategory.OTHER,
      unit_of_measure: (ingredient.unit_of_measure as UnitOfMeasure) || UnitOfMeasure.UNITS,
      brand: ingredient.brand || '',
      standard_cost: ingredient.standard_cost?.toString() || '',
      low_stock_threshold: ingredient.low_stock_threshold?.toString() || '',
    });
    setEditingId(ingredient.id);
    setIsAdding(true);
  };

  const handleDelete = async (ingredientId: string) => {
    if (!window.confirm(t('setup_wizard:inventory.confirm_delete', 'Are you sure you want to delete this ingredient?'))) {
      return;
    }

    try {
      await deleteIngredientMutation.mutateAsync({ tenantId, ingredientId });
    } catch (error) {
      console.error('Error deleting ingredient:', error);
    }
  };

  // Template import handlers
  const handleImportTemplate = async (template: IngredientTemplate) => {
    try {
      const ingredientData = templateToIngredientCreate(template);
      await createIngredientMutation.mutateAsync({
        tenantId,
        ingredientData,
      });
    } catch (error) {
      console.error('Error importing template:', error);
    }
  };

  const handleImportMultiple = async (templates: IngredientTemplate[]) => {
    setIsImporting(true);
    try {
      for (const template of templates) {
        await handleImportTemplate(template);
      }
      setShowTemplates(false);
    } catch (error) {
      console.error('Error importing templates:', error);
    } finally {
      setIsImporting(false);
    }
  };

  const handleUseTemplate = (template: IngredientTemplate) => {
    const ingredientData = templateToIngredientCreate(template);
    setFormData({
      name: ingredientData.name,
      category: (ingredientData.category as any) || IngredientCategory.OTHER,
      unit_of_measure: (ingredientData.unit_of_measure as UnitOfMeasure) || UnitOfMeasure.UNITS,
      brand: '',
      standard_cost: ingredientData.standard_cost?.toString() || '',
      low_stock_threshold: ingredientData.low_stock_threshold?.toString() || '',
    });
    setIsAdding(true);
    setShowTemplates(false);
  };

  // Stock entry handlers
  const handleAddStockClick = (ingredientId: string) => {
    setAddingStockForId(ingredientId);
    setStockFormData({
      current_quantity: '',
      expiration_date: '',
      supplier_id: suppliers.length === 1 ? suppliers[0].id : '',
      batch_number: '',
      lot_number: '',
    });
    setStockErrors({});
  };

  const handleCancelStock = () => {
    setAddingStockForId(null);
    setStockFormData({
      current_quantity: '',
      expiration_date: '',
      supplier_id: '',
      batch_number: '',
      lot_number: '',
    });
    setStockErrors({});
  };

  const validateStockForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!stockFormData.current_quantity || Number(stockFormData.current_quantity) <= 0) {
      newErrors.current_quantity = t('setup_wizard:inventory.stock_errors.quantity_required', 'Quantity must be greater than zero');
    }

    if (stockFormData.expiration_date) {
      const expDate = new Date(stockFormData.expiration_date);
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      if (expDate < today) {
        newErrors.expiration_date = t('setup_wizard:inventory.stock_errors.expiration_past', 'Expiration date is in the past');
      }

      const threeDaysFromNow = new Date(today);
      threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3);
      if (expDate < threeDaysFromNow) {
        newErrors.expiration_warning = t('setup_wizard:inventory.stock_errors.expiring_soon', 'Warning: This ingredient expires very soon!');
      }
    }

    setStockErrors(newErrors);
    return Object.keys(newErrors).filter(k => k !== 'expiration_warning').length === 0;
  };

  const handleSaveStock = async (addAnother: boolean = false) => {
    if (!addingStockForId || !validateStockForm()) return;

    const stockData: StockCreate = {
      ingredient_id: addingStockForId,
      current_quantity: Number(stockFormData.current_quantity),
      expiration_date: stockFormData.expiration_date || undefined,
      supplier_id: stockFormData.supplier_id || undefined,
      batch_number: stockFormData.batch_number || undefined,
      lot_number: stockFormData.lot_number || undefined,
      production_stage: ProductionStage.RAW_INGREDIENT,
      quality_status: 'good',
    };

    // Generate a temporary ID for display purposes
    const tempId = `temp-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
    const stockWithTempId = { ...stockData, _tempId: tempId };

    // Add to pending stocks for batch submission
    setPendingStocks(prev => [...prev, stockData]);

    // Add to local state for display
    setIngredientStocks(prev => ({
      ...prev,
      [addingStockForId]: [...(prev[addingStockForId] || []), stockWithTempId],
    }));

    if (addAnother) {
      // Reset form for adding another lot
      setStockFormData({
        current_quantity: '',
        expiration_date: '',
        supplier_id: stockFormData.supplier_id, // Keep supplier selected
        batch_number: '',
        lot_number: '',
      });
      setStockErrors({});
    } else {
      handleCancelStock();
    }
  };

  const handleDeleteStock = (ingredientId: string, tempId: string) => {
    // Remove from local display state
    setIngredientStocks(prev => ({
      ...prev,
      [ingredientId]: (prev[ingredientId] || []).filter(s => s._tempId !== tempId),
    }));
    // Remove from pending stocks
    setPendingStocks(prev => prev.filter((s) => {
      // Find and remove the matching stock entry
      const stocksForIngredient = ingredientStocks[ingredientId] || [];
      const stockToRemove = stocksForIngredient.find(st => st._tempId === tempId);
      if (!stockToRemove) return true;
      return s.ingredient_id !== stockToRemove.ingredient_id ||
             s.current_quantity !== stockToRemove.current_quantity ||
             s.batch_number !== stockToRemove.batch_number;
    }));
  };

  // Submit all pending stocks when proceeding to next step
  const handleSubmitPendingStocks = async (): Promise<boolean> => {
    // Cancel any pending auto-save
    cancelPendingSave();

    if (pendingStocks.length === 0) {
      // No pending stocks, but still delete any draft data
      try {
        await deleteStepDraft.mutateAsync(STEP_NAME);
      } catch {
        // Ignore errors when deleting draft
      }
      return true;
    }

    try {
      await bulkAddStockMutation.mutateAsync({
        tenantId,
        stocks: pendingStocks,
      });
      // Clear pending stocks after successful submission
      setPendingStocks([]);
      setIngredientStocks({});

      // Delete draft data after successful submission
      try {
        await deleteStepDraft.mutateAsync(STEP_NAME);
      } catch {
        // Ignore errors when deleting draft
      }

      return true;
    } catch (error) {
      console.error('Error submitting stocks:', error);
      return false;
    }
  };

  const categoryOptions = [
    { value: IngredientCategory.FLOUR, label: t('inventory:category.flour', 'Flour') },
    { value: IngredientCategory.YEAST, label: t('inventory:category.yeast', 'Yeast') },
    { value: IngredientCategory.DAIRY, label: t('inventory:category.dairy', 'Dairy') },
    { value: IngredientCategory.EGGS, label: t('inventory:category.eggs', 'Eggs') },
    { value: IngredientCategory.SUGAR, label: t('inventory:category.sugar', 'Sugar') },
    { value: IngredientCategory.FATS, label: t('inventory:category.fats', 'Fats/Oils') },
    { value: IngredientCategory.SALT, label: t('inventory:category.salt', 'Salt') },
    { value: IngredientCategory.SPICES, label: t('inventory:category.spices', 'Spices') },
    { value: IngredientCategory.ADDITIVES, label: t('inventory:category.additives', 'Additives') },
    { value: IngredientCategory.PACKAGING, label: t('inventory:category.packaging', 'Packaging') },
    { value: IngredientCategory.CLEANING, label: t('inventory:category.cleaning', 'Cleaning') },
    { value: IngredientCategory.OTHER, label: t('inventory:category.other', 'Other') },
  ];

  const unitOptions = [
    { value: UnitOfMeasure.KILOGRAMS, label: t('inventory:unit.kg', 'Kilograms (kg)') },
    { value: UnitOfMeasure.GRAMS, label: t('inventory:unit.g', 'Grams (g)') },
    { value: UnitOfMeasure.LITERS, label: t('inventory:unit.l', 'Liters (l)') },
    { value: UnitOfMeasure.MILLILITERS, label: t('inventory:unit.ml', 'Milliliters (ml)') },
    { value: UnitOfMeasure.UNITS, label: t('inventory:unit.units', 'Units') },
    { value: UnitOfMeasure.PIECES, label: t('inventory:unit.pcs', 'Pieces') },
    { value: UnitOfMeasure.PACKAGES, label: t('inventory:unit.pkg', 'Packages') },
    { value: UnitOfMeasure.BAGS, label: t('inventory:unit.bags', 'Bags') },
    { value: UnitOfMeasure.BOXES, label: t('inventory:unit.boxes', 'Boxes') },
  ];

  return (
    <div className="space-y-6">
      {/* Why This Matters */}
      <div className="bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg p-4">
        <h3 className="font-semibold text-[var(--text-primary)] mb-2 flex items-center gap-2">
          <svg className="w-5 h-5 text-[var(--color-info)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          {t('setup_wizard:why_this_matters', 'Why This Matters')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('setup_wizard:inventory.why', 'Inventory items are the building blocks of your recipes. Once set up, the system will track quantities, alert you when stock is low, and help you calculate recipe costs.')}
        </p>
      </div>

      {/* Quick Start Templates */}
      {showTemplates && (
        <div className="space-y-4 border-2 border-[var(--color-primary)] rounded-lg p-4 bg-gradient-to-br from-[var(--color-primary)]/5 to-transparent">
          <div className="flex items-start justify-between">
            <div>
              <h3 className="font-semibold text-[var(--text-primary)] flex items-center gap-2">
                <svg className="w-5 h-5 text-[var(--color-primary)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                {t('setup_wizard:inventory.quick_start', 'Quick Start')}
              </h3>
              <p className="text-sm text-[var(--text-secondary)] mt-1">
                {t('setup_wizard:inventory.quick_start_desc', 'Import common ingredients to get started quickly')}
              </p>
            </div>
            <button
              type="button"
              onClick={() => setShowTemplates(false)}
              className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] p-1"
              aria-label={t('common:close', 'Close')}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Essential Ingredients */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-sm font-medium text-[var(--text-primary)]">
                {t('setup_wizard:inventory.essential', 'Essential Ingredients')} ({ESSENTIAL_INGREDIENTS.length})
              </h4>
              <button
                type="button"
                onClick={() => handleImportMultiple(ESSENTIAL_INGREDIENTS)}
                disabled={isImporting}
                className="text-xs px-3 py-1 bg-[var(--color-primary)] text-white rounded hover:bg-[var(--color-primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isImporting ? t('common:importing', 'Importing...') : t('setup_wizard:inventory.import_all', 'Import All')}
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
              {ESSENTIAL_INGREDIENTS.map((template) => (
                <button
                  key={template.id}
                  type="button"
                  onClick={() => handleUseTemplate(template)}
                  disabled={isImporting}
                  className="text-left p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:shadow-sm transition-all disabled:opacity-50 disabled:cursor-not-allowed group"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm text-[var(--text-primary)] truncate group-hover:text-[var(--color-primary)]">
                        {template.name}
                      </p>
                      <p className="text-xs text-[var(--text-tertiary)] mt-0.5">
                        {template.unit_of_measure}
                        {template.estimatedCost && ` • $${template.estimatedCost.toFixed(2)}`}
                      </p>
                    </div>
                    <svg className="w-4 h-4 text-[var(--text-tertiary)] group-hover:text-[var(--color-primary)] flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                    </svg>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Common Ingredients */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-sm font-medium text-[var(--text-primary)]">
                {t('setup_wizard:inventory.common', 'Common Ingredients')} ({COMMON_INGREDIENTS.length})
              </h4>
              <button
                type="button"
                onClick={() => handleImportMultiple(COMMON_INGREDIENTS)}
                disabled={isImporting}
                className="text-xs px-3 py-1 bg-[var(--bg-secondary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-primary)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isImporting ? t('common:importing', 'Importing...') : t('setup_wizard:inventory.import_all', 'Import All')}
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
              {COMMON_INGREDIENTS.map((template) => (
                <button
                  key={template.id}
                  type="button"
                  onClick={() => handleUseTemplate(template)}
                  disabled={isImporting}
                  className="text-left p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:shadow-sm transition-all disabled:opacity-50 disabled:cursor-not-allowed group"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm text-[var(--text-primary)] truncate group-hover:text-[var(--color-primary)]">
                        {template.name}
                      </p>
                      <p className="text-xs text-[var(--text-tertiary)] mt-0.5">
                        {template.unit_of_measure}
                        {template.estimatedCost && ` • $${template.estimatedCost.toFixed(2)}`}
                      </p>
                    </div>
                    <svg className="w-4 h-4 text-[var(--text-tertiary)] group-hover:text-[var(--color-primary)] flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                    </svg>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Packaging Items */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-sm font-medium text-[var(--text-primary)]">
                {t('setup_wizard:inventory.packaging', 'Packaging')} ({PACKAGING_ITEMS.length})
              </h4>
              <button
                type="button"
                onClick={() => handleImportMultiple(PACKAGING_ITEMS)}
                disabled={isImporting}
                className="text-xs px-3 py-1 bg-[var(--bg-secondary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-primary)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isImporting ? t('common:importing', 'Importing...') : t('setup_wizard:inventory.import_all', 'Import All')}
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
              {PACKAGING_ITEMS.map((template) => (
                <button
                  key={template.id}
                  type="button"
                  onClick={() => handleUseTemplate(template)}
                  disabled={isImporting}
                  className="text-left p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:shadow-sm transition-all disabled:opacity-50 disabled:cursor-not-allowed group"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm text-[var(--text-primary)] truncate group-hover:text-[var(--color-primary)]">
                        {template.name}
                      </p>
                      <p className="text-xs text-[var(--text-tertiary)] mt-0.5">
                        {template.unit_of_measure}
                        {template.estimatedCost && ` • $${template.estimatedCost.toFixed(2)}`}
                      </p>
                    </div>
                    <svg className="w-4 h-4 text-[var(--text-tertiary)] group-hover:text-[var(--color-primary)] flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                    </svg>
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div className="text-xs text-[var(--text-tertiary)] flex items-center gap-1">
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            {t('setup_wizard:inventory.templates_hint', 'Click any item to customize before adding, or use "Import All" for quick setup')}
          </div>
        </div>
      )}

      {/* Show templates button when hidden */}
      {!showTemplates && ingredients.length > 0 && (
        <button
          type="button"
          onClick={() => setShowTemplates(true)}
          className="w-full p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:bg-[var(--bg-primary)] transition-colors group"
        >
          <div className="flex items-center justify-center gap-2 text-[var(--text-secondary)] group-hover:text-[var(--color-primary)] text-sm">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            <span>{t('setup_wizard:inventory.show_templates', 'Show Quick Start Templates')}</span>
          </div>
        </button>
      )}

      {/* Progress indicator */}
      <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
        <div className="flex items-center gap-2">
          <svg className="w-5 h-5 text-[var(--text-secondary)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
          </svg>
          <span className="text-sm font-medium text-[var(--text-primary)]">
            {t('setup_wizard:inventory.added_count', { count: ingredients.length, defaultValue: '{count} ingredient added' })}
          </span>
        </div>
        {ingredients.length >= 3 ? (
          <div className="flex items-center gap-1 text-xs text-[var(--color-success)]">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
            {t('setup_wizard:inventory.minimum_met', 'Minimum requirement met')}
          </div>
        ) : (
          <div className="text-xs text-[var(--text-secondary)]">
            {t('setup_wizard:inventory.need_more', 'Need {count} more', { count: 3 - ingredients.length })}
          </div>
        )}
      </div>

      {/* Ingredients list */}
      {ingredients.length > 0 && (
        <div className="space-y-2">
          <h4 className="text-sm font-medium text-[var(--text-secondary)]">
            {t('setup_wizard:inventory.your_ingredients', 'Your Ingredients')}
          </h4>
          <div className="space-y-4 max-h-96 overflow-y-auto">
            {ingredients.map((ingredient) => {
              const stocks = ingredientStocks[ingredient.id] || [];
              const isAddingStock = addingStockForId === ingredient.id;

              return (
                <div key={ingredient.id} className="space-y-2">
                  {/* Ingredient Header */}
                  <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--border-primary)] transition-colors">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <h5 className="font-medium text-[var(--text-primary)] truncate">{ingredient.name}</h5>
                        {ingredient.brand && (
                          <span className="text-xs text-[var(--text-tertiary)]">({ingredient.brand})</span>
                        )}
                        {stocks.length > 0 && (
                          <span className="text-xs px-2 py-0.5 bg-[var(--color-success)]/10 text-[var(--color-success)] rounded-full">
                            {stocks.length} {stocks.length === 1 ? 'lot' : 'lots'}
                          </span>
                        )}
                      </div>
                      <div className="flex items-center gap-3 mt-1 text-xs text-[var(--text-secondary)]">
                        <span className="px-2 py-0.5 bg-[var(--bg-primary)] rounded-full">
                          {categoryOptions.find(opt => opt.value === ingredient.category)?.label || ingredient.category}
                        </span>
                        <span>{ingredient.unit_of_measure}</span>
                        {ingredient.standard_cost && (
                          <span className="flex items-center gap-1">
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            ${Number(ingredient.standard_cost).toFixed(2)}
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2 ml-4">
                      <button
                        type="button"
                        onClick={() => handleEdit(ingredient)}
                        className="p-1.5 text-[var(--text-secondary)] hover:text-[var(--color-primary)] hover:bg-[var(--bg-primary)] rounded transition-colors"
                        aria-label={t('common:edit', 'Edit')}
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDelete(ingredient.id)}
                        className="p-1.5 text-[var(--text-secondary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error)]/10 rounded transition-colors"
                        aria-label={t('common:delete', 'Delete')}
                        disabled={deleteIngredientMutation.isPending}
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </div>

                  {/* Stock List - Phase 2 */}
                  {stocks.length > 0 && (
                    <div className="ml-6 space-y-1">
                      {stocks.map((stock) => (
                        <div
                          key={stock._tempId}
                          className="flex items-center justify-between p-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded text-sm"
                        >
                          <div className="flex items-center gap-3 text-xs">
                            <span className="font-medium">{stock.current_quantity} {ingredient.unit_of_measure}</span>
                            {stock.expiration_date && (
                              <span className="flex items-center gap-1 text-[var(--text-secondary)]">
                                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                </svg>
                                Exp: {new Date(stock.expiration_date).toLocaleDateString()}
                              </span>
                            )}
                            {stock.batch_number && (
                              <span className="text-[var(--text-tertiary)]">{t('setup_wizard:inventory.batch_label', 'Batch')}: {stock.batch_number}</span>
                            )}
                          </div>
                          <button
                            type="button"
                            onClick={() => handleDeleteStock(ingredient.id, stock._tempId)}
                            className="p-1 text-[var(--text-secondary)] hover:text-[var(--color-error)] rounded transition-colors"
                            aria-label="Delete lot"
                          >
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Inline Stock Entry Form - Phase 1 & 2 */}
                  {isAddingStock ? (
                    <div className="ml-6 p-4 bg-[var(--color-primary)]/5 border-2 border-[var(--color-primary)] rounded-lg space-y-3">
                      <div className="flex items-center justify-between mb-2">
                        <h5 className="text-sm font-medium text-[var(--text-primary)] flex items-center gap-2">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                          </svg>
                          {t('setup_wizard:inventory.add_stock', 'Add Initial Stock')}
                        </h5>
                        <button
                          type="button"
                          onClick={handleCancelStock}
                          className="text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
                        >
                          {t('common:cancel', 'Cancel')}
                        </button>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        {/* Quantity */}
                        <div>
                          <label className="block text-xs font-medium text-[var(--text-primary)] mb-1">
                            {t('setup_wizard:inventory.quantity', 'Quantity')} ({ingredient.unit_of_measure}) <span className="text-[var(--color-error)]">*</span>
                          </label>
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            value={stockFormData.current_quantity}
                            onChange={(e) => setStockFormData({ ...stockFormData, current_quantity: e.target.value })}
                            className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${stockErrors.current_quantity ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm`}
                            placeholder="25.0"
                          />
                          {stockErrors.current_quantity && (
                            <p className="mt-1 text-xs text-[var(--color-error)]">{stockErrors.current_quantity}</p>
                          )}
                        </div>

                        {/* Expiration Date */}
                        <div>
                          <label className="block text-xs font-medium text-[var(--text-primary)] mb-1">
                            {t('setup_wizard:inventory.expiration_date', 'Expiration Date')}
                          </label>
                          <input
                            type="date"
                            value={stockFormData.expiration_date}
                            onChange={(e) => setStockFormData({ ...stockFormData, expiration_date: e.target.value })}
                            className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${stockErrors.expiration_date ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm`}
                          />
                          {stockErrors.expiration_date && (
                            <p className="mt-1 text-xs text-[var(--color-error)]">{stockErrors.expiration_date}</p>
                          )}
                          {stockErrors.expiration_warning && (
                            <p className="mt-1 text-xs text-[var(--color-warning)] flex items-center gap-1">
                              <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                              </svg>
                              {stockErrors.expiration_warning}
                            </p>
                          )}
                        </div>

                        {/* Supplier */}
                        <div>
                          <label className="block text-xs font-medium text-[var(--text-primary)] mb-1">
                            {t('setup_wizard:inventory.supplier', 'Supplier')}
                          </label>
                          <select
                            value={stockFormData.supplier_id}
                            onChange={(e) => setStockFormData({ ...stockFormData, supplier_id: e.target.value })}
                            className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
                          >
                            <option value="">{t('common:none', 'None')}</option>
                            {suppliers.map((supplier) => (
                              <option key={supplier.id} value={supplier.id}>
                                {supplier.name}
                              </option>
                            ))}
                          </select>
                        </div>

                        {/* Batch Number */}
                        <div>
                          <label className="block text-xs font-medium text-[var(--text-primary)] mb-1">
                            {t('setup_wizard:inventory.batch_number', 'Batch/Lot Number')}
                          </label>
                          <input
                            type="text"
                            value={stockFormData.batch_number}
                            onChange={(e) => setStockFormData({ ...stockFormData, batch_number: e.target.value })}
                            className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
                            placeholder="LOT-2024-11"
                          />
                        </div>
                      </div>

                      {/* Help Text */}
                      <p className="text-xs text-[var(--text-secondary)] flex items-start gap-1">
                        <svg className="w-3 h-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        {t('setup_wizard:inventory.stock_help', 'Expiration tracking helps prevent waste and enables FIFO inventory management')}
                      </p>

                      {/* Action Buttons */}
                      <div className="flex items-center gap-2 pt-2">
                        <button
                          type="button"
                          onClick={() => handleSaveStock(true)}
                          className="px-4 py-2 text-sm bg-[var(--bg-primary)] border border-[var(--border-secondary)] text-[var(--text-primary)] rounded hover:bg-[var(--bg-secondary)] transition-colors"
                        >
                          {t('setup_wizard:inventory.add_another_lot', '+ Add Another Lot')}
                        </button>
                        <button
                          type="button"
                          onClick={() => handleSaveStock(false)}
                          className="px-4 py-2 text-sm bg-[var(--color-primary)] text-white rounded hover:bg-[var(--color-primary-dark)] transition-colors flex items-center gap-1"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                          </svg>
                          {t('common:save', 'Save')}
                        </button>
                      </div>

                      {stockErrors.submit && (
                        <p className="text-xs text-[var(--color-error)]">{stockErrors.submit}</p>
                      )}
                    </div>
                  ) : (
                    /* Add Stock Button */
                    !isAdding && (
                      <div className="ml-6">
                        <button
                          type="button"
                          onClick={() => handleAddStockClick(ingredient.id)}
                          className="text-xs text-[var(--color-primary)] hover:underline flex items-center gap-1"
                        >
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                          </svg>
                          {stocks.length > 0
                            ? t('setup_wizard:inventory.add_another_stock', 'Add Another Stock Lot')
                            : t('setup_wizard:inventory.add_initial_stock', 'Add Initial Stock (Optional)')}
                        </button>
                      </div>
                    )
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Add/Edit form */}
      {isAdding ? (
        <form onSubmit={handleSubmit} className="space-y-4 p-4 border-2 border-[var(--color-primary)] rounded-lg bg-[var(--bg-secondary)]">
          <div className="flex items-center justify-between mb-2">
            <h4 className="font-medium text-[var(--text-primary)]">
              {editingId ? t('setup_wizard:inventory.edit_ingredient', 'Edit Ingredient') : t('setup_wizard:inventory.add_ingredient', 'Add Ingredient')}
            </h4>
            <button
              type="button"
              onClick={resetForm}
              className="text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
            >
              {t('common:cancel', 'Cancel')}
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Name */}
            <div className="md:col-span-2">
              <label htmlFor="ingredient-name" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:inventory.fields.name', 'Ingredient Name')} <span className="text-[var(--color-error)]">*</span>
              </label>
              <input
                id="ingredient-name"
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${errors.name ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]`}
                placeholder={t('setup_wizard:inventory.placeholders.name', 'e.g., Harina 000, Levadura fresca')}
              />
              {errors.name && <p className="mt-1 text-xs text-[var(--color-error)]">{errors.name}</p>}
            </div>

            {/* Category */}
            <div>
              <label htmlFor="category" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:inventory.fields.category', 'Category')} <span className="text-[var(--color-error)]">*</span>
              </label>
              <select
                id="category"
                value={formData.category}
                onChange={(e) => setFormData({ ...formData, category: e.target.value as IngredientCategory })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
              >
                {categoryOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            {/* Unit of Measure */}
            <div>
              <label htmlFor="unit" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:inventory.fields.unit', 'Unit of Measure')} <span className="text-[var(--color-error)]">*</span>
              </label>
              <select
                id="unit"
                value={formData.unit_of_measure}
                onChange={(e) => setFormData({ ...formData, unit_of_measure: e.target.value as UnitOfMeasure })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
              >
                {unitOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            {/* Brand */}
            <div>
              <label htmlFor="brand" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:inventory.fields.brand', 'Brand')}
              </label>
              <input
                id="brand"
                type="text"
                value={formData.brand}
                onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
                placeholder={t('setup_wizard:inventory.placeholders.brand', 'e.g., Molinos Río')}
              />
            </div>

            {/* Standard Cost */}
            <div>
              <label htmlFor="cost" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:inventory.fields.cost', 'Standard Cost')}
              </label>
              <input
                id="cost"
                type="number"
                step="0.01"
                value={formData.standard_cost}
                onChange={(e) => setFormData({ ...formData, standard_cost: e.target.value })}
                className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${errors.standard_cost ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]`}
                placeholder={t('setup_wizard:inventory.placeholders.cost', 'e.g., 150.00')}
              />
              {errors.standard_cost && <p className="mt-1 text-xs text-[var(--color-error)]">{errors.standard_cost}</p>}
            </div>
          </div>

          <div className="flex gap-2 pt-2">
            <button
              type="submit"
              disabled={createIngredientMutation.isPending || updateIngredientMutation.isPending}
              className="px-4 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
            >
              {(createIngredientMutation.isPending || updateIngredientMutation.isPending) ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t('common:saving', 'Saving...')}
                </span>
              ) : editingId ? (
                t('common:update', 'Update')
              ) : (
                t('common:add', 'Add')
              )}
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="px-4 py-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] rounded-lg transition-colors"
            >
              {t('common:cancel', 'Cancel')}
            </button>
          </div>
        </form>
      ) : (
        <button
          type="button"
          onClick={() => setIsAdding(true)}
          className="w-full p-4 border-2 border-dashed border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:bg-[var(--bg-secondary)] transition-colors group"
        >
          <div className="flex items-center justify-center gap-2 text-[var(--text-secondary)] group-hover:text-[var(--color-primary)]">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            <span className="font-medium">
              {ingredients.length === 0
                ? t('setup_wizard:inventory.add_first', 'Add Your First Ingredient')
                : t('setup_wizard:inventory.add_another', 'Add Another Ingredient')}
            </span>
          </div>
        </button>
      )}

      {/* Loading state */}
      {isLoading && ingredients.length === 0 && (
        <div className="text-center py-8">
          <svg className="animate-spin h-8 w-8 text-[var(--color-primary)] mx-auto" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
          </svg>
          <p className="mt-2 text-sm text-[var(--text-secondary)]">
            {t('common:loading', 'Loading...')}
          </p>
        </div>
      )}

      {/* Navigation buttons */}
      {!isAdding && onComplete && (
        <div className="flex items-center justify-between gap-4 pt-6 mt-6 border-t border-[var(--border-secondary)]">
          <div className="flex gap-2">
            <button
              type="button"
              onClick={onPrevious}
              className="px-4 py-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors font-medium"
            >
              ← {t('common:previous', 'Anterior')}
            </button>
          </div>

          <div className="flex items-center gap-3">
            {pendingStocks.length > 0 && (
              <span className="text-sm text-[var(--text-secondary)]">
                {pendingStocks.length} {t('setup_wizard:inventory.pending_stocks', 'stock entries pending')}
              </span>
            )}
            <button
              type="button"
              onClick={async () => {
                const success = await handleSubmitPendingStocks();
                if (success) {
                  // CRITICAL: Mark step as completed BEFORE calling onComplete
                  // This prevents any pending auto-save from overwriting the completion
                  stepCompletedRef.current = true;
                  cancelPendingSave();
                  onComplete();
                }
              }}
              disabled={canContinue === false || bulkAddStockMutation.isPending}
              className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium flex items-center gap-2"
            >
              {bulkAddStockMutation.isPending ? (
                <>
                  <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t('common:saving', 'Saving...')}
                </>
              ) : (
                t('common:next', 'Continuar →')
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
