import { useState, useEffect } from 'react'
import axios from 'axios'

export interface TenantConfig {
  id: number
  slug: string
  name: string
  primary_color: string
  secondary_color: string
  logo_url: string | null
  contact_email: string | null
  contact_phone: string | null
}

const DEFAULT: TenantConfig = {
  id: 1,
  slug: 'alemao',
  name: 'Alemão Conveniências',
  primary_color: '#f59e0b',
  secondary_color: '#10b981',
  logo_url: null,
  contact_email: null,
  contact_phone: null,
}

export function useTenant() {
  const [tenant, setTenant] = useState<TenantConfig>(DEFAULT)

  useEffect(() => {
    axios.get('/api/tenant/config').then(r => {
      const t = r.data as TenantConfig
      setTenant(t)
      // Apply CSS variables for dynamic theming
      document.documentElement.style.setProperty('--primary', t.primary_color)
      document.documentElement.style.setProperty('--secondary', t.secondary_color)
      if (t.name) document.title = t.name
    }).catch(() => {})
  }, [])

  return tenant
}
