// Sidebar navigation

const { useState: sbState } = React;

/* ── Máscaras locais ── */
const sbMaskPhone = v => v.replace(/\D/g,'').slice(0,11)
  .replace(/^(\d{2})(\d)/,'($1) $2')
  .replace(/(\d{5})(\d{1,4})$/,'$1-$2');

/* ── Modal: Minha Conta ── */
function ModalMinhaConta({ perfil, onClose }) {
  const [tab, setTab] = sbState('dados'); // 'dados' | 'senha'
  const [form, setForm] = sbState({
    nome:'Ana', sobrenome:'Silva', email:'ana.silva@conexaopsi.com',
    telefone:'(11) 98765-4321',
    /* terapeuta */
    crp:'06/123456', valorSessao:'220',
    /* senha */
    senhaAtual:'', novaSenha:'', confirmarSenha:'',
  });
  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const inputStyle = {
    padding:'9px 12px', border:'1px solid #d1d5db', borderRadius:6,
    fontSize:14, background:'white', outline:'none', color:'#111',
    width:'100%', boxSizing:'border-box',
  };
  const labelStyle = { fontSize:13, fontWeight:500, color:'#374151' };
  const Field = ({ label, ...props }) => (
    <div style={{ display:'flex', flexDirection:'column', gap:5, flex:1 }}>
      <label style={labelStyle}>{label}</label>
      <input style={inputStyle} {...props} />
    </div>
  );

  /* força da nova senha */
  const pwd = form.novaSenha;
  const checks = [pwd.length >= 8, /[A-Z]/.test(pwd), /[0-9]/.test(pwd), /[^A-Za-z0-9]/.test(pwd)];
  const score = checks.filter(Boolean).length;
  const strength = pwd.length === 0 ? null
    : score <= 1 ? { label:'Fraca',    color:'#ef4444', w:'25%' }
    : score === 2 ? { label:'Razoável', color:'#f59e0b', w:'50%' }
    : score === 3 ? { label:'Boa',      color:'#3b82f6', w:'75%' }
    :               { label:'Forte',    color:'#16a34a', w:'100%' };

  const tabStyle = active => ({
    flex:1, padding:'9px', border:'none', borderBottom: active ? `2px solid ${C.primary}` : '2px solid transparent',
    background:'none', cursor:'pointer', fontSize:13, fontWeight: active ? 600 : 400,
    color: active ? C.primary : '#6b7280', transition:'all .15s',
  });

  return (
    <Modal title="Minha conta" onClose={onClose} width={480}>
      {/* Tab bar */}
      <div style={{ display:'flex', marginBottom:20, borderBottom:'1px solid #e5e7eb', marginTop:-4 }}>
        <button style={tabStyle(tab==='dados')} onClick={() => setTab('dados')}>Dados pessoais</button>
        <button style={tabStyle(tab==='senha')} onClick={() => setTab('senha')}>Alterar senha</button>
      </div>

      {tab === 'dados' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {/* Nome + Sobrenome */}
          <div style={{ display:'flex', gap:12 }}>
            <Field label="Nome" value={form.nome} onChange={set('nome')} placeholder="Nome" />
            <Field label="Sobrenome" value={form.sobrenome} onChange={set('sobrenome')} placeholder="Sobrenome" />
          </div>

          {/* E-mail */}
          <Field label="E-mail" type="email" value={form.email} onChange={set('email')} placeholder="seu@email.com" />

          {/* Telefone */}
          <Field label="Telefone" value={form.telefone}
            onChange={e => setForm(f => ({ ...f, telefone: sbMaskPhone(e.target.value) }))}
            placeholder="(11) 90000-0000" />

          {/* Campos exclusivos do terapeuta */}
          {perfil === 'terapeuta' && (
            <>
              <div style={{ borderTop:'1px solid #e5e7eb', paddingTop:4 }}>
                <label style={{ fontSize:11, fontWeight:700, color:'#9ca3af', letterSpacing:'.06em', textTransform:'uppercase', display:'block', marginBottom:12 }}>
                  Perfil Profissional
                </label>
                <div style={{ display:'flex', gap:12 }}>
                  <Field label="Registro CRP/CRM" value={form.crp} onChange={set('crp')} placeholder="06/123456" />
                  <div style={{ flex:1, display:'flex', flexDirection:'column', gap:5 }}>
                    <label style={labelStyle}>Valor da sessão</label>
                    <div style={{ position:'relative' }}>
                      <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', fontSize:14, color:'#6b7280', pointerEvents:'none' }}>R$</span>
                      <input type="number" placeholder="220" value={form.valorSessao} onChange={set('valorSessao')}
                        style={{ ...inputStyle, paddingLeft:36 }} />
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}
        </div>
      )}

      {tab === 'senha' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Field label="Senha atual" type="password" value={form.senhaAtual} onChange={set('senhaAtual')} placeholder="••••••••" />

          <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
            <label style={labelStyle}>Nova senha</label>
            <input type="password" placeholder="Mínimo 8 caracteres" value={form.novaSenha} onChange={set('novaSenha')} style={inputStyle} />
            {strength && (
              <div>
                <div style={{ height:4, background:'#e5e7eb', borderRadius:2, overflow:'hidden', marginTop:4 }}>
                  <div style={{ height:'100%', width:strength.w, background:strength.color, borderRadius:2, transition:'width .3s, background .3s' }} />
                </div>
                <span style={{ fontSize:11, color:strength.color, fontWeight:500 }}>Força: {strength.label}</span>
              </div>
            )}
          </div>

          <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
            <label style={labelStyle}>Confirmar nova senha</label>
            <input type="password" placeholder="Repita a nova senha" value={form.confirmarSenha} onChange={set('confirmarSenha')} style={inputStyle} />
            {form.confirmarSenha.length > 0 && (
              <span style={{ fontSize:12, color: form.novaSenha === form.confirmarSenha ? '#16a34a' : '#ef4444' }}>
                {form.novaSenha === form.confirmarSenha ? '✓ Senhas coincidem' : '✕ Senhas não coincidem'}
              </span>
            )}
          </div>
        </div>
      )}

      <ModalActions onCancel={onClose} onConfirm={onClose} confirmLabel="Salvar alterações" />
    </Modal>
  );
}

/* ── Sidebar ── */
function Sidebar({ page, setPage, perfil = 'admin', onLogout }) {
  const [hov, setHov] = sbState(null);
  const [showMenu, setShowMenu] = sbState(false);
  const [showConta, setShowConta] = sbState(false);

  const allNav = [
    { group:'Principal' },
    { id:'dashboard',    label:'Dashboard',    icon:'dashboard',  roles:['admin','secretaria','terapeuta'] },
    { id:'agenda',       label:'Agenda',       icon:'agenda',     roles:['admin','secretaria','terapeuta'] },
    { id:'pacientes',    label:'Pacientes',    icon:'pacientes',  roles:['admin','secretaria','terapeuta'] },
    { id:'meuperfil',    label:'Meu Perfil',   icon:'idcard',     roles:['terapeuta'] },
    { group:'Gestão' },
    { id:'usuarios',     label:'Usuários',     icon:'usuarios',   roles:['admin'] },
    { id:'relatorios',   label:'Relatórios',   icon:'chart',      roles:['admin'] },
    { id:'financeiro',   label:'Financeiro',   icon:'financeiro', roles:['admin','secretaria'] },
    { id:'unidades',     label:'Unidades',     icon:'unidades',   roles:['admin','secretaria'] },
    { group:'Sistema' },
    { id:'auditoria',    label:'Auditoria',    icon:'clipboard',  roles:['admin'] },
    { id:'configuracoes',label:'Configurações',icon:'settings',   roles:['admin'] },
  ];

  // Filtra por perfil e remove grupos vazios
  const withRoles = allNav.filter(item => item.group || item.roles.includes(perfil));
  const nav = withRoles.filter((item, i) =>
    item.group ? (withRoles[i + 1] && !withRoles[i + 1].group) : true
  );

  return (
    <>
      <div style={{ width:176, background:C.sidebar, display:'flex', flexDirection:'column', flexShrink:0, height:'100vh', position:'sticky', top:0 }}>
        {/* Logo */}
        <div style={{ padding:'14px 16px 12px', borderBottom:'1px solid rgba(255,255,255,0.08)', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <img src="uploads/WhatsApp_Image_2026-03-16_at_20.39.04_-_Copia-removebg-preview-82c82356.png" alt="Conexão" style={{ height:32, width:'auto', objectFit:'contain' }} />
        </div>

        {/* Nav links */}
        <nav style={{ flex:1, padding:'10px 0', overflowY:'auto' }}>
          {nav.map((item, i) => {
            if (item.group) return (
              <div key={`g-${i}`} style={{ padding:'14px 16px 4px', display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:10, fontWeight:700, color:'rgba(184,204,228,0.4)', letterSpacing:'.1em', textTransform:'uppercase' }}>{item.group}</span>
                <div style={{ flex:1, height:1, background:'rgba(255,255,255,0.07)' }} />
              </div>
            );
            const active = page === item.id || (page.startsWith('paciente-') && item.id === 'pacientes');
            const isHov = hov === item.id;
            return (
              <button key={item.id} onClick={() => setPage(item.id)}
                onMouseEnter={() => setHov(item.id)}
                onMouseLeave={() => setHov(null)}
                style={{
                  display:'flex', alignItems:'center', gap:10,
                  width:'100%', padding:'10px 16px',
                  background: active ? C.sidebarAct : isHov ? 'rgba(255,255,255,0.06)' : 'transparent',
                  border:'none', cursor:'pointer',
                  color: active ? 'white' : 'rgba(184,204,228,0.9)',
                  fontSize:14, fontWeight: active ? 600 : 400,
                  textAlign:'left', transition:'background 0.15s',
                }}>
                <Icon name={item.icon} size={16} color={active ? 'white' : 'rgba(184,204,228,0.8)'} />
                {item.label}
              </button>
            );
          })}
        </nav>

        {/* Footer user */}
        <div style={{ position:'relative', padding:'12px 16px', borderTop:'1px solid rgba(255,255,255,0.08)' }}>
          {/* Popup menu */}
          {showMenu && (
            <div style={{
              position:'absolute', bottom:'calc(100% + 6px)', left:12, right:12,
              background:'#245485', borderRadius:8, overflow:'hidden',
              boxShadow:'0 8px 24px rgba(0,0,0,0.4)', border:'1px solid rgba(255,255,255,0.1)',
            }}>
              {/* Minha conta */}
              <button onClick={() => { setShowConta(true); setShowMenu(false); }}
                style={{ width:'100%', padding:'11px 14px', background:'none', border:'none', cursor:'pointer', color:'rgba(184,204,228,0.9)', fontSize:13, fontWeight:500, textAlign:'left', display:'flex', alignItems:'center', gap:8 }}
                onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,0.05)'}
                onMouseLeave={e => e.currentTarget.style.background='none'}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2M12 7a4 4 0 100 8 4 4 0 000-8z"/>
                </svg>
                Minha conta
              </button>

              {/* Divider */}
              <div style={{ height:1, background:'rgba(255,255,255,0.08)', margin:'0 10px' }} />

              {/* Sair */}
              <button onClick={onLogout}
                style={{ width:'100%', padding:'11px 14px', background:'none', border:'none', cursor:'pointer', color:'#fca5a5', fontSize:13, fontWeight:500, textAlign:'left', display:'flex', alignItems:'center', gap:8 }}
                onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,0.05)'}
                onMouseLeave={e => e.currentTarget.style.background='none'}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/>
                </svg>
                Sair
              </button>
            </div>
          )}

          {/* User row */}
          <button onClick={() => setShowMenu(s => !s)}
            style={{ display:'flex', alignItems:'center', gap:10, width:'100%', background:'none', border:'none', cursor:'pointer', padding:0, borderRadius:6, transition:'background 0.15s' }}
            onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,0.05)'}
            onMouseLeave={e => e.currentTarget.style.background='none'}>
            <div style={{ width:34, height:34, borderRadius:'50%', background:'#1C416B', display:'flex', alignItems:'center', justifyContent:'center', color:'white', fontWeight:700, fontSize:13, flexShrink:0 }}>D</div>
            <div style={{ overflow:'hidden', textAlign:'left', flex:1 }}>
              <div style={{ color:'white', fontSize:13, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Dr. Ana Silva</div>
              <div style={{ color:'rgba(184,204,228,0.7)', fontSize:11 }}>
                {perfil === 'admin' ? 'Administradora' : perfil === 'terapeuta' ? 'Terapeuta' : 'Secretária'}
              </div>
            </div>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(184,204,228,0.5)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
              style={{ transform: showMenu ? 'rotate(180deg)' : 'none', transition:'transform 0.2s', flexShrink:0 }}>
              <path d="M6 9l6 6 6-6"/>
            </svg>
          </button>
        </div>
      </div>

      {/* Modal Minha Conta — fora do sidebar para ficar sobre tudo */}
      {showConta && <ModalMinhaConta perfil={perfil} onClose={() => setShowConta(false)} />}
    </>
  );
}

Object.assign(window, { Sidebar });
