

export type OrderItem = {
  id: string;
  name: string;
  quantity: number;
  price: number;
  artisanWage: number;
  measurements?: string;
};

export type Order = {
  id: string;
  memoId?: string;
  customerId: string;
  customer: string;
  phone: string;
  type: 'pickup' | 'delivery';
  status: 'New' | 'In Progress' | 'Ready for Delivery' | 'Delivered' | 'Completed' | 'Cancelled';
  date: string;
  totalAmount: number;
  paidAmount: number;
  totalArtisanWage: number;
  items: OrderItem[];
  deliveryDate?: string;
  artisan?: string;
  cuttingMaster?: string;
  artisanAssignedDate?: string;
  artisanCompletedDate?: string;
  cuttingCompletedDate?: string;
};


export const initialMockOrders: Order[] = [];

export const getMockOrders = (): Order[] => {
  if (typeof window !== 'undefined') {
    const storedOrders = localStorage.getItem('mockOrders');
    if (storedOrders) {
      try {
        const parsedOrders = JSON.parse(storedOrders);
        if (Array.isArray(parsedOrders)) {
           // Basic validation to check if it's the old or new format
           if (parsedOrders.length === 0 || (parsedOrders[0] && 'items' in parsedOrders[0])) {
             return parsedOrders;
           }
        }
      } catch (e) {
        console.error("Failed to parse orders from localStorage, using initial data.", e);
        // If parsing fails, reset to initial to avoid crashes
        localStorage.setItem('mockOrders', JSON.stringify(initialMockOrders));
        return initialMockOrders;
      }
    }
    // If no data, set initial
    localStorage.setItem('mockOrders', JSON.stringify(initialMockOrders));
  }
  return initialMockOrders;
};


export type Customer = {
    id: string;
    name: string;
    phone: string;
};

export const initialMockCustomers: Customer[] = [];

export const getMockCustomers = (): Customer[] => {
    if (typeof window !== 'undefined') {
        const storedCustomers = localStorage.getItem('mockCustomers');
        if (storedCustomers) {
            try {
                const parsedCustomers = JSON.parse(storedCustomers);
                if (Array.isArray(parsedCustomers)) {
                    if (parsedCustomers.length === 0 || (parsedCustomers[0] && 'name' in parsedCustomers[0])) {
                        return parsedCustomers;
                    }
                }
            } catch (e) {
                console.error("Failed to parse customers from localStorage, resetting.", e);
                localStorage.setItem('mockCustomers', JSON.stringify(initialMockCustomers));
                return initialMockCustomers;
            }
        }
        localStorage.setItem('mockCustomers', JSON.stringify(initialMockCustomers));
    }
    return initialMockCustomers;
};

export type CustomerMeasurement = {
    id: string;
    customerId: string;
    itemName: string;
    measurements: string;
};

export const initialMockMeasurements: CustomerMeasurement[] = [];

export const getMockMeasurements = (customerId?: string): CustomerMeasurement[] => {
    if (typeof window === 'undefined') {
        return [];
    }
    try {
        const storedMeasurements = localStorage.getItem('mockMeasurements');
        const allMeasurements = storedMeasurements ? JSON.parse(storedMeasurements) : initialMockMeasurements;
        if (Array.isArray(allMeasurements)) {
            if (customerId) {
                return allMeasurements.filter(m => m.customerId === customerId);
            }
            return allMeasurements;
        }
    } catch (e) {
        console.error("Failed to parse measurements from localStorage", e);
    }
    localStorage.setItem('mockMeasurements', JSON.stringify(initialMockMeasurements));
    return [];
};

export const addMockMeasurement = (measurement: Omit<CustomerMeasurement, 'id'>) => {
    const allMeasurements = getMockMeasurements();
    const newMeasurement = { ...measurement, id: `MEAS-${Date.now()}`};
    const updatedMeasurements = [...allMeasurements, newMeasurement];
    localStorage.setItem('mockMeasurements', JSON.stringify(updatedMeasurements));
};

export const updateMockMeasurement = (updatedMeasurement: CustomerMeasurement) => {
    const allMeasurements = getMockMeasurements();
    const updatedMeasurements = allMeasurements.map(m => m.id === updatedMeasurement.id ? updatedMeasurement : m);
    localStorage.setItem('mockMeasurements', JSON.stringify(updatedMeasurements));
};

export const deleteMockMeasurement = (measurementId: string) => {
    const allMeasurements = getMockMeasurements();
    const updatedMeasurements = allMeasurements.filter(m => m.id !== measurementId);
    localStorage.setItem('mockMeasurements', JSON.stringify(updatedMeasurements));
}



export type InventoryItem = {
    id: string;
    name: string;
    type: 'Cotton' | 'Silk' | 'Wool' | 'Linen';
    color: string;
    pricePerMeter: number;
    quantity: number;
    lowStockThreshold: number;
};

export const initialMockInventory: InventoryItem[] = [];

export const getMockInventory = (): InventoryItem[] => {
  if (typeof window === 'undefined') {
    return initialMockInventory;
  }
  try {
    const storedItems = localStorage.getItem('mockInventory');
    if (storedItems) {
      const parsedItems = JSON.parse(storedItems);
      if (Array.isArray(parsedItems)) {
        if (parsedItems.length === 0 || (parsedItems[0] && 'pricePerMeter' in parsedItems[0])) {
            return parsedItems;
        }
      }
    }
  } catch (e) {
    console.error("Failed to parse inventory from localStorage", e);
  }
  localStorage.setItem('mockInventory', JSON.stringify(initialMockInventory));
  return initialMockInventory;
};


export type TailoringItem = {
  id: string;
  name: string;
  category: 'Men' | 'Women' | 'Kids' | 'Other';
  sewingPrice: number;
  artisanWage: number;
};

export const initialMockTailoringItems: TailoringItem[] = [
    { id: 'ITEM001', name: 'Pant', category: 'Men', sewingPrice: 800, artisanWage: 250 },
    { id: 'ITEM002', name: 'Shirt', category: 'Men', sewingPrice: 600, artisanWage: 200 },
    { id: 'ITEM003', name: 'Suit', category: 'Men', sewingPrice: 5000, artisanWage: 1500 },
    { id: 'ITEM004', name: 'Salwar Kameez', category: 'Women', sewingPrice: 1200, artisanWage: 400 },
    { id: 'ITEM005', name: 'Blouse', category: 'Women', sewingPrice: 500, artisanWage: 150 },
    { id: 'ITEM006', name: 'Kids Frock', category: 'Kids', sewingPrice: 700, artisanWage: 220 },
];

export const getMockTailoringItems = (): TailoringItem[] => {
  if (typeof window === 'undefined') {
    return initialMockTailoringItems;
  }
  try {
    const storedItems = localStorage.getItem('mockTailoringItems');
    if (storedItems) {
      const parsedItems = JSON.parse(storedItems);
      if (Array.isArray(parsedItems)) {
        return parsedItems;
      }
    }
  } catch (e) {
    console.error("Failed to parse tailoring items from localStorage", e);
  }
  localStorage.setItem('mockTailoringItems', JSON.stringify(initialMockTailoringItems));
  return initialMockTailoringItems;
};


export type Transaction = {
  id: string;
  category: string;
  date: string;
  amount: number;
  description: string;
  isEditable?: boolean;
}

export const initialMockIncome: Transaction[] = [];

export const getMockIncome = (): Transaction[] => {
  if (typeof window === 'undefined') {
    return initialMockIncome;
  }
  try {
    const storedItems = localStorage.getItem('mockIncome');
    if (storedItems) {
      const parsedItems = JSON.parse(storedItems);
      if (Array.isArray(parsedItems)) {
        return parsedItems;
      }
    }
  } catch (e) {
    console.error("Failed to parse income from localStorage", e);
  }
  localStorage.setItem('mockIncome', JSON.stringify(initialMockIncome));
  return initialMockIncome;
};

export const expenseCategories = ['Salary Advance', 'Rent', 'Utilities', 'Supplies', 'Marketing', 'Other'];

export type Expense = {
  id: string;
  category: string;
  date: string;
  amount: number;
  description?: string;
  person?: string;
  isEditable?: boolean;
}

export const initialOtherExpenses: Expense[] = [];

export const getOtherExpenses = (): Expense[] => {
  if (typeof window === 'undefined') {
    return initialOtherExpenses;
  }
  try {
    const storedItems = localStorage.getItem('mockOtherExpenses');
    if (storedItems) {
      const parsedItems = JSON.parse(storedItems);
      if (Array.isArray(parsedItems)) {
        return parsedItems;
      }
    }
  } catch (e) {
    console.error("Failed to parse other expenses from localStorage", e);
  }
  localStorage.setItem('mockOtherExpenses', JSON.stringify(initialOtherExpenses));
  return initialOtherExpenses;
};


export type EmployeeRole = 'Tailor' | 'Manager' | 'Cutter' | 'Assistant';
export const employeeRoles: EmployeeRole[] = ['Tailor', 'Manager', 'Cutter', 'Assistant'];


export type Employee = {
    id: string;
    name: string;
    phone: string;
    role: EmployeeRole;
    monthlySalary?: number;
};

export const initialMockEmployees: Employee[] = [];

export const getMockEmployees = (): Employee[] => {
  if (typeof window === 'undefined') {
    return initialMockEmployees;
  }
  try {
    const storedItems = localStorage.getItem('mockEmployees');
    if (storedItems) {
      const parsedItems = JSON.parse(storedItems);
       if (Array.isArray(parsedItems)) {
         return parsedItems;
       }
    }
  } catch (e) {
    console.error("Failed to parse employees from localStorage", e);
  }
  localStorage.setItem('mockEmployees', JSON.stringify(initialMockEmployees));
  return initialMockEmployees;
};

export const getArtisans = () => {
    if (typeof window === 'undefined') {
        return initialMockEmployees.filter(e => e.role === 'Tailor' || e.role === 'Manager');
    }
    return getMockEmployees().filter(e => e.role === 'Tailor' || e.role === 'Manager');
}

export const getCuttingMasters = () => {
    if (typeof window === 'undefined') {
        return initialMockEmployees.filter(e => e.role === 'Cutter' || e.role === 'Manager');
    }
    return getMockEmployees().filter(e => e.role === 'Cutter' || e.role === 'Manager');
}

export type ShopProfile = {
  shopName: string;
  email: string;
  address: string;
  contact: string;
  logoUrl?: string | null;
}

const initialShopProfile: ShopProfile = {
  shopName: "Olympia Tailor",
  email: "contact@thetailorshop.com",
  address: "123 Main Street, Dhaka, Bangladesh",
  contact: "01700000000",
  logoUrl: "https://picsum.photos/seed/10/36/36"
}

export const getShopProfile = (): ShopProfile => {
  if (typeof window === 'undefined') {
    return initialShopProfile;
  }
  try {
    const storedProfile = localStorage.getItem('shopProfile');
    if (storedProfile) {
      return JSON.parse(storedProfile);
    }
  } catch (e) {
    console.error("Failed to parse shop profile from localStorage", e);
  }
  localStorage.setItem('shopProfile', JSON.stringify(initialShopProfile));
  return initialShopProfile;
};

export const setShopProfile = (profile: ShopProfile) => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('shopProfile', JSON.stringify(profile));
    window.dispatchEvent(new Event('storage'));
  }
}

export type LoginCredentials = {
  email: string;
  password?: string;
}

const initialLoginCredentials: LoginCredentials = {
  email: 'admin@gmail.com',
  password: 'password',
}

export const getLoginCredentials = (): LoginCredentials => {
  if (typeof window === 'undefined') {
    return initialLoginCredentials;
  }
  try {
    const storedCreds = localStorage.getItem('loginCredentials');
    if (storedCreds) {
      const parsed = JSON.parse(storedCreds);
       return { ...initialLoginCredentials, ...parsed };
    }
  } catch (e) {
    console.error("Failed to parse login credentials from localStorage", e);
  }
  localStorage.setItem('loginCredentials', JSON.stringify(initialLoginCredentials));
  return initialLoginCredentials;
};

export const setLoginCredentials = (credentials: LoginCredentials) => {
  if (typeof window !== 'undefined') {
    const currentCreds = getLoginCredentials();
    localStorage.setItem('loginCredentials', JSON.stringify({ ...currentCreds, ...credentials}));
    window.dispatchEvent(new Event('storage'));
  }
}

export type Service = {
    id: string;
    name: string;
    price: number;
    description?: string;
}

const initialMockServices: Service[] = [
    { id: 'service-1', name: 'Custom Suit', price: 450.00, description: 'A fully tailored suit, from measurement to final fitting.' },
    { id: 'service-2', name: 'Saree Blouse', price: 80.00, description: 'Custom designed and stitched saree blouse.' },
    { id: 'service-3', name: 'Shirt', price: 120.00, description: 'A bespoke shirt, tailored to your exact measurements.' },
    { id: 'service-4', name: 'Trousers', price: 150.00, description: 'Perfectly fitted trousers for any occasion.' },
    { id: 'service-5', name: 'Alterations', price: 25.00, description: 'Basic alterations, price varies by complexity.' },
];

export const getMockServices = (): Service[] => {
  if (typeof window === 'undefined') {
    return initialMockServices;
  }
  try {
    const storedServices = localStorage.getItem('mockServices');
    if (storedServices) {
      return JSON.parse(storedServices);
    }
  } catch (e) {
    console.error("Failed to parse services from localStorage", e);
  }
  localStorage.setItem('mockServices', JSON.stringify(initialMockServices));
  return initialMockServices;
}

export const setMockServices = (services: Service[]) => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('mockServices', JSON.stringify(services));
    window.dispatchEvent(new Event('storage'));
  }
}

export type AppearanceSettings = {
  theme: 'light' | 'dark';
  font: 'inter' | 'manrope' | 'system' | 'poppins' | 'pt-sans';
}

const initialAppearanceSettings: AppearanceSettings = {
  theme: 'light',
  font: 'inter',
}

export const getAppearanceSettings = (): AppearanceSettings => {
  if (typeof window === 'undefined') {
    return initialAppearanceSettings;
  }
  try {
    const storedSettings = localStorage.getItem('appearanceSettings');
    if (storedSettings) {
      return JSON.parse(storedSettings);
    }
  } catch (e) {
    console.error("Failed to parse appearance settings from localStorage", e);
  }
  localStorage.setItem('appearanceSettings', JSON.stringify(initialAppearanceSettings));
  return initialAppearanceSettings;
}

export const setAppearanceSettings = (settings: AppearanceSettings) => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('appearanceSettings', JSON.stringify(settings));
    window.dispatchEvent(new Event('storage'));
  }
}

export type NotificationSettings = {
  smsEnabled: boolean;
  smsProvider: 'twilio' | 'other';
  smsApiKey?: string;
  smsApiSecret?: string;
  smsSenderId?: string;
  smsMessageTemplate?: string;
  whatsappEnabled: boolean;
  whatsappApiKey?: string;
  whatsappSenderNumber?: string;
  whatsappMessageTemplate?: string;
};

const initialNotificationSettings: NotificationSettings = {
  smsEnabled: false,
  smsProvider: 'twilio',
  smsApiKey: '',
  smsApiSecret: '',
  smsSenderId: '',
  smsMessageTemplate: 'Dear {customerName}, your order #{orderId} is ready for delivery. Total due: {dueAmount}. Thank you, {shopName}.',
  whatsappEnabled: false,
  whatsappApiKey: '',
  whatsappSenderNumber: '',
  whatsappMessageTemplate: 'Dear {customerName}, your order *#{orderId}* is ready for delivery. Total due: *{dueAmount}*. Thank you, *{shopName}*.',
};

export const getNotificationSettings = (): NotificationSettings => {
    if (typeof window === 'undefined') {
        return initialNotificationSettings;
    }
    try {
        const stored = localStorage.getItem('notificationSettings');
        if (stored) {
            return JSON.parse(stored);
        }
    } catch (e) {
        console.error("Failed to parse notification settings from localStorage", e);
    }
    localStorage.setItem('notificationSettings', JSON.stringify(initialNotificationSettings));
    return initialNotificationSettings;
}

export const setNotificationSettings = (settings: NotificationSettings) => {
    if (typeof window !== 'undefined') {
        localStorage.setItem('notificationSettings', JSON.stringify(settings));
        window.dispatchEvent(new Event('storage'));
    }
}
