// Meu perfil (/conta/:aba): Perfil, Conta, Preferências, Notificações, Segurança e Sessões.
// É a conta real do usuário autenticado: nada sobre segurança é inventado. Alterar senha usa o contrato existente
// (VxAuth.updatePassword / Supabase Auth). MFA e lista de outros dispositivos não têm contrato e aparecem como indisponíveis.
const PF_TABS = [{ value: 'perfil', label: 'Perfil', icon: 'ph-user' }, { value: 'conta', label: 'Conta', icon: 'ph-identification-card' }, { value: 'pref', label: 'Preferências', icon: 'ph-sliders' }, { value: 'notif', label: 'Notificações', icon: 'ph-bell' }, { value: 'seg', label: 'Segurança', icon: 'ph-shield-check' }, { value: 'sess', label: 'Sessões', icon: 'ph-devices' }];
const PF_NOTIF = ['Sistema', 'Segurança', 'Comercial', 'Oportunidades', 'Tarefas', 'Integrações', 'Erros'];
const pfLoadNotif = () => { try { return { ...Object.fromEntries(PF_NOTIF.map(k => [k, true])), ...JSON.parse(localStorage.getItem('vx-notif-prefs') || '{}') }; } catch (e) { return Object.fromEntries(PF_NOTIF.map(k => [k, true])); } };
const pfDevice = () => { const u = navigator.userAgent; const b = /Edg\//.test(u) ? 'Edge' : /Chrome\//.test(u) ? 'Chrome' : /Firefox\//.test(u) ? 'Firefox' : /Safari\//.test(u) ? 'Safari' : 'Navegador'; const os = /Windows/.test(u) ? 'Windows' : /Mac OS/.test(u) ? 'macOS' : /Android/.test(u) ? 'Android' : /iPhone|iPad/.test(u) ? 'iOS' : /Linux/.test(u) ? 'Linux' : ''; return [b, os].filter(Boolean).join(' · '); };
const pfPwError = pw => !pw ? 'Informe a nova senha.' : (pw.length < 8 || !/[A-Za-z]/.test(pw) || !/\d/.test(pw)) ? 'Use ao menos 8 caracteres, com letras e números.' : '';

function PasswordModal({ onClose, toast }) {
  const { Modal, PasswordInput, Button, Alert } = window.VRticeDesignSystem_d763eb;
  const [pw, setPw] = React.useState(''), [pw2, setPw2] = React.useState(''), [touched, setTouched] = React.useState(false), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState('');
  const pErr = touched ? pfPwError(pw) : '', cErr = touched && pw2 !== pw ? 'As senhas não coincidem.' : '';
  const submit = async () => {
    setTouched(true); setErr('');
    if (pfPwError(pw) || pw !== pw2) return;
    setBusy(true);
    const { error } = await window.VxAuth.updatePassword(pw);
    setBusy(false);
    if (error) return setErr(error);
    onClose(); toast('Senha alterada', 'ph-lock-key');
  };
  return (
    <Modal kicker="Segurança" title="Alterar senha" width={480} onClose={busy ? undefined : onClose} footer={<><Button style={{ flex: 1 }} loading={busy} onClick={submit}>Salvar nova senha</Button><Button variant="ghost" disabled={busy} onClick={onClose}>Cancelar</Button></>}>
      <PasswordInput label="Nova senha" placeholder="Mínimo de 8 caracteres" value={pw} onChange={e => setPw(e.target.value)} error={pErr} disabled={busy} />
      <PasswordInput label="Confirmar nova senha" placeholder="Repita a nova senha" value={pw2} onChange={e => setPw2(e.target.value)} error={cErr} disabled={busy} />
      {err && <Alert tone="danger">{err}</Alert>}
    </Modal>
  );
}

function ProfileScreen({ params }) {
  const { Card, CardHeader, Avatar, Badge, Tag, Alert, Tabs, Input, Button, DataField, SettingRow, ThemeSelect, Select, Switch } = window.VRticeDesignSystem_d763eb;
  const { user, saveUser, toast, bp, go, env } = useShell();
  const { enforced } = useAccess();
  const tab = (params && params.tab && PF_TABS.some(t => t.value === params.tab)) ? params.tab : 'perfil';
  const [d, setD] = React.useState({ name: user.name, role: user.role, email: user.email, phone: user.phone || '', reg: user.reg || '', base: user.base || '', color: user.color || UM_COLORS[0], photo: user.photo });
  const [err, setErr] = React.useState(''), [np, setNp] = React.useState(pfLoadNotif), [pwOpen, setPwOpen] = React.useState(false);
  const set = (k, v) => { setErr(''); setD(s => ({ ...s, [k]: v })); };
  const save = async () => { if (!d.name.trim()) return setErr('Informe o nome.'); setErr(''); const { data, error } = await window.VxAuth.saveProfile({ full_name: d.name.trim(), display_name: d.name.trim(), job_title: d.role || null, phone: d.phone || null, avatar_url: d.photo && /^https?:\/\//.test(d.photo) ? d.photo : null }); if (error) return setErr(error); const saved = data || {}; saveUser({ ...user, ...d, name: saved.full_name || saved.display_name || d.name.trim(), role: saved.job_title || d.role, phone: saved.phone || d.phone || '', photo: saved.avatar_url || d.photo }); toast('Nome, cargo e telefone salvos'); };
  const setNotif = (k, v) => { const n = { ...np, [k]: v }; setNp(n); try { localStorage.setItem('vx-notif-prefs', JSON.stringify(n)); } catch (e) {} };
  const F = (k, label, extra) => <Input key={k} label={label} value={d[k]} onChange={e => set(k, e.target.value)} {...extra} />;
  return (
    <>
      <Card variant="card" padding={bp === 'mobile' ? 20 : '28px 32px'} gap={20}>
        <div style={{ display: 'flex', gap: 20, alignItems: 'center', flexWrap: 'wrap' }}>
          <Avatar name={user.name} src={user.photo} color={user.color} size={72} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1, minWidth: 220 }}>
            <h1 style={{ margin: 0, fontSize: bp === 'mobile' ? 24 : 30, fontWeight: 600, letterSpacing: '-0.03em', overflowWrap: 'anywhere' }}>{user.name}</h1>
            <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>{user.role} · {user.email}</span>
            <span style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}><Badge tone="success" dot>Sessão ativa</Badge><Tag icon="ph-buildings">{env.org}</Tag><Badge variant="meta" tone={env.tone}>{env.label}</Badge></span>
          </div>
        </div>
        <Alert tone="info" title="Permissões efetivas">{enforced ? 'As permissões exibidas vêm do servidor. Toda ação sensível é validada novamente no backend.' : 'Vêm do servidor (RBAC + RLS). A autorização de interface ainda não está ativa neste ambiente; toda ação sensível continua sendo validada no backend.'}</Alert>
      </Card>
      <div style={{ overflowX: 'auto' }}><Tabs value={tab} onChange={t => go('profile', { tab: t })} tabs={PF_TABS} /></div>
      {tab === 'perfil' && (
        <Card variant="flat" gap={20}>
          <CardHeader title="Dados pessoais" />
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
            <Avatar name={d.name} src={d.photo} color={d.color} size={64} />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
              <label className="vx-btn vx-btn--secondary vx-btn--sm"><i className="ph ph-camera" />Trocar foto<input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => { const f = e.target.files && e.target.files[0]; if (f) set('photo', URL.createObjectURL(f)); }} /></label>
              {d.photo && <Button variant="danger" size="sm" onClick={() => set('photo', undefined)}>Remover</Button>}
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Foto e cor valem só nesta sessão; ainda não são gravadas no servidor.</span>
              <span style={{ display: 'flex', gap: 8, marginLeft: 8 }}>{UM_COLORS.map(c => <button key={c} type="button" aria-label="Cor do avatar" aria-pressed={d.color === c} onClick={() => set('color', c)} style={{ cursor: 'pointer', width: 26, height: 26, borderRadius: '50%', padding: 0, background: c, border: '2px solid ' + (d.color === c ? 'var(--status-info)' : 'transparent') }} />)}</span>
            </div>
          </div>
          <div style={cxGrid(260, 18)}>{F('name', 'Nome')}{F('role', 'Cargo')}{F('email', 'E-mail', { disabled: true, hint: 'Gerenciado pelo login (Supabase Auth).' })}{F('phone', 'Telefone', { mono: true, placeholder: '(11) 99999-0000' })}{F('reg', 'Registro profissional', { placeholder: 'CREA-SP 0000000000', hint: 'Ainda não é gravado no servidor.' })}{F('base', 'Base', { placeholder: 'Cidade - UF', hint: 'Ainda não é gravado no servidor.' })}</div>
          {err && <span role="alert" style={{ fontSize: 13, color: 'var(--status-danger-text)' }}>{err}</span>}
          <div><Button onClick={save}>Salvar perfil</Button></div>
        </Card>
      )}
      {tab === 'conta' && (
        <Card variant="flat" gap={20}>
          <CardHeader title="Conta" subtitle="Identidade e contexto de acesso" />
          <div style={cxGrid(220, 24)}><DataField label="E-mail de login">{user.email}</DataField><DataField label="Organização">{env.org}</DataField><DataField label="Ambiente">{env.label}</DataField><DataField label="Tipo de ambiente" mono>{env.kind}</DataField></div>
          <Alert tone="info">Organização, ambiente e papel vêm da sua associação (membership) no servidor. O seletor de contexto ainda é ilustrativo.</Alert>
        </Card>
      )}
      {tab === 'pref' && (
        <Card variant="flat" gap={4}>
          <CardHeader title="Preferências" />
          <SettingRow title="Tema" description="Claro, escuro ou seguir o sistema. Persistente neste navegador."><ThemeSelect /></SettingRow>
          <SettingRow title="Página inicial" description="Tela aberta após o login."><Select compact options={['Dashboard', 'Visão comercial', 'Pipeline']} disabled /><Badge variant="meta" tone="neutral">Em breve</Badge></SettingRow>
          <SettingRow title="Mais preferências" description="Menu lateral, tamanho da interface e atalhos."><Button size="sm" variant="secondary" onClick={() => go('config')}>Abrir configurações</Button></SettingRow>
        </Card>
      )}
      {tab === 'notif' && (
        <Card variant="flat" gap={4}>
          <CardHeader title="Notificações" subtitle="Escolha o que chega até você. Salvo neste navegador." />
          {PF_NOTIF.map(k => <SettingRow key={k} title={k}><Switch checked={np[k]} onChange={v => setNotif(k, v)} /></SettingRow>)}
        </Card>
      )}
      {tab === 'seg' && (
        <Card variant="flat" gap={4}>
          <CardHeader title="Segurança" />
          <SettingRow title="Senha" description="Defina uma nova senha para entrar no Vértice OS."><Button size="sm" variant="secondary" icon="ph-lock-key" onClick={() => setPwOpen(true)}>Alterar senha</Button></SettingRow>
          <SettingRow title="Autenticação em dois fatores" description="Ainda não oferecida pelo login atual."><Badge variant="meta" tone="neutral">Em breve</Badge></SettingRow>
        </Card>
      )}
      {tab === 'sess' && (
        <Card variant="flat" gap={4}>
          <CardHeader title="Sessões ativas" />
          <SettingRow icon={/Android|iOS/.test(pfDevice()) ? 'ph-device-mobile' : 'ph-desktop'} title={pfDevice()} description="Esta sessão"><Badge tone="info">Atual</Badge></SettingRow>
          <div style={{ paddingTop: 12 }}><Alert tone="info">Outros dispositivos aparecem aqui quando houver contrato de sessões no backend. Para encerrar esta sessão, use Sair no menu da conta.</Alert></div>
        </Card>
      )}
      {pwOpen && <PasswordModal onClose={() => setPwOpen(false)} toast={toast} />}
    </>
  );
}
window.ProfileScreen = ProfileScreen;
