import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AppEnvState {
  // Branding
  appName: string;
  appTagline: string;
  appMotto: string;
  appLogo: string; // URL or emoji
  appLogoUrl: string; // Uploaded logo URL
  faviconUrl: string; // Uploaded favicon URL

  // Colors
  primaryColor: string; // hex like #f97316
  primaryHover: string;
  accentColor: string;
  gradientFrom: string;
  gradientTo: string;

  // Layout
  currencySymbol: string; // ৳
  footerText: string;
  copyrightText: string;

  // Contact
  contactPhone: string;
  contactEmail: string;
  contactAddress: string;

  // Module toggles
  enableHouseRental: boolean;
  enableShopRental: boolean;
  enableMarketplace: boolean;
  enableMedicine: boolean;
  enableEducation: boolean;
  enableCommunity: boolean;

  // Splash & Media
  splashLogoUrl: string;
  ogImage: string;

  // SEO
  seoTitle: string;
  seoDescription: string;

  // Actions
  updateEnv: (partial: Partial<AppEnvState>) => void;
  loadFromApi: () => Promise<void>;
  resetEnv: () => void;
}

const defaultEnv: Omit<AppEnvState, 'updateEnv' | 'loadFromApi' | 'resetEnv'> = {
  appName: 'Needyfy',
  appTagline: 'Your Super App for Bangladesh',
  appMotto: 'Simplifying Life, One Tap at a Time',
  appLogo: '🏠',
  appLogoUrl: '',
  faviconUrl: '',
  splashLogoUrl: '',
  ogImage: '',
  primaryColor: '#f97316',
  primaryHover: '#ea580c',
  accentColor: '#f59e0b',
  gradientFrom: '#ea580c',
  gradientTo: '#f59e0b',
  currencySymbol: '৳',
  footerText: '© 2025 Needyfy. All rights reserved.',
  copyrightText: '© 2025 Needyfy. All rights reserved.',
  contactPhone: '+880 1234-567890',
  contactEmail: 'support@needyfy.com',
  contactAddress: 'Dhaka, Bangladesh',
  enableHouseRental: true,
  enableShopRental: true,
  enableMarketplace: true,
  enableMedicine: true,
  enableEducation: true,
  enableCommunity: true,
  seoTitle: 'Needyfy - Every Need, One Platform',
  seoDescription: "Bangladesh's complete super app for all your daily needs",
};

export const useAppEnv = create<AppEnvState>()(
  persist(
    (set) => ({
      ...defaultEnv,
      updateEnv: (partial) => set((state) => ({ ...state, ...partial })),
      loadFromApi: async () => {
        try {
          const res = await fetch('/api/admin/settings');
          const data = await res.json();
          if (data.success && data.flat) {
            const flat = data.flat;
            set({
              appName: flat.appName || defaultEnv.appName,
              appTagline: flat.appTagline || defaultEnv.appTagline,
              appMotto: flat.appMotto || defaultEnv.appMotto,
              appLogoUrl: flat.appLogoUrl || flat.appLogo || defaultEnv.appLogoUrl,
              faviconUrl: flat.faviconUrl || defaultEnv.faviconUrl,
              splashLogoUrl: flat.splashLogoUrl || defaultEnv.splashLogoUrl,
              ogImage: flat.ogImage || defaultEnv.ogImage,
              primaryColor: flat.primaryColor || defaultEnv.primaryColor,
              primaryHover: flat.primaryHover || defaultEnv.primaryHover,
              accentColor: flat.accentColor || defaultEnv.accentColor,
              gradientFrom: flat.gradientFrom || defaultEnv.gradientFrom,
              gradientTo: flat.gradientTo || defaultEnv.gradientTo,
              footerText: flat.footerText || defaultEnv.footerText,
              copyrightText: flat.copyrightText || defaultEnv.copyrightText,
              contactPhone: flat.contactPhone || defaultEnv.contactPhone,
              contactEmail: flat.contactEmail || defaultEnv.contactEmail,
              contactAddress: flat.contactAddress || defaultEnv.contactAddress,
              enableHouseRental: flat.enableHouseRental !== 'false',
              enableShopRental: flat.enableShopRental !== 'false',
              enableMarketplace: flat.enableMarketplace !== 'false',
              enableMedicine: flat.enableMedicine !== 'false',
              enableEducation: flat.enableEducation !== 'false',
              enableCommunity: flat.enableCommunity !== 'false',
              seoTitle: flat.seoTitle || defaultEnv.seoTitle,
              seoDescription: flat.seoDescription || defaultEnv.seoDescription,
            });
          }
        } catch (err) {
          console.error('Failed to load app settings from API:', err);
        }
      },
      resetEnv: () => set(defaultEnv),
    }),
    {
      name: 'needyfy-env',
    }
  )
);
