'use client'

import { useState } from 'react'
import { enterViewAs } from '@/app/actions/view-as'

type Candidate = {
  id: string
  email: string
  full_name: string | null
}

export function ViewAsSwitcher({ candidates }: { candidates: Candidate[] }) {
  const [open, setOpen] = useState(false)
  if (candidates.length === 0) return null

  return (
    <div style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="nav-signout"
        style={{ marginRight: '0.5rem' }}
      >
        View as ▾
      </button>
      {open && (
        <div
          style={{
            position: 'absolute',
            top: '100%',
            right: 0,
            marginTop: '0.4rem',
            background: '#fff',
            color: '#1a1a1a',
            border: '1px solid #d0d0d0',
            borderRadius: '6px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
            padding: '0.4rem 0',
            minWidth: '220px',
            zIndex: 20,
          }}
        >
          {candidates.map((c) => (
            <form key={c.id} action={enterViewAs}>
              <input type="hidden" name="user_id" value={c.id} />
              <button
                type="submit"
                style={{
                  display: 'block',
                  width: '100%',
                  background: 'transparent',
                  color: '#1a1a1a',
                  border: 'none',
                  textAlign: 'left',
                  padding: '0.5rem 0.9rem',
                  fontSize: '0.9rem',
                  borderRadius: 0,
                }}
              >
                {c.full_name || c.email}
                <div
                  className="muted"
                  style={{ fontSize: '0.75em', marginTop: '0.1rem' }}
                >
                  {c.email}
                </div>
              </button>
            </form>
          ))}
        </div>
      )}
    </div>
  )
}
