/**
 * Pro Context - Manages Pro/Free state across the app
 */

import { createContext, useContext, ReactNode, useState, useCallback } from 'react'

interface LicenseInfo {
  isActive: boolean
  isPaying: boolean
  isTrial: boolean
  hasProPlugin: boolean
  planTitle: string
  planName: string
  expiresAt: string | null
  activationUrl: string
  accountUrl: string
}

interface ProContextType {
  isPro: boolean
  proFeatures: Record<string, { name: string; description: string; enabled: boolean }>
  limits: {
    currencies: number
    canAddCheckoutFields: boolean
    conditionalLogic: boolean
  }
  license: LicenseInfo
  upgradeUrl: string
  checkFeature: (featureKey: string) => boolean
  // Shake animation trigger
  shakeUpgradeButton: boolean
  triggerShake: () => void
}

const defaultLimits = {
  currencies: 3,
  canAddCheckoutFields: false,
  conditionalLogic: false,
}

const defaultLicense: LicenseInfo = {
  isActive: false,
  isPaying: false,
  isTrial: false,
  hasProPlugin: false,
  planTitle: 'Free',
  planName: 'free',
  expiresAt: null,
  activationUrl: '',
  accountUrl: '',
}

const ProContext = createContext<ProContextType>({
  isPro: false,
  proFeatures: {},
  limits: defaultLimits,
  license: defaultLicense,
  upgradeUrl: '',
  checkFeature: () => false,
  shakeUpgradeButton: false,
  triggerShake: () => {},
})

export function ProProvider({ children }: { children: ReactNode }) {
  const data = window.swiftCommerceData || {}
  const [shakeUpgradeButton, setShakeUpgradeButton] = useState(false)
  
  const isPro = data.isPro || false
  const proFeatures = data.proFeatures || {}
  const limits = data.limits || defaultLimits
  const license = data.license || defaultLicense
  const upgradeUrl = data.upgradeUrl || ''

  const checkFeature = (featureKey: string): boolean => {
    if (!isPro) return false
    const feature = proFeatures[featureKey]
    return feature?.enabled || false
  }

  const triggerShake = useCallback(() => {
    setShakeUpgradeButton(true)
    setTimeout(() => setShakeUpgradeButton(false), 600)
  }, [])

  return (
    <ProContext.Provider value={{ isPro, proFeatures, limits, license, upgradeUrl, checkFeature, shakeUpgradeButton, triggerShake }}>
      {children}
    </ProContext.Provider>
  )
}

export function usePro() {
  const context = useContext(ProContext)
  if (!context) {
    throw new Error('usePro must be used within a ProProvider')
  }
  return context
}

export { ProContext }
