/**
 * EditItem Page Tests
 *
 * Tests for the item editing form including loading existing data,
 * image management, authorization, and form submission.
 */

import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router';
import { vi, type MockedFunction } from 'vitest';
import EditItem from '../../pages/EditItem';
import { useAuth } from '../../contexts/AuthContext';
import { itemAPI, rentalAPI, addressAPI, userAPI } from '../../services/api';
import { uploadImagesWithVariants, getImageUrl } from '../../services/uploadService';

// Mock FileReader globally
class MockFileReader {
  result: string | null = null;
  onloadend: (() => void) | null = null;

  readAsDataURL() {
    this.result = 'data:image/jpeg;base64,mockbase64data';
    // Call onloadend synchronously (use Promise.resolve to ensure it's after microtask queue)
    Promise.resolve().then(() => {
      if (this.onloadend) {
        this.onloadend();
      }
    });
  }
}

// Replace global FileReader
vi.stubGlobal('FileReader', MockFileReader);

// Mock scrollIntoView which doesn't exist in jsdom
Element.prototype.scrollIntoView = vi.fn();

// Mock dependencies
vi.mock('../../contexts/AuthContext');
vi.mock('../../services/api', () => ({
  itemAPI: {
    getItem: vi.fn(),
    updateItem: vi.fn(),
    getItems: vi.fn(),
  },
  rentalAPI: {
    getListings: vi.fn(),
  },
  addressAPI: {
    getAddresses: vi.fn(),
  },
  userAPI: {
    updateAvailability: vi.fn(),
  },
}));
vi.mock('../../services/uploadService', () => ({
  uploadImagesWithVariants: vi.fn(),
  getImageUrl: vi.fn(),
}));

// Mock child components
vi.mock('../../components/ImageUpload', () => ({
  default: ({ imageFiles, imagePreviews, onImageChange, onRemoveImage }: any) => (
    <div data-testid="image-upload">
      <input
        type="file"
        data-testid="image-input"
        onChange={onImageChange}
        multiple
        accept="image/*"
      />
      {imagePreviews.map((preview: string, index: number) => (
        <div key={index} data-testid={`image-preview-${index}`}>
          <img src={preview} alt={`Preview ${index}`} />
          <button
            data-testid={`remove-image-${index}`}
            onClick={() => onRemoveImage(index)}
          >
            Remove
          </button>
        </div>
      ))}
      <span data-testid="preview-count">{imagePreviews.length}</span>
      <span data-testid="new-file-count">{imageFiles.length}</span>
    </div>
  ),
}));

vi.mock('../../components/ItemInformation', () => ({
  default: ({ name, description, onChange }: any) => (
    <div data-testid="item-information">
      <input
        id="name"
        name="name"
        value={name}
        onChange={onChange}
        data-testid="item-name"
        placeholder="Item name"
      />
      <textarea
        name="description"
        value={description}
        onChange={onChange}
        data-testid="item-description"
        placeholder="Description"
      />
    </div>
  ),
}));

vi.mock('../../components/LocationForm', () => ({
  default: ({
    data,
    userAddresses,
    selectedAddressId,
    addressesLoading,
    onChange,
    onAddressSelect,
    formatAddressDisplay,
  }: any) => (
    <div data-testid="location-form">
      {addressesLoading ? (
        <span data-testid="addresses-loading">Loading addresses...</span>
      ) : (
        <>
          {userAddresses.length > 0 && (
            <select
              data-testid="address-select"
              value={selectedAddressId}
              onChange={(e) => onAddressSelect(e.target.value)}
            >
              <option value="">Select an address</option>
              {userAddresses.map((addr: any) => (
                <option key={addr.id} value={addr.id}>
                  {formatAddressDisplay(addr)}
                </option>
              ))}
              <option value="new">Enter new address</option>
            </select>
          )}
          <input
            id="address1"
            name="address1"
            value={data.address1}
            onChange={onChange}
            data-testid="address1"
            placeholder="Address"
          />
          <input
            id="city"
            name="city"
            value={data.city}
            onChange={onChange}
            data-testid="city"
            placeholder="City"
          />
          <input
            id="state"
            name="state"
            value={data.state}
            onChange={onChange}
            data-testid="state"
            placeholder="State"
          />
          <input
            id="zipCode"
            name="zipCode"
            value={data.zipCode}
            onChange={onChange}
            data-testid="zipCode"
            placeholder="ZIP Code"
          />
        </>
      )}
    </div>
  ),
}));

vi.mock('../../components/AvailabilitySettings', () => ({
  default: ({ data }: any) => (
    <div data-testid="availability-settings">
      <span data-testid="available-after">{data.generalAvailableAfter}</span>
      <span data-testid="available-before">{data.generalAvailableBefore}</span>
    </div>
  ),
}));

vi.mock('../../components/PricingForm', () => ({
  default: ({
    pricePerHour,
    pricePerDay,
    pricePerWeek,
    pricePerMonth,
    replacementCost,
    showAdvancedPricing,
    onChange,
  }: any) => (
    <div data-testid="pricing-form">
      <input
        name="pricePerHour"
        type="number"
        value={pricePerHour}
        onChange={onChange}
        data-testid="price-per-hour"
        placeholder="Price per hour"
      />
      <input
        name="pricePerDay"
        type="number"
        value={pricePerDay}
        onChange={onChange}
        data-testid="price-per-day"
        placeholder="Price per day"
      />
      <input
        name="pricePerWeek"
        type="number"
        value={pricePerWeek}
        onChange={onChange}
        data-testid="price-per-week"
        placeholder="Price per week"
      />
      <input
        name="pricePerMonth"
        type="number"
        value={pricePerMonth}
        onChange={onChange}
        data-testid="price-per-month"
        placeholder="Price per month"
      />
      <input
        id="replacementCost"
        name="replacementCost"
        type="number"
        value={replacementCost}
        onChange={onChange}
        data-testid="replacement-cost"
        placeholder="Replacement cost"
      />
      <span data-testid="advanced-visible">{showAdvancedPricing ? 'yes' : 'no'}</span>
    </div>
  ),
}));

vi.mock('../../components/RulesForm', () => ({
  default: ({ rules, onChange }: any) => (
    <div data-testid="rules-form">
      <textarea
        name="rules"
        value={rules}
        onChange={onChange}
        data-testid="rules-input"
        placeholder="Rules"
      />
    </div>
  ),
}));

const mockNavigate = vi.fn();
vi.mock('react-router', async () => {
  const actual = await vi.importActual('react-router');
  return {
    ...actual,
    useNavigate: () => mockNavigate,
  };
});

const mockedUseAuth = useAuth as MockedFunction<typeof useAuth>;
const mockedGetItem = itemAPI.getItem as MockedFunction<typeof itemAPI.getItem>;
const mockedUpdateItem = itemAPI.updateItem as MockedFunction<typeof itemAPI.updateItem>;
const mockedGetItems = itemAPI.getItems as MockedFunction<typeof itemAPI.getItems>;
const mockedGetListings = rentalAPI.getListings as MockedFunction<typeof rentalAPI.getListings>;
const mockedGetAddresses = addressAPI.getAddresses as MockedFunction<typeof addressAPI.getAddresses>;
const mockedUpdateAvailability = userAPI.updateAvailability as MockedFunction<typeof userAPI.updateAvailability>;
const mockedUploadImagesWithVariants = uploadImagesWithVariants as MockedFunction<typeof uploadImagesWithVariants>;
const mockedGetImageUrl = getImageUrl as MockedFunction<typeof getImageUrl>;

// Helper to render with Router and route params
const renderWithRouter = (itemId: string = 'item-123') => {
  return render(
    <MemoryRouter initialEntries={[`/items/${itemId}/edit`]}>
      <Routes>
        <Route path="/items/:id/edit" element={<EditItem />} />
      </Routes>
    </MemoryRouter>
  );
};

const mockUser = {
  id: 'user-123',
  email: 'test@example.com',
  firstName: 'John',
  lastName: 'Doe',
  isVerified: true,
};

const mockItem = {
  id: 'item-123',
  name: 'Test Camera',
  description: 'A nice camera for rent',
  pricePerHour: null,
  pricePerDay: 50,
  pricePerWeek: null,
  pricePerMonth: null,
  replacementCost: 500,
  address1: '123 Main St',
  address2: '',
  city: 'New York',
  state: 'NY',
  zipCode: '10001',
  country: 'US',
  latitude: 40.7128,
  longitude: -74.006,
  rules: 'Handle with care',
  imageFilenames: ['items/existing-image.jpg'],
  ownerId: 'user-123',
  availableAfter: '09:00',
  availableBefore: '18:00',
  specifyTimesPerDay: false,
  weeklyTimes: {
    sunday: { availableAfter: '09:00', availableBefore: '18:00' },
    monday: { availableAfter: '09:00', availableBefore: '18:00' },
    tuesday: { availableAfter: '09:00', availableBefore: '18:00' },
    wednesday: { availableAfter: '09:00', availableBefore: '18:00' },
    thursday: { availableAfter: '09:00', availableBefore: '18:00' },
    friday: { availableAfter: '09:00', availableBefore: '18:00' },
    saturday: { availableAfter: '09:00', availableBefore: '18:00' },
  },
};

const mockAddress = {
  id: 'addr-1',
  address1: '456 Oak Ave',
  address2: '',
  city: 'Boston',
  state: 'MA',
  zipCode: '02101',
  country: 'US',
  latitude: 42.3601,
  longitude: -71.0589,
};

describe('EditItem', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedUseAuth.mockReturnValue({
      user: mockUser,
      isAuthenticated: true,
      loading: false,
      checkAuth: vi.fn(),
      login: vi.fn(),
      register: vi.fn(),
      logout: vi.fn(),
      googleLogin: vi.fn(),
      openAuthModal: vi.fn(),
      closeAuthModal: vi.fn(),
      setAuthModalMode: vi.fn(),
      isAuthModalOpen: false,
      authModalMode: 'login',
      updateUser: vi.fn(),
    } as any);
    mockedGetItem.mockResolvedValue({ data: mockItem });
    mockedGetListings.mockResolvedValue({ data: [] });
    mockedGetAddresses.mockResolvedValue({ data: [] });
    mockedGetItems.mockResolvedValue({ data: { items: [mockItem] } });
    mockedUpdateItem.mockResolvedValue({ data: mockItem });
    mockedUpdateAvailability.mockResolvedValue({ data: {} });
    mockedUploadImagesWithVariants.mockResolvedValue([
      { baseKey: 'items/new-upload.jpg' },
    ]);
    mockedGetImageUrl.mockImplementation((key: string) => `https://s3.amazonaws.com/${key}`);
  });

  describe('Loading State', () => {
    it('shows loading spinner while fetching item', async () => {
      mockedGetItem.mockImplementation(() => new Promise(() => {})); // Never resolves

      renderWithRouter();

      expect(screen.getByRole('status')).toBeInTheDocument();
      expect(screen.getByText('Loading...')).toBeInTheDocument();
    });

    it('fetches item data on mount', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(mockedGetItem).toHaveBeenCalledWith('item-123');
      });
    });

    it('fetches accepted rentals on mount', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(mockedGetListings).toHaveBeenCalled();
      });
    });

    it('fetches user addresses on mount', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(mockedGetAddresses).toHaveBeenCalled();
      });
    });
  });

  describe('Authorization', () => {
    it('shows error when user is not the owner', async () => {
      mockedGetItem.mockResolvedValue({
        data: { ...mockItem, ownerId: 'different-user' },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent(
          'You are not authorized to edit this item'
        );
      });
    });

    it('allows owner to edit their item', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByText('Edit Listing')).toBeInTheDocument();
      });

      expect(screen.queryByText('not authorized')).not.toBeInTheDocument();
    });
  });

  describe('Form Population', () => {
    it('populates form with existing item data', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      expect(screen.getByTestId('item-description')).toHaveValue('A nice camera for rent');
      expect(screen.getByTestId('address1')).toHaveValue('123 Main St');
      expect(screen.getByTestId('city')).toHaveValue('New York');
      expect(screen.getByTestId('state')).toHaveValue('NY');
      expect(screen.getByTestId('zipCode')).toHaveValue('10001');
      expect(screen.getByTestId('price-per-day')).toHaveValue(50);
      expect(screen.getByTestId('replacement-cost')).toHaveValue(500);
      expect(screen.getByTestId('rules-input')).toHaveValue('Handle with care');
    });

    it('displays existing images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('preview-count')).toHaveTextContent('1');
      });
    });

    it('populates availability settings from item', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('available-after')).toHaveTextContent('09:00');
        expect(screen.getByTestId('available-before')).toHaveTextContent('18:00');
      });
    });

    it('auto-expands advanced pricing when multiple tiers set', async () => {
      mockedGetItem.mockResolvedValue({
        data: {
          ...mockItem,
          pricePerHour: 10,
          pricePerDay: 50,
          pricePerWeek: 200,
        },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('advanced-visible')).toHaveTextContent('yes');
      });
    });
  });

  describe('Image Management', () => {
    it('allows adding new images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('image-upload')).toBeInTheDocument();
      });

      const file = new File(['test'], 'new-image.jpg', { type: 'image/jpeg' });
      const input = screen.getByTestId('image-input');

      fireEvent.change(input, { target: { files: [file] } });

      await waitFor(() => {
        expect(screen.getByTestId('new-file-count')).toHaveTextContent('1');
      });
    });

    it('allows removing existing images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('preview-count')).toHaveTextContent('1');
      });

      fireEvent.click(screen.getByTestId('remove-image-0'));

      await waitFor(() => {
        expect(screen.getByTestId('preview-count')).toHaveTextContent('0');
      });
    });

    it('allows removing new images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('image-upload')).toBeInTheDocument();
      });

      // Add a new image first
      const file = new File(['test'], 'new-image.jpg', { type: 'image/jpeg' });
      const input = screen.getByTestId('image-input');

      fireEvent.change(input, { target: { files: [file] } });

      await waitFor(() => {
        // Should have 1 existing + 1 new = 2 total previews
        expect(screen.getByTestId('preview-count')).toHaveTextContent('2');
      });

      // Remove the new image (index 1)
      fireEvent.click(screen.getByTestId('remove-image-1'));

      await waitFor(() => {
        expect(screen.getByTestId('preview-count')).toHaveTextContent('1');
      });
    });
  });

  describe('Form Validation', () => {
    it('shows error when submitting with no images', async () => {
      mockedGetItem.mockResolvedValue({
        data: { ...mockItem, imageFilenames: [] },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByText('Edit Listing')).toBeInTheDocument();
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent(
          'At least one image is required'
        );
      });
    });

    it('shows error when name is empty', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      // Clear the name
      fireEvent.change(screen.getByTestId('item-name'), {
        target: { value: '' },
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Item name is required');
      });
    });

    it('shows error when address is empty', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      // Clear the address
      fireEvent.change(screen.getByTestId('address1'), {
        target: { value: '' },
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Address is required');
      });
    });

    it('shows error when replacement cost is empty', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      // Clear replacement cost
      fireEvent.change(screen.getByTestId('replacement-cost'), {
        target: { value: '' },
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Replacement cost is required');
      });
    });
  });

  describe('Successful Submission', () => {
    it('submits form with existing images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(mockedUpdateItem).toHaveBeenCalledWith(
          'item-123',
          expect.objectContaining({
            name: 'Test Camera',
            imageFilenames: ['items/existing-image.jpg'],
          })
        );
      });
    });

    it('submits form with new and existing images', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      // Add a new image
      const file = new File(['test'], 'new-image.jpg', { type: 'image/jpeg' });
      const input = screen.getByTestId('image-input');

      fireEvent.change(input, { target: { files: [file] } });

      await waitFor(() => {
        expect(screen.getByTestId('new-file-count')).toHaveTextContent('1');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(mockedUploadImagesWithVariants).toHaveBeenCalledWith(
          'item',
          expect.any(Array)
        );
      });

      await waitFor(() => {
        expect(mockedUpdateItem).toHaveBeenCalledWith(
          'item-123',
          expect.objectContaining({
            imageFilenames: ['items/existing-image.jpg', 'items/new-upload.jpg'],
          })
        );
      });
    });

    it('shows success message and redirects', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByText('Item updated successfully! Redirecting...')).toBeInTheDocument();
      });

      // Wait for the redirect (setTimeout 1500ms in the component)
      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith('/items/item-123');
      }, { timeout: 3000 });
    });

    it('shows loading state during submission', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      // Create a promise that doesn't resolve immediately
      let resolvePromise: ((value: any) => void) | undefined;
      mockedUpdateItem.mockImplementation(
        () => new Promise((resolve) => { resolvePromise = resolve; })
      );

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('button', { name: 'Updating...' })).toBeDisabled();
      });

      // Resolve the promise to clean up
      resolvePromise?.({ data: mockItem });
    });

    it('saves availability when user has only this item', async () => {
      mockedGetItems.mockResolvedValue({ data: { items: [mockItem] } });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(mockedUpdateAvailability).toHaveBeenCalledWith(
          expect.objectContaining({
            generalAvailableAfter: '09:00',
            generalAvailableBefore: '18:00',
          })
        );
      });
    });

    it('does not save availability when user has other items', async () => {
      const otherItem = { ...mockItem, id: 'item-456' };
      mockedGetItems.mockResolvedValue({ data: { items: [mockItem, otherItem] } });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(mockedUpdateItem).toHaveBeenCalled();
      });

      // Wait a bit more to ensure no late calls
      await new Promise((resolve) => setTimeout(resolve, 50));

      expect(mockedUpdateAvailability).not.toHaveBeenCalled();
    });
  });

  describe('Error Handling', () => {
    it('displays error when item fetch fails', async () => {
      mockedGetItem.mockRejectedValue({
        response: { data: { message: 'Item not found' } },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Item not found');
      });
    });

    it('displays error when update fails', async () => {
      mockedUpdateItem.mockRejectedValue({
        response: { data: { message: 'Update failed' } },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Update failed');
      });
    });

    it('displays generic error for unknown failures', async () => {
      mockedUpdateItem.mockRejectedValue(new Error('Network error'));

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('item-name')).toHaveValue('Test Camera');
      });

      fireEvent.click(screen.getByRole('button', { name: 'Update Listing' }));

      await waitFor(() => {
        expect(screen.getByRole('alert')).toHaveTextContent('Network error');
      });
    });
  });

  describe('Navigation', () => {
    it('navigates back when clicking Back button', async () => {
      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByText('Edit Listing')).toBeInTheDocument();
      });

      fireEvent.click(screen.getByRole('button', { name: 'Back' }));

      expect(mockNavigate).toHaveBeenCalledWith(-1);
    });
  });

  describe('Address Selection', () => {
    it('displays address dropdown when user has addresses', async () => {
      mockedGetAddresses.mockResolvedValue({ data: [mockAddress] });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('address-select')).toBeInTheDocument();
      });
    });

    it('allows selecting a saved address', async () => {
      mockedGetAddresses.mockResolvedValue({ data: [mockAddress] });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('address-select')).toBeInTheDocument();
      });

      fireEvent.change(screen.getByTestId('address-select'), {
        target: { value: 'addr-1' },
      });

      await waitFor(() => {
        expect(screen.getByTestId('address1')).toHaveValue('456 Oak Ave');
        expect(screen.getByTestId('city')).toHaveValue('Boston');
        expect(screen.getByTestId('state')).toHaveValue('MA');
      });
    });

    it('clears address when selecting "new"', async () => {
      mockedGetAddresses.mockResolvedValue({ data: [mockAddress] });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('address-select')).toBeInTheDocument();
      });

      // First select the saved address
      fireEvent.change(screen.getByTestId('address-select'), {
        target: { value: 'addr-1' },
      });

      await waitFor(() => {
        expect(screen.getByTestId('address1')).toHaveValue('456 Oak Ave');
      });

      // Then select "new"
      fireEvent.change(screen.getByTestId('address-select'), {
        target: { value: 'new' },
      });

      await waitFor(() => {
        expect(screen.getByTestId('address1')).toHaveValue('');
        expect(screen.getByTestId('city')).toHaveValue('');
      });
    });
  });

  describe('Pricing Tiers', () => {
    it('sets pricing unit based on existing item data', async () => {
      mockedGetItem.mockResolvedValue({
        data: { ...mockItem, pricePerDay: 50 },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('price-per-day')).toHaveValue(50);
      });
    });

    it('prioritizes hourly pricing when set', async () => {
      mockedGetItem.mockResolvedValue({
        data: { ...mockItem, pricePerHour: 10, pricePerDay: 50 },
      });

      renderWithRouter();

      await waitFor(() => {
        expect(screen.getByTestId('price-per-hour')).toHaveValue(10);
        expect(screen.getByTestId('price-per-day')).toHaveValue(50);
      });
    });
  });
});
