"use client"

import { createContext, useContext, useState, useEffect, ReactNode } from "react"

export interface ProfilData {
  prenom: string
  nom: string
  email: string
  tel: string
  poste: string
  bio: string
  avatar: string | null        // base64 ou null
  nomEntreprise: string
  secteur: string
  logoEntreprise: string | null // base64 ou null
}

const DEFAUT: ProfilData = {
  prenom:          "Jean",
  nom:             "Dupont",
  email:           "jean.dupont@altis.ci",
  tel:             "+225 07 00 00 00",
  poste:           "Responsable RH",
  bio:             "Responsable RH avec 8 ans d'expérience.",
  avatar:          null,
  nomEntreprise:   "Groupe Altis",
  secteur:         "Recrutement & RH",
  logoEntreprise:  null,
}

const CLE = "scpro360_profil"

interface ProfilCtx {
  profil: ProfilData
  mettreAJour: (data: Partial<ProfilData>) => void
}

const Ctx = createContext<ProfilCtx>({
  profil:       DEFAUT,
  mettreAJour: () => {},
})

export function ProfilProvider({ children }: { children: ReactNode }) {
  const [profil, setProfil] = useState<ProfilData>(DEFAUT)

  // Lecture localStorage au montage
  useEffect(() => {
    try {
      const data = localStorage.getItem(CLE)
      if (data) setProfil({ ...DEFAUT, ...JSON.parse(data) })
    } catch {}
  }, [])

  const mettreAJour = (data: Partial<ProfilData>) => {
    setProfil(prev => {
      const nouveau = { ...prev, ...data }
      localStorage.setItem(CLE, JSON.stringify(nouveau))
      return nouveau
    })
  }

  return <Ctx.Provider value={{ profil, mettreAJour }}>{children}</Ctx.Provider>
}

export const useProfil = () => useContext(Ctx)