/* Drawer panels for individual tool flows */
const { useState: useStateP, useEffect: useEffectP } = React;

function PanelField({ label, value, onChange, type = 'text', placeholder, options }) {
  const [focused, setFocused] = useStateP(false);
  const floating = focused || (value != null && value !== '');
  const Tag = options ? 'select' : type === 'textarea' ? 'textarea' : 'input';
  return (
    <label className={`field ${floating ? 'is-floating' : ''}`}>
      <Tag
        type={type === 'textarea' ? undefined : type}
        value={value || ''}
        onChange={e => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder=""
      >
        {options && options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </Tag>
      <span style={{}}>{label}</span>
    </label>
  );
}

function DrawerHeader({ tool, onClose }) {
  return (
    <div style={{
      padding: '20px 24px 18px',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      display: 'flex', alignItems: 'flex-start', gap: 14,
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 24, right: 24, height: 1,
        background: 'linear-gradient(90deg, transparent, rgba(34,197,94,0.6), transparent)',
      }} />
      <div className={`ic-wrap ${tool.kind || 'safe'}`} style={{
        width: 40, height: 40, borderRadius: 10,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background:
          tool.kind === 'danger' ? 'rgba(239,68,68,0.12)' :
          tool.kind === 'warn'   ? 'rgba(245,158,11,0.12)' :
          tool.kind === 'info'   ? 'rgba(59,130,246,0.12)' :
                                    'rgba(34,197,94,0.12)',
        border: `1px solid ${
          tool.kind === 'danger' ? 'rgba(239,68,68,0.30)' :
          tool.kind === 'warn'   ? 'rgba(245,158,11,0.32)' :
          tool.kind === 'info'   ? 'rgba(59,130,246,0.32)' :
                                    'rgba(34,197,94,0.30)'}`,
        color:
          tool.kind === 'danger' ? '#ef4444' :
          tool.kind === 'warn'   ? '#f59e0b' :
          tool.kind === 'info'   ? '#3b82f6' :
                                    '#22c55e',
      }}>
        <Icon name={tool.icon} size={18} />
      </div>
      <div style={{ flex: 1 }}>
        <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.28em' }}>
          / {tool.tag}
        </div>
        <h2 style={{ margin: '4px 0 4px', fontSize: 19, fontWeight: 500, letterSpacing: '-0.01em' }}>
          {tool.title}<span style={{ color: 'var(--green)' }}>.</span>
        </h2>
        <p style={{ margin: 0, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', lineHeight: 1.5 }}>
          {tool.desc}
        </p>
      </div>
      <button onClick={onClose} aria-label="Fechar"
        style={{
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.10)',
          width: 30, height: 30, borderRadius: 8,
          color: 'rgba(255,255,255,0.6)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18 M6 6l12 12" /></svg>
      </button>
    </div>
  );
}

function DrawerFooter({ children }) {
  return (
    <div style={{
      padding: '14px 24px',
      borderTop: '1px solid rgba(255,255,255,0.06)',
      display: 'flex', alignItems: 'center', gap: 10,
      background: 'rgba(10,14,39,0.5)',
    }}>{children}</div>
  );
}

function FlashSuccess({ msg, onDone }) {
  useEffectP(() => { const t = setTimeout(onDone, 2200); return () => clearTimeout(t); }, []);
  return (
    <div style={{
      margin: '0 24px 0', padding: '12px 14px',
      background: 'rgba(34,197,94,0.10)',
      border: '1px solid rgba(34,197,94,0.32)',
      borderRadius: 10,
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 0 60px -10px rgba(34,197,94,0.45)',
    }}>
      <span className="dot-pulse" />
      <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.85)' }}>{msg}</span>
    </div>
  );
}

// === Concrete panels ======================================
function PanelCriarCadastro({ onClose }) {
  const [f, setF] = useStateP({ nome: '', email: '', cpf: '', role: 'sac', nivel: 'pleno', equipe: 'atendimento' });
  const [done, setDone] = useStateP(false);
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12, flex: 1, overflow: 'auto' }}>
        {done && <FlashSuccess msg={`Cadastro de ${f.nome || 'colaborador'} criado · senha enviada por e-mail.`} onDone={() => setDone(false)} />}
        <PanelField label="Nome completo" value={f.nome} onChange={v => setF({ ...f, nome: v })} />
        <PanelField label="E-mail corporativo" value={f.email} onChange={v => setF({ ...f, email: v })} type="email" />
        <PanelField label="CPF" value={f.cpf} onChange={v => setF({ ...f, cpf: v })} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <PanelField label="Role" value={f.role} onChange={v => setF({ ...f, role: v })} options={[
            { value: 'sac', label: 'Atendente SAC' },
            { value: 'supervisor', label: 'Supervisor' },
            { value: 'gestor', label: 'Gestor' },
            { value: 'admin', label: 'Administrador' },
          ]} />
          <PanelField label="Nível" value={f.nivel} onChange={v => setF({ ...f, nivel: v })} options={[
            { value: 'junior', label: 'Júnior' },
            { value: 'pleno', label: 'Pleno' },
            { value: 'senior', label: 'Sênior' },
          ]} />
        </div>
        <PanelField label="Equipe" value={f.equipe} onChange={v => setF({ ...f, equipe: v })} options={[
          { value: 'atendimento', label: 'Atendimento — Geral' },
          { value: 'cobranca', label: 'Cobrança' },
          { value: 'churn', label: 'Retenção / Churn' },
          { value: 'tecnico', label: 'Suporte Técnico' },
        ]} />
        <Notice tone="info" text="O colaborador receberá um e-mail com link de criação de senha (válido por 24h)." />
      </div>
      <DrawerFooter>
        <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.35)' }}>
          AÇÃO REGISTRADA EM AUDITORIA
        </span>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>CANCELAR</button>
        <button className="btn-cta" onClick={() => { setDone(true); }}>
          Criar cadastro <span style={{ opacity: 0.6 }}>↵</span>
        </button>
      </DrawerFooter>
    </Fragment>
  );
}

function PanelResetSenha({ onClose }) {
  const [target, setTarget] = useStateP('');
  const [done, setDone] = useStateP(false);
  const matches = mockUserSearch(target);
  const [picked, setPicked] = useStateP(null);
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14, flex: 1, overflow: 'auto' }}>
        {done && <FlashSuccess msg={`Link de reset enviado para ${picked?.email}.`} onDone={() => { setDone(false); setPicked(null); setTarget(''); }} />}
        <PanelField label="E-mail, CPF ou ID do colaborador" value={target} onChange={setTarget} />
        {target && !picked && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {matches.map(u => (
              <button key={u.id} onClick={() => setPicked(u)} style={resultRow}>
                <div style={avatarMini}>{u.initials}</div>
                <div style={{ flex: 1, textAlign: 'left' }}>
                  <div style={{ fontSize: 13 }}>{u.name}</div>
                  <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.22em' }}>
                    {u.email} · {u.role}
                  </div>
                </div>
                <span className="kbd">↵</span>
              </button>
            ))}
            {!matches.length && <Empty msg="Nenhum colaborador encontrado." />}
          </div>
        )}
        {picked && (
          <div className="card card-topline" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={avatarMini}>{picked.initials}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{picked.name}</div>
                <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.22em' }}>
                  {picked.email}
                </div>
              </div>
              <button onClick={() => setPicked(null)} className="chip">TROCAR</button>
            </div>
            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <Meta k="Último acesso" v={picked.lastSeen} />
              <Meta k="Equipe" v={picked.team} />
              <Meta k="Status" v={<span style={{ color: 'var(--green)' }}>● Ativo</span>} />
              <Meta k="MFA" v={picked.mfa ? 'Habilitado' : <span style={{ color: 'var(--warning)' }}>Desabilitado</span>} />
            </div>
          </div>
        )}
        <Notice tone="warn" text="O link expira em 1 hora. Sessões ativas serão encerradas após o reset." />
      </div>
      <DrawerFooter>
        <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.35)' }}>
          / TLS 1.3 · LOGADO EM AUDITORIA
        </span>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>CANCELAR</button>
        <button className="btn-cta" disabled={!picked} onClick={() => setDone(true)}>
          Disparar reset <span style={{ opacity: 0.6 }}>↵</span>
        </button>
      </DrawerFooter>
    </Fragment>
  );
}

function PanelAlterarRole({ onClose }) {
  const [target, setTarget] = useStateP('Marina Coelho');
  const matches = mockUserSearch(target);
  const [picked, setPicked] = useStateP(matches[0] || null);
  const [role, setRole] = useStateP(picked?.role || 'sac');
  const [nivel, setNivel] = useStateP(picked?.level || 'pleno');
  const [done, setDone] = useStateP(false);
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14, flex: 1, overflow: 'auto' }}>
        {done && <FlashSuccess msg={`Permissões de ${picked?.name} atualizadas.`} onDone={() => setDone(false)} />}
        <PanelField label="Buscar colaborador" value={target} onChange={v => { setTarget(v); setPicked(null); }} />
        {picked && (
          <div className="card card-topline" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <div style={avatarMini}>{picked.initials}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{picked.name}</div>
                <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.22em' }}>
                  ATUAL · {picked.role.toUpperCase()} / {picked.level.toUpperCase()}
                </div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <PanelField label="Nova role" value={role} onChange={setRole} options={[
                { value: 'sac', label: 'Atendente SAC' },
                { value: 'supervisor', label: 'Supervisor' },
                { value: 'gestor', label: 'Gestor' },
                { value: 'admin', label: 'Administrador' },
              ]} />
              <PanelField label="Novo nível" value={nivel} onChange={setNivel} options={[
                { value: 'junior', label: 'Júnior' },
                { value: 'pleno', label: 'Pleno' },
                { value: 'senior', label: 'Sênior' },
              ]} />
            </div>
            <div style={{ marginTop: 12 }}>
              <DiffRow from={picked.role} to={role} label="ROLE" />
              <DiffRow from={picked.level} to={nivel} label="NÍVEL" />
            </div>
          </div>
        )}
        <Notice tone="warn" text="Alteração de role exige confirmação dupla. Será solicitado seu MFA na próxima etapa." />
      </div>
      <DrawerFooter>
        <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.35)' }}>
          REGISTRO #AUD-2026-{Math.floor(Math.random()*9000+1000)}
        </span>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>CANCELAR</button>
        <button className="btn-cta" disabled={!picked} onClick={() => setDone(true)}>
          Aplicar permissões
        </button>
      </DrawerFooter>
    </Fragment>
  );
}

function PanelDesatribuir({ onClose }) {
  const [target, setTarget] = useStateP('Lucas Pereira');
  const matches = mockUserSearch(target);
  const [picked, setPicked] = useStateP(matches[0] || null);
  const [convs] = useStateP(mockConversations(picked?.id));
  const [sel, setSel] = useStateP(new Set(convs.map(c => c.id)));
  const [done, setDone] = useStateP(false);
  const toggle = id => {
    const n = new Set(sel);
    n.has(id) ? n.delete(id) : n.add(id);
    setSel(n);
  };
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14, flex: 1, overflow: 'auto' }}>
        {done && <FlashSuccess msg={`${sel.size} conversas devolvidas à fila geral.`} onDone={() => setDone(false)} />}
        <PanelField label="Atendente" value={target} onChange={v => { setTarget(v); }} />
        {picked && (
          <Fragment>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 14px',
              background: 'rgba(245,158,11,0.06)',
              border: '1px solid rgba(245,158,11,0.20)',
              borderRadius: 10,
            }}>
              <div style={avatarMini}>{picked.initials}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5 }}>{picked.name}</div>
                <div className="mono" style={{ fontSize: 9.5, color: 'rgba(245,158,11,0.85)', letterSpacing: '0.22em' }}>
                  ● AUSENTE · 47 MIN · {convs.length} CONVERSAS
                </div>
              </div>
              <button className="chip">{sel.size} SELECIONADAS</button>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 280, overflow: 'auto', paddingRight: 4 }}>
              {convs.map(c => (
                <button key={c.id} onClick={() => toggle(c.id)}
                        style={{ ...resultRow, opacity: sel.has(c.id) ? 1 : 0.5 }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: 4,
                    border: '1px solid rgba(34,197,94,0.4)',
                    background: sel.has(c.id) ? 'var(--green)' : 'transparent',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#06170d',
                  }}>
                    {sel.has(c.id) && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><path d="M20 6 9 17l-5-5" /></svg>}
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>
                    <div style={{ fontSize: 12.5 }}>{c.client}</div>
                    <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.22em' }}>
                      #{c.id} · {c.channel} · ABERTA HÁ {c.age}
                    </div>
                  </div>
                  <span className={`chip ${c.sla === 'risk' ? 'is-warn' : c.sla === 'breached' ? 'is-danger' : ''}`}>
                    SLA {c.sla === 'ok' ? 'OK' : c.sla === 'risk' ? 'RISCO' : 'ESTOURADO'}
                  </span>
                </button>
              ))}
            </div>

            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
              padding: 14, background: 'rgba(255,255,255,0.02)',
              border: '1px dashed rgba(255,255,255,0.10)', borderRadius: 10,
            }}>
              <PanelField label="Destino" value="fila-geral" onChange={()=>{}} options={[
                { value: 'fila-geral', label: 'Fila geral (auto-distribuir)' },
                { value: 'supervisor', label: 'Supervisor de plantão' },
                { value: 'manter', label: 'Manter sem atribuição' },
              ]} />
              <PanelField label="Notificar cliente" value="silent" onChange={()=>{}} options={[
                { value: 'silent', label: 'Não notificar' },
                { value: 'transfer', label: 'Mensagem padrão de transferência' },
              ]} />
            </div>
          </Fragment>
        )}
      </div>
      <DrawerFooter>
        <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.35)' }}>
          AÇÃO REVERSÍVEL EM 5 MIN
        </span>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>CANCELAR</button>
        <button className="btn-cta" disabled={!sel.size} onClick={() => setDone(true)}>
          Desatribuir {sel.size} conversa{sel.size === 1 ? '' : 's'}
        </button>
      </DrawerFooter>
    </Fragment>
  );
}

function PanelAtribAuto({ onClose }) {
  const [enabled, setEnabled] = useStateP(true);
  const [strategy, setStrategy] = useStateP('round-robin');
  const [maxConv, setMaxConv] = useStateP(8);
  const [skill, setSkill] = useStateP(true);
  const [offHours, setOffHours] = useStateP(false);
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18, flex: 1, overflow: 'auto' }}>
        <Toggle label="Atribuição automática ativa" sub="Distribui conversas novas conforme regras abaixo." value={enabled} onChange={setEnabled} />

        <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.32em', marginTop: 4 }}>
          / ESTRATÉGIA
        </div>
        <PanelField label="Algoritmo" value={strategy} onChange={setStrategy} options={[
          { value: 'round-robin', label: 'Round-robin (rotativo)' },
          { value: 'least-busy', label: 'Menor carga (least-busy)' },
          { value: 'skill', label: 'Por skill / fila' },
          { value: 'priority', label: 'Por prioridade do cliente' },
        ]} />
        <SliderRow label="Máx. conversas simultâneas por atendente" value={maxConv} onChange={setMaxConv} min={1} max={20} />

        <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.32em', marginTop: 4 }}>
          / REGRAS
        </div>
        <Toggle label="Respeitar skills do atendente" sub="Conversas só caem em quem tem o skill da fila." value={skill} onChange={setSkill} />
        <Toggle label="Encaminhar fora do horário" sub="Direciona para plantão noturno (22h–06h)." value={offHours} onChange={setOffHours} />

        <Notice tone="info" text="Mudanças aplicam para conversas novas. Conversas já atribuídas permanecem com o dono atual." />
      </div>
      <DrawerFooter>
        <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.35)' }}>
          ÚLTIMA EDIÇÃO · 02/05 14:18 · M. COELHO
        </span>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>FECHAR</button>
        <button className="btn-cta">Salvar configuração</button>
      </DrawerFooter>
    </Fragment>
  );
}

function PanelGenerica({ tool, onClose }) {
  return (
    <Fragment>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14, flex: 1, overflow: 'auto' }}>
        <div className="card card-topline" style={{ padding: 18 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--green)', letterSpacing: '0.32em' }}>
            / EM CONSTRUÇÃO
          </div>
          <p style={{ marginTop: 8, fontSize: 13, color: 'rgba(255,255,255,0.7)', lineHeight: 1.55 }}>
            Esta ferramenta abrirá um fluxo dedicado com formulários, prévia e confirmação dupla quando aplicável.
            O comportamento detalhado pode ser definido junto com o time de operações.
          </p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Meta k="Categoria" v={tool.cat.toUpperCase()} />
          <Meta k="Tag" v={tool.tag} />
          <Meta k="Uso médio" v={tool.uses} />
          <Meta k="Risco" v={tool.kind === 'danger' ? <span style={{ color: 'var(--danger)' }}>Alto</span> : tool.kind === 'warn' ? <span style={{ color: 'var(--warning)' }}>Médio</span> : 'Baixo'} />
        </div>
      </div>
      <DrawerFooter>
        <span style={{ flex: 1 }} />
        <button className="chip" onClick={onClose}>FECHAR</button>
      </DrawerFooter>
    </Fragment>
  );
}

// === Helpers ==============================================
const resultRow = {
  display: 'flex', alignItems: 'center', gap: 12,
  padding: '10px 12px',
  background: 'rgba(255,255,255,0.03)',
  border: '1px solid rgba(255,255,255,0.07)',
  borderRadius: 10,
  textAlign: 'left',
  transition: 'all 180ms ease',
};
const avatarMini = {
  width: 28, height: 28, borderRadius: '50%',
  background: 'linear-gradient(135deg, #22c55e, #16a34a)',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  fontSize: 11, fontWeight: 600, color: '#06170d',
};

function Meta({ k, v }) {
  return (
    <div style={{
      padding: 10, borderRadius: 8,
      background: 'rgba(255,255,255,0.025)',
      border: '1px solid rgba(255,255,255,0.06)',
    }}>
      <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.22em' }}>{k}</div>
      <div style={{ fontSize: 12.5, marginTop: 4 }}>{v}</div>
    </div>
  );
}

function Notice({ tone = 'info', text }) {
  const c = tone === 'warn' ? 'rgba(245,158,11,' : tone === 'danger' ? 'rgba(239,68,68,' : 'rgba(59,130,246,';
  return (
    <div style={{
      padding: '10px 12px', borderRadius: 8,
      background: c + '0.06)', border: '1px solid ' + c + '0.20)',
      display: 'flex', alignItems: 'flex-start', gap: 10,
      fontSize: 12, color: 'rgba(255,255,255,0.75)', lineHeight: 1.5,
    }}>
      <span style={{ color: c + '1)', marginTop: 2 }}>●</span>
      <span>{text}</span>
    </div>
  );
}

function Empty({ msg }) {
  return (
    <div style={{
      padding: '18px 14px', borderRadius: 8,
      background: 'rgba(255,255,255,0.02)',
      border: '1px dashed rgba(255,255,255,0.10)',
      fontSize: 12, color: 'rgba(255,255,255,0.5)',
      textAlign: 'center',
    }}>{msg}</div>
  );
}

function DiffRow({ label, from, to }) {
  const same = from === to;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '6px 10px', borderRadius: 6,
      background: same ? 'transparent' : 'rgba(34,197,94,0.05)',
      marginTop: 4,
    }}>
      <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', minWidth: 50 }}>{label}</span>
      <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', textTransform: 'capitalize' }}>{from}</span>
      <span style={{ color: same ? 'rgba(255,255,255,0.3)' : 'var(--green)' }}>→</span>
      <span style={{ fontSize: 12, color: same ? 'rgba(255,255,255,0.55)' : 'var(--green)', textTransform: 'capitalize', fontWeight: 500 }}>{to}</span>
      {!same && <span className="mono" style={{ marginLeft: 'auto', fontSize: 9, color: 'var(--green)', letterSpacing: '0.22em' }}>ALTERADO</span>}
    </div>
  );
}

function Toggle({ label, sub, value, onChange }) {
  return (
    <button onClick={() => onChange(!value)} style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '12px 14px', borderRadius: 10,
      background: 'rgba(255,255,255,0.025)',
      border: '1px solid ' + (value ? 'rgba(34,197,94,0.30)' : 'rgba(255,255,255,0.08)'),
      textAlign: 'left',
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{
        width: 36, height: 20, borderRadius: 999,
        background: value ? 'linear-gradient(180deg, #22c55e, #16a34a)' : 'rgba(255,255,255,0.10)',
        position: 'relative', transition: 'all 200ms ease',
        boxShadow: value ? '0 0 20px -4px rgba(34,197,94,0.6)' : 'none',
      }}>
        <div style={{
          position: 'absolute', top: 2, left: value ? 18 : 2,
          width: 16, height: 16, borderRadius: '50%',
          background: '#fff', transition: 'all 200ms ease',
        }} />
      </div>
    </button>
  );
}

function SliderRow({ label, value, onChange, min, max }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
        <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.22em' }}>{label}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--green)' }}>{value}</span>
      </div>
      <input type="range" min={min} max={max} value={value}
             onChange={e => onChange(+e.target.value)}
             style={{ width: '100%', accentColor: '#22c55e' }} />
    </div>
  );
}

function mockUserSearch(q) {
  const all = [
    { id: 'u-1042', name: 'Marina Coelho', initials: 'MC', email: 'marina.coelho@igreen.com', role: 'supervisor', level: 'senior', team: 'Atendimento', lastSeen: 'há 12 min', mfa: true },
    { id: 'u-1118', name: 'Lucas Pereira',  initials: 'LP', email: 'lucas.pereira@igreen.com',  role: 'sac',         level: 'pleno',  team: 'Cobrança',    lastSeen: 'há 2h',     mfa: false },
    { id: 'u-1207', name: 'Ana Beatriz',     initials: 'AB', email: 'ana.beatriz@igreen.com',    role: 'sac',         level: 'junior', team: 'Atendimento', lastSeen: 'há 45 min', mfa: true },
    { id: 'u-1311', name: 'Renato Lima',     initials: 'RL', email: 'renato.lima@igreen.com',    role: 'gestor',      level: 'senior', team: 'Operações',   lastSeen: 'agora',     mfa: true },
  ];
  if (!q) return all;
  const s = q.toLowerCase();
  return all.filter(u => u.name.toLowerCase().includes(s) || u.email.toLowerCase().includes(s) || u.id.includes(s));
}

function mockConversations(uid) {
  return [
    { id: '48291', client: 'Carolina Mendes',   channel: 'WHATSAPP', age: '38min', sla: 'risk' },
    { id: '48304', client: 'Eduardo Tavares',   channel: 'CHAT WEB', age: '1h12',  sla: 'breached' },
    { id: '48317', client: 'Patricia Lopes',    channel: 'WHATSAPP', age: '22min', sla: 'ok' },
    { id: '48322', client: 'Henrique Sá',       channel: 'E-MAIL',   age: '4h08',  sla: 'breached' },
    { id: '48330', client: 'Beatriz Andrade',   channel: 'WHATSAPP', age: '14min', sla: 'ok' },
  ];
}

window.PANELS = {
  'gs-cad-criar': PanelCriarCadastro,
  'gs-cad-reset': PanelResetSenha,
  'gs-cad-role':  PanelAlterarRole,
  'gs-cad-nivel': PanelAlterarRole,
};
window.PanelGenerica = PanelGenerica;
window.DrawerHeader = DrawerHeader;
