/* global React, BezaLogo, Icon */
const { useState: useStateAuth, useEffect: useEffectAuth } = React;

/* ============================================================
   IDENTITY · quem está usando o dash
   ----
   Esta camada hoje é client-side simples. Quando a Beza migrar
   pra Supabase/NextAuth, é só substituir loadViewer/saveViewer
   pelas funções de auth real.
   ============================================================ */
const VIEWER_LS_KEY = 'beza_viewer_v1';

const VIEWER_OPTIONS = [
  { id: 'luan',     name: 'Luan',     role: 'Gestor',                avatar: 'L', color: '#9A9BE5', isManager: true  },
  { id: 'maria',    name: 'Maria',    role: 'Gestora',               avatar: 'M', color: '#9A9BE5', isManager: true  },
  { id: 'grazi',    name: 'Grazi',    role: 'Planejamento + Copy',   avatar: 'G', color: '#9A9BE5', isManager: false },
  { id: 'reinaldy', name: 'Reinaldy', role: 'Designer',              avatar: 'R', color: '#77B8F1', isManager: false },
  { id: 'lucas',    name: 'Lucas',    role: 'Vídeo',                 avatar: 'L', color: '#6FC878', isManager: false },
];

function loadViewer() {
  try { return JSON.parse(localStorage.getItem(VIEWER_LS_KEY) || 'null'); } catch { return null; }
}
function saveViewer(v) {
  try { localStorage.setItem(VIEWER_LS_KEY, JSON.stringify(v)); } catch (e) {}
}
function clearViewer() {
  try { localStorage.removeItem(VIEWER_LS_KEY); } catch (e) {}
}

/* ============================================================
   ViewerPicker · tela inicial de "quem é você"
   ============================================================ */
function ViewerPicker({ onPick }) {
  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 'var(--space-6) var(--space-5)',
      background: 'var(--bg)',
    }}>
      <div style={{
        width: '100%', maxWidth: 540,
        padding: 'var(--space-6)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
        border: '1px solid rgba(154,155,229,0.30)',
        borderRadius: 'var(--r-card-lg)',
        position: 'relative', overflow: 'hidden',
        boxShadow: '0 24px 64px rgba(154,155,229,0.18)',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-40%', right: '-15%',
          width: 500, height: 500, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(154,155,229,0.22), transparent 60%)',
          filter: 'blur(50px)', pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative' }}>
          <div style={{ marginBottom: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
            <BezaLogo size={28} />
          </div>

          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>
            Bem-vindo de volta
          </div>
          <h2 className="t-h1" style={{ margin: '0 0 12px', color: 'var(--text)', textWrap: 'pretty' }}>
            <span className="t-light">Quem está </span>
            <span className="punch">por aqui</span>
            <span className="t-light"> hoje?</span>
          </h2>
          <p style={{ margin: '0 0 28px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 420, lineHeight: 1.6 }}>
            Escolha seu perfil pra ver suas tarefas, prioridades e notas. Salvo neste navegador.
          </p>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {VIEWER_OPTIONS.map(v => (
              <button key={v.id} onClick={() => onPick(v)} style={{
                appearance: 'none', textAlign: 'left',
                padding: '14px 16px',
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-card)',
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'grid', gridTemplateColumns: '44px 1fr auto', gap: 14, alignItems: 'center',
                transition: 'all var(--t-fast)',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = v.color; e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = ''; }}
              >
                <div style={{
                  width: 40, height: 40, borderRadius: '50%',
                  background: v.color, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 16, fontWeight: 500,
                }}>{v.avatar}</div>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>
                    {v.name}
                    {v.isManager && (
                      <span style={{
                        marginLeft: 8, fontSize: 9, fontWeight: 500,
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                        color: 'var(--accent)', padding: '2px 6px',
                        background: 'var(--accent-soft)', borderRadius: 999,
                      }}>🔒 gestor</span>
                    )}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 2 }}>{v.role}</div>
                </div>
                <Icon.Arrow width={16} height={16} style={{ color: 'var(--text-faint)' }} />
              </button>
            ))}
          </div>

          <div style={{
            marginTop: 24, paddingTop: 16,
            borderTop: '1px solid var(--border)',
            fontSize: 11, color: 'var(--text-faint)', textAlign: 'center', lineHeight: 1.5,
          }}>
            Acesso temporário · ao migrar a Beza pra infra própria, vira login com SSO Google.
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   ViewerBadge · canto superior · troca de perfil
   ============================================================ */
function ViewerBadge({ viewer, onSwitch }) {
  const [open, setOpen] = useStateAuth(false);
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        appearance: 'none', border: '1px solid var(--border)',
        background: 'var(--surface)', color: 'var(--text)',
        padding: '6px 12px 6px 6px', borderRadius: 999,
        fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{
          width: 26, height: 26, borderRadius: '50%',
          background: viewer.color, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 500, fontSize: 12,
        }}>{viewer.avatar}</span>
        <span style={{ fontWeight: 500 }}>{viewer.name}</span>
        {viewer.isManager && <span style={{ fontSize: 10, color: 'var(--accent)' }}>🔒</span>}
        <span style={{ fontSize: 10, color: 'var(--text-faint)' }}>▾</span>
      </button>

      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: '100%', right: 0, marginTop: 6,
            zIndex: 41, minWidth: 220,
            background: 'var(--bg-flat)', border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-card)',
            boxShadow: '0 12px 32px rgba(26,26,26,0.12)',
            overflow: 'hidden',
          }}>
            <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>conectado como</div>
              <div style={{ fontSize: 14, color: 'var(--text)', fontWeight: 500, marginTop: 2 }}>{viewer.name}</div>
            </div>
            <button onClick={() => { onSwitch(); setOpen(false); }} style={{
              width: '100%', appearance: 'none', border: 'none',
              background: 'transparent', color: 'var(--text-muted)',
              padding: '10px 14px', fontSize: 13, fontFamily: 'inherit',
              cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 8,
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-soft)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              ⇄ Trocar de pessoa
            </button>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, {
  VIEWER_OPTIONS, loadViewer, saveViewer, clearViewer,
  ViewerPicker, ViewerBadge,
});
