import React from 'react'
import { sfx } from '../utils/audio'
import { getUsers, setUser, setRole, getUser } from '../utils/storage'
import Auth from '../pages/Auth'

export default function SwitchAccountsModal({ open, onClose, onSwitched }){
  const [showAuth, setShowAuth] = React.useState(false)
  const [users, setUsersState] = React.useState([])
  const current = getUser()

  React.useEffect(()=>{
    if(open){
      try{ setUsersState(getUsers() || []) }catch{}
      setShowAuth(false)
    }
  },[open])

  if(!open) return null

  const choose = (u)=>{
    setUser(u)
    setRole(u?.role || null)
    sfx.play('success')
    onSwitched?.(u)
    onClose?.()
  }

  return (
    <div className="fixed inset-0 z-50">
      <div className="absolute inset-0 bg-black/40" onClick={()=>onClose?.()} />
      <div className="absolute inset-0 grid place-items-center p-4">
        <div className="w-full max-w-md rounded-2xl bg-white text-gray-800 shadow-xl border-2 border-onme-softBlue">
          <div className="flex items-center justify-between px-4 py-3 border-b-2 border-onme-softBlue">
            <h3 className="ui font-semibold">Switch Accounts</h3>
            <button onClick={()=>{ sfx.play('click'); onClose?.() }} aria-label="Close" className="ui text-xl">×</button>
          </div>

          {!showAuth ? (
            <div className="p-3 space-y-2">
              {users.map((u)=> (
                <button key={u.email} onClick={()=>choose(u)} className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50 text-left ${current?.email===u.email?'bg-gray-50':''}`}>
                  <div className="h-10 w-10 rounded-full bg-gray-300" aria-hidden />
                  <div className="flex-1">
                    <div className="ui font-semibold">{u.name||u.email}</div>
                    <div className="ui text-sm text-gray-500">@{(u.email||'').split('@')[0]}</div>
                  </div>
                  {current?.email===u.email && <span aria-label="Current" title="Current">✅</span>}
                </button>
              ))}
              <button onClick={()=>{ sfx.play('click'); setShowAuth(true) }} className="w-full flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50">
                <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center text-2xl">+</div>
                <div className="ui font-semibold">Add Account</div>
              </button>
            </div>
          ) : (
            <div className="p-3">
              <Auth />
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
