// Tela: Meu Perfil

/* ── Modal: Adicionar Conexão ────────────────────────────── */
function ConexoesModal({ onClose }) {
  const toast = useToast();
  const plataformas = [
    { color: 'blue',  label: 'Slack',          desc: 'Notificações e alertas',     icon: 'SL' },
    { color: 'pink',  label: 'Zapier',          desc: 'Automações personalizadas',  icon: 'ZP' },
    { color: 'lav',   label: 'GitHub',          desc: 'Rastrear issues e commits',  icon: 'GH' },
    { color: 'mint',  label: 'Google Calendar', desc: 'Sincronizar agenda',         icon: 'GC' },
    { color: 'yellow',label: 'Pipedrive',       desc: 'Migrar histórico de CRM',    icon: 'PD' },
  ];
  return (
    <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal-box" style={{width: 400}}>
        <div className="modal-head">
          <div className="modal-title">Adicionar conexão</div>
          <button className="icon-btn" onClick={onClose} style={{marginLeft:'auto'}}>✕</button>
        </div>
        <div style={{fontSize:12.5, color:'var(--ink-soft)', marginBottom:12}}>
          Escolha uma plataforma para integrar ao seu perfil:
        </div>
        <div className="col" style={{gap:8}}>
          {plataformas.map(p => (
            <div key={p.label}
              onClick={() => { toast(`Conectando com ${p.label}…`); onClose(); }}
              style={{
                display:'flex', alignItems:'center', gap:12, padding:'10px 12px',
                borderRadius:10, background:'var(--bg-soft)', cursor:'pointer',
                transition:'background .15s',
              }}
              onMouseEnter={e => e.currentTarget.style.background='var(--acc-blue-faint,oklch(0.97 0.02 250))'}
              onMouseLeave={e => e.currentTarget.style.background='var(--bg-soft)'}
            >
              <div style={{
                width:36, height:36, borderRadius:10, flexShrink:0,
                background:`var(--acc-${p.color})`,
                display:'grid', placeItems:'center',
                fontSize:11, fontWeight:700, letterSpacing:'.04em',
                color:'oklch(0.22 0.04 250)',
              }}>{p.icon}</div>
              <div className="col" style={{gap:2}}>
                <div style={{fontSize:13, fontWeight:600}}>{p.label}</div>
                <div style={{fontSize:11.5, color:'var(--ink-soft)'}}>{p.desc}</div>
              </div>
              <span style={{marginLeft:'auto', fontSize:18, color:'var(--ink-faint)'}}>›</span>
            </div>
          ))}
        </div>
        <button className="btn-sec" onClick={onClose} style={{width:'100%', marginTop:14}}>Fechar</button>
      </div>
    </div>
  );
}

/* ── Modal: Trocar Senha ─────────────────────────────────── */
function TrocarSenhaModal({ onClose }) {
  const [atual, setAtual] = React.useState('');
  const [nova, setNova] = React.useState('');
  const [conf, setConf] = React.useState('');
  const toast = useToast();
  const valid = atual.length >= 6 && nova.length >= 8 && nova === conf;
  const submit = () => {
    if (!valid) return;
    toast('Senha atualizada com sucesso ✓');
    onClose();
  };
  const strength = nova.length === 0 ? 0 : nova.length < 8 ? 1 : /[A-Z]/.test(nova) && /[0-9]/.test(nova) ? 3 : 2;
  const strengthLabel = ['', 'Fraca', 'Média', 'Forte'][strength];
  const strengthColor = ['', 'var(--danger)', 'oklch(0.68 0.18 70)', 'var(--ok)'][strength];
  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="card modal-card" onClick={e => e.stopPropagation()} style={{width: 440}}>
        <div className="modal-head">
          <div><div className="modal-title">Trocar <em>senha</em></div><div className="modal-sub muted">Mínimo 8 caracteres · maiúsculas e números</div></div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>
        <div className="form-grid" style={{gridTemplateColumns:'1fr'}}>
          <div className="field"><label className="field-lbl">Senha atual</label>
            <input className="ezz-input" type="password" placeholder="••••••••" value={atual} onChange={e => setAtual(e.target.value)} autoFocus /></div>
          <div className="field"><label className="field-lbl">Nova senha</label>
            <input className="ezz-input" type="password" placeholder="••••••••" value={nova} onChange={e => setNova(e.target.value)} />
            {nova.length > 0 && <div style={{display:'flex',gap:4,marginTop:6,alignItems:'center'}}>
              {[1,2,3].map(i => <div key={i} style={{flex:1,height:4,borderRadius:4,background:i<=strength?strengthColor:'oklch(0.93 0.01 255)',transition:'background .2s'}}/>)}
              <span style={{fontSize:11,fontWeight:600,color:strengthColor,marginLeft:4,minWidth:32}}>{strengthLabel}</span>
            </div>}
          </div>
          <div className="field"><label className="field-lbl">Confirmar nova senha</label>
            <input className="ezz-input" type="password" placeholder="••••••••" value={conf} onChange={e => setConf(e.target.value)}
              style={{borderColor: conf.length > 0 && conf !== nova ? 'var(--danger)' : ''}} />
            {conf.length > 0 && conf !== nova && <div style={{fontSize:11,color:'var(--danger)',marginTop:4}}>As senhas não coincidem</div>}
          </div>
        </div>
        <div className="modal-actions">
          <button className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn-primary" onClick={submit} disabled={!valid} style={{opacity: valid ? 1 : 0.5}}>{ICN.check} Atualizar senha</button>
        </div>
      </div>
    </div>
  );
}

/* ── Modal: Sessões Ativas ───────────────────────────────── */
function SessoesModal({ onClose }) {
  const [sessions, setSessions] = React.useState([
    { id: 1, device: 'Chrome · macOS', local: 'São Paulo, SP', time: 'Agora', current: true },
    { id: 2, device: 'Safari · iPhone 15', local: 'São Paulo, SP', time: 'há 2 horas' },
    { id: 3, device: 'Chrome · Windows 11', local: 'Campinas, SP', time: 'há 1 dia' },
  ]);
  const toast = useToast();
  const encerrar = (id) => { setSessions(s => s.filter(x => x.id !== id)); toast('Sessão encerrada ✓'); };
  const encerrarTodas = () => { setSessions(s => s.filter(x => x.current)); toast('Todas as outras sessões encerradas ✓'); };
  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="card modal-card" onClick={e => e.stopPropagation()} style={{width: 480}}>
        <div className="modal-head">
          <div><div className="modal-title">Sessões <em>ativas</em></div><div className="modal-sub muted">{sessions.length} dispositivo{sessions.length !== 1 ? 's' : ''} conectado{sessions.length !== 1 ? 's' : ''}</div></div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>
        <div className="col" style={{gap:0}}>
          {sessions.map((s, i) => (
            <div key={s.id} style={{display:'flex',alignItems:'center',gap:14,padding:'14px 0',borderBottom: i<sessions.length-1 ? '1px solid oklch(0.93 0.01 255)' : 0}}>
              <div style={{width:40,height:40,borderRadius:12,background:'oklch(0.96 0.012 250)',color:'var(--ink-soft)',display:'grid',placeItems:'center',flexShrink:0}}>
                {s.device.includes('iPhone') ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>
                  : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>}
              </div>
              <div className="col" style={{flex:1,minWidth:0}}>
                <div style={{fontSize:13,fontWeight:600}}>{s.device} {s.current && <span className="pill pill-mint" style={{fontSize:9,marginLeft:4}}>Esta sessão</span>}</div>
                <div className="muted" style={{fontSize:11.5,marginTop:2}}>{s.local} · {s.time}</div>
              </div>
              {!s.current && <button className="btn-ghost btn-sm" style={{color:'var(--danger)',fontSize:11}} onClick={() => encerrar(s.id)}>Encerrar</button>}
            </div>
          ))}
        </div>
        <div className="modal-actions">
          <button className="btn-ghost" onClick={onClose}>Fechar</button>
          {sessions.length > 1 && <button className="btn-primary" onClick={encerrarTodas}>Encerrar outras sessões</button>}
        </div>
      </div>
    </div>
  );
}

function Perfil({ onBack }) {
  const [editing, setEditing] = React.useState(false);
  const [showSenha, setShowSenha] = React.useState(false);
  const [showSessoes, setShowSessoes] = React.useState(false);
  const [editingPrefs, setEditingPrefs] = React.useState(false);
  const [showConexoes, setShowConexoes] = React.useState(false);
  const [avatar, setAvatar] = React.useState('https://i.pravatar.cc/240?img=47');
  const avatarRef = React.useRef(null);
  const toast = useToast();

  const handleAvatarFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    setAvatar(URL.createObjectURL(file));
    toast('Foto atualizada ✓');
  };

  const [vals, setVals] = React.useState({
    nome: 'Letícia Andrade Borges',
    cargo: 'Head Comercial',
    dept: 'Vendas',
    bio: 'Lidero o time comercial da Ezza desde 2023. Foco em vendas consultivas para indústria e construção.',
    email: 'leticia.andrade@ezza.com.br',
    emailAlt: 'leticia.borges@gmail.com',
    tel: '+55 11 9 9412-7782',
    ramal: '2204',
  });
  const [saved, setSaved] = React.useState({...vals});
  const [savedAvatar, setSavedAvatar] = React.useState(avatar);

  const save = () => { setSaved({...vals}); setSavedAvatar(avatar); setEditing(false); toast('Perfil salvo com sucesso!'); };
  const revert = () => { setVals({...saved}); setAvatar(savedAvatar); setEditing(false); };
  const setV = (key) => (e) => setVals(prev => ({...prev, [key]: e.target.value}));

  return (
    <>
      {showSenha    && <TrocarSenhaModal onClose={() => setShowSenha(false)} />}
      {showSessoes  && <SessoesModal onClose={() => setShowSessoes(false)} />}
      {showConexoes && <ConexoesModal onClose={() => setShowConexoes(false)} />}
      <PageHead
        title={<>Meu <em>perfil</em></>}
        subtitle="Dados pessoais, preferências e segurança"
        back onBack={onBack}
        right={
          <div className="row">
            {editing
              ? <><button className="btn-ghost" onClick={revert}>Desfazer</button>
                  <button className="btn-primary" onClick={save}>{ICN.check} Salvar alterações</button></>
              : <button className="btn-primary" onClick={() => setEditing(true)}>{ICN.edit} Editar perfil</button>
            }
          </div>
        }
      />

      <div className="prf-grid">
        <div className="col" style={{gap: 14}}>
          <div className="card">
            <div className="card-head">
              <div className="card-title">Foto e identidade</div>
              <MoreMenu items={[
                { ic: ICN.upload, label: 'Trocar foto',  onClick: () => avatarRef.current?.click() },
                { ic: ICN.trash,  label: 'Remover foto', danger: true, onClick: () => { setAvatar('https://i.pravatar.cc/240?img=47'); toast('Foto removida'); } },
              ]} />
            </div>
            <input ref={avatarRef} type="file" accept="image/*" style={{display:'none'}} onChange={e => handleAvatarFile(e.target.files?.[0])} />
            <div className="prf-avwrap">
              <div className="prf-avbig">
                <img src={avatar} alt="" />
                <button className="prf-camera" title="Trocar foto" onClick={() => avatarRef.current?.click()}>{ICN.edit}</button>
              </div>
              <div className="col" style={{flex:1, gap: 14}}>
                <FieldRow label="Nome completo" value={vals.nome} editing={editing} onChange={setV('nome')} onActivateEdit={() => setEditing(true)} />
                <div className="row" style={{gap: 12}}>
                  <FieldRow label="Cargo" value={vals.cargo} editing={editing} onChange={setV('cargo')} onActivateEdit={() => setEditing(true)} />
                  <FieldRow label="Departamento" value={vals.dept} editing={editing} onChange={setV('dept')} onActivateEdit={() => setEditing(true)} />
                </div>
                <FieldRow label="Bio" textarea value={vals.bio} editing={editing} onChange={setV('bio')} onActivateEdit={() => setEditing(true)} />
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Contato</div>
              <span className="pill pill-mint">Verificado</span>
            </div>
            <div className="form-grid">
              <FieldRow label="E-mail principal" value={vals.email} badge="Primário" editing={editing} onChange={setV('email')} />
              <FieldRow label="E-mail alternativo" value={vals.emailAlt} editing={editing} onChange={setV('emailAlt')} />
              <FieldRow label="Telefone / WhatsApp" value={vals.tel} editing={editing} onChange={setV('tel')} />
              <FieldRow label="Ramal" value={vals.ramal} editing={editing} onChange={setV('ramal')} />
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Preferências</div>
              <ActionBtn icon={ICN.edit} title="Editar preferências" onClick={() => setEditingPrefs(e => !e)} />
            </div>
            {editingPrefs && <div className="row" style={{gap:8,marginBottom:12}}>
              <span className="pill pill-lav" style={{fontSize:10}}>Editando preferências</span>
              <button className="btn-ghost btn-sm" onClick={() => { setEditingPrefs(false); toast('Preferências salvas ✓'); }}>{ICN.check} Salvar</button>
            </div>}
            <div className="prf-prefs">
              <PrefRow label="Idioma" value="Português (Brasil)" editing={editingPrefs} options={['Português (Brasil)','English (US)','Español']} />
              <PrefRow label="Fuso horário" value="America/São_Paulo · GMT-3" editing={editingPrefs} options={['America/São_Paulo · GMT-3','America/Manaus · GMT-4','America/Fortaleza · GMT-3','UTC']} />
              <PrefRow label="Formato de moeda" value="R$ 1.000,00 (BRL)" editing={editingPrefs} options={['R$ 1.000,00 (BRL)','$ 1,000.00 (USD)','€ 1.000,00 (EUR)']} />
              <PrefRow label="Primeiro dia da semana" value="Segunda-feira" editing={editingPrefs} options={['Segunda-feira','Domingo']} />
              <PrefRow label="Densidade da interface" value="Confortável" editing={editingPrefs} options={['Confortável','Compacto','Espaçoso']} />
            </div>
          </div>
        </div>

        <div className="col" style={{gap: 14}}>
          <div className="card prf-stat-card">
            <div className="prf-stat-header">
              <div className="prf-stat-title">Atividade desta semana</div>
              <span className="prf-stat-badge">↑ +12% vs semana anterior</span>
            </div>
            <div className="prf-stat-grid">
              <div className="prf-stat-item prf-stat-item-hl">
                <div className="prf-stat-val money">R$ 482k</div>
                <div className="prf-stat-lbl">Receita fechada</div>
                <div className="prf-stat-delta">↑ +R$ 48k</div>
              </div>
              <div className="prf-stat-item">
                <div className="prf-stat-val">14</div>
                <div className="prf-stat-lbl">Negócios ativos</div>
                <div className="prf-stat-delta">↑ +3</div>
              </div>
              <div className="prf-stat-item">
                <div className="prf-stat-val">36</div>
                <div className="prf-stat-lbl">Reuniões</div>
                <div className="prf-stat-delta">→ igual</div>
              </div>
              <div className="prf-stat-item">
                <div className="prf-stat-val">128</div>
                <div className="prf-stat-lbl">Mensagens</div>
                <div className="prf-stat-delta">↑ +22</div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Segurança</div>
              <MoreMenu items={[
                { ic: ICN.refresh, label: 'Trocar senha agora', onClick: () => setShowSenha(true) },
                { ic: ICN.bolt,    label: 'Reconfigurar 2FA',  toast: 'Redirecionando para app autenticador…' },
                { ic: ICN.users,   label: 'Encerrar sessões',  onClick: () => setShowSessoes(true) },
              ]} />
            </div>
            <SecRow icon={ICN.refresh}   icColor="blue"   label="Alterar senha"            hint="Última troca há 47 dias"          onClick={() => setShowSenha(true)} />
            <SecRow icon={ICN.bolt}      icColor="mint"   label="Autenticação em 2 etapas" hint="App autenticador ativo"            pill="Ativo" pillColor="mint" />
            <SecRow icon={ICN.users}     icColor="lav"    label="Sessões ativas"           hint="3 dispositivos conectados"        onClick={() => setShowSessoes(true)} />
            <SecRow icon={ICN.download}  icColor="yellow" label="Exportar meus dados"      hint="Baixar seus dados em JSON"        onClick={() => {
              const data = JSON.stringify({ nome: vals.nome, email: vals.email, exportadoEm: new Date().toISOString() }, null, 2);
              const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([data], {type:'application/json'})), download: 'meus-dados-ezza.json' });
              a.click(); URL.revokeObjectURL(a.href); toast('Dados exportados ✓');
            }} />
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Conexões sociais</div>
              <ActionBtn icon={ICN.plus} title="Adicionar conexão" onClick={() => setShowConexoes(true)} />
            </div>
            <ConRow logo="linkedin"  label="LinkedIn"          handle="linkedin.com/in/leticia-andrade" connected />
            <ConRow logo="google"    label="Google Workspace"  handle="leticia@ezza.com.br"             connected />
            <ConRow logo="whatsapp"  label="WhatsApp Business" handle="+55 11 9 9412-7782"             connected />
            <ConRow logo="instagram" label="Instagram"         handle="@leticia.andrade" />
          </div>
        </div>
      </div>

      <style>{`
        .prf-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 14px; align-items: start; }

        .prf-avwrap { display: flex; gap: 22px; align-items: flex-start; }
        .prf-avbig { position: relative; flex-shrink: 0; }
        .prf-avbig img { width: 128px; height: 128px; border-radius: 50%; object-fit: cover; border: 4px solid white; box-shadow: 0 12px 28px -12px rgba(20,30,60,.25); }
        .prf-camera {
          position: absolute; bottom: 6px; right: 6px;
          width: 36px; height: 36px; border-radius: 50%;
          background: var(--black); color: white;
          border: 3px solid white; cursor: default;
          display: grid; place-items: center;
          font-family: inherit;
        }

        .fld { display: flex; flex-direction: column; gap: 6px; flex: 1; min-width: 0; }
        .fld-lbl { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 700; color: var(--ink-muted); display: flex; align-items: center; gap: 8px; }
        .fld-badge { font-size: 9.5px; background: var(--black); color: white; padding: 2px 7px; border-radius: 999px; letter-spacing: 0.06em; }
        .fld-val {
          background: oklch(0.97 0.01 250);
          border: 0.5px solid oklch(0.90 0.01 250);
          border-radius: 12px;
          padding: 10px 14px;
          font-size: 13.5px;
          color: var(--ink);
          min-height: 22px;
        }
        .fld-val-click {
          cursor: pointer;
          display: flex; align-items: center; justify-content: space-between; gap: 8px;
          transition: background .15s, border-color .15s;
        }
        .fld-val-click:hover {
          background: oklch(0.94 0.015 250);
          border-color: oklch(0.82 0.04 250);
        }
        .fld-edit-ic {
          opacity: 0;
          color: var(--ink-muted);
          flex-shrink: 0;
          transition: opacity .15s;
          display: flex;
        }
        .fld-edit-ic svg { width: 13px; height: 13px; }
        .fld-val-click:hover .fld-edit-ic { opacity: 1; }
        .fld-val-area { min-height: 56px; line-height: 1.5; }

        .prf-prefs > * + * { border-top: 1px solid oklch(0.93 0.01 255); }
        .pref-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; }
        .pref-lbl { font-size: 12.5px; color: var(--ink-muted); }
        .pref-val { font-size: 13px; font-weight: 600; }
        .pref-val + .mini-btn { margin-left: 8px; }

        /* ── Stats ── */
        .prf-stat-card { background: linear-gradient(135deg, oklch(0.94 0.06 250) 0%, oklch(0.94 0.06 295) 100%) !important; border: 0 !important; }
        .prf-stat-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
        .prf-stat-title { font-size: 11px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: oklch(0.34 0.16 270); }
        .prf-stat-badge { font-size: 10px; font-weight: 700; background: oklch(0.88 0.10 155); color: oklch(0.32 0.12 155); padding: 3px 8px; border-radius: 99px; }
        .prf-stat-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
        .prf-stat-item { background: white; border-radius: 14px; padding: 14px 16px; }
        .prf-stat-item-hl { background: oklch(0.22 0.01 255); }
        .prf-stat-item-hl .prf-stat-val { color: white; }
        .prf-stat-item-hl .prf-stat-lbl { color: oklch(0.72 0.01 255); }
        .prf-stat-item-hl .prf-stat-delta { color: oklch(0.72 0.09 155); }
        .prf-stat-val { font-size: 26px; font-weight: 800; letter-spacing: -0.03em; color: var(--ink); line-height: 1; margin-bottom: 4px; }
        .prf-stat-lbl { font-size: 11px; color: var(--ink-muted); font-weight: 500; }
        .prf-stat-delta { font-size: 10.5px; font-weight: 700; color: oklch(0.42 0.13 155); margin-top: 6px; }

        /* ── Segurança ── */
        .sec-row { display: flex; align-items: center; gap: 14px; padding: 11px 8px; border-radius: 10px; margin: 0 -8px; border-bottom: 1px solid oklch(0.93 0.01 255); transition: background .15s; }
        .sec-row:last-child { border-bottom: 0; }
        .sec-ic { width: 38px; height: 38px; border-radius: 12px; background: oklch(0.96 0.012 250); color: var(--ink-soft); display: grid; place-items: center; flex-shrink: 0; }
        .sec-ic svg { width: 16px; height: 16px; }
        .sec-lbl { font-size: 13px; font-weight: 600; }
        .sec-hint { font-size: 11.5px; color: var(--ink-muted); margin-top: 2px; }

        /* ── Conexões ── */
        .con-row { display: flex; align-items: center; gap: 14px; padding: 10px 0; border-bottom: 1px solid oklch(0.93 0.01 255); }
        .con-row:last-child { border-bottom: 0; }
        .con-logo-wrap { width: 42px; height: 42px; border-radius: 14px; display: grid; place-items: center; flex-shrink: 0; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
        .con-name { font-size: 13.5px; font-weight: 600; }
        .con-handle { font-size: 11.5px; color: var(--ink-muted); margin-top: 2px; font-family: var(--font-mono); }
        .con-connected-wrap { display: flex; align-items: center; gap: 6px; background: oklch(0.94 0.07 155); border-radius: 99px; padding: 5px 10px 5px 8px; }
        .con-status-dot { width: 7px; height: 7px; border-radius: 50%; background: oklch(0.52 0.16 155); flex-shrink: 0; }
        .con-connected-lbl { font-size: 11px; font-weight: 700; color: oklch(0.32 0.12 155); }
        .con-disconnect { background: none; border: none; cursor: pointer; color: oklch(0.52 0.08 155); font-size: 10px; font-weight: 800; line-height: 1; padding: 0; margin-left: 2px; }
        .con-disconnect:hover { color: oklch(0.38 0.15 18); }
      `}</style>
    </>
  );
}

function FieldRow({ label, value, badge, textarea, editing, onChange, onActivateEdit }) {
  return (
    <div className="fld">
      <div className="fld-lbl">
        {label}
        {badge && <span className="fld-badge">{badge}</span>}
      </div>
      {editing
        ? textarea
          ? <textarea className="ezz-input" rows="3" value={value} onChange={onChange} autoFocus
              style={{resize:'vertical', lineHeight:1.5, fontFamily:'inherit', fontSize:13.5}} />
          : <input className="ezz-input" value={value} onChange={onChange} style={{fontSize:13.5}} />
        : <div
            className={`fld-val fld-val-click ${textarea ? 'fld-val-area' : ''}`}
            onClick={onActivateEdit}
            title="Clique para editar"
          >
            {value}
            <span className="fld-edit-ic">{ICN.edit}</span>
          </div>
      }
    </div>
  );
}
function PrefRow({ label, value, editing, options }) {
  const [val, setVal] = React.useState(value);
  return (
    <div className="pref-row">
      <span className="pref-lbl">{label}</span>
      {editing && options
        ? <select className="ezz-input" value={val} onChange={e => setVal(e.target.value)}
            style={{appearance:'auto', fontSize:12.5, padding:'6px 10px', height:32, fontFamily:'inherit'}}>
            {options.map(o => <option key={o}>{o}</option>)}
          </select>
        : <div className="row">
            <span className="pref-val">{val}</span>
            <span className="muted">{ICN.chevron}</span>
          </div>
      }
    </div>
  );
}
function SecRow({ icon, icColor, label, hint, pill, pillColor, onClick }) {
  const bgMap = { blue:'oklch(0.93 0.06 250)', mint:'oklch(0.92 0.07 160)', lav:'oklch(0.93 0.06 295)', yellow:'oklch(0.94 0.08 80)', pink:'oklch(0.93 0.06 18)' };
  const fgMap = { blue:'oklch(0.38 0.16 250)', mint:'oklch(0.34 0.14 160)', lav:'oklch(0.38 0.14 295)', yellow:'oklch(0.40 0.14 80)', pink:'oklch(0.40 0.16 18)' };
  return (
    <div className="sec-row" onClick={onClick} style={{cursor: onClick ? 'pointer' : 'default'}}
      onMouseEnter={e => { if(onClick) e.currentTarget.style.background='oklch(0.97 0.01 250)'; e.currentTarget.style.borderRadius='12px'; }}
      onMouseLeave={e => { e.currentTarget.style.background=''; e.currentTarget.style.borderRadius=''; }}>
      <div className="sec-ic" style={icColor ? {background: bgMap[icColor], color: fgMap[icColor]} : {}}>{icon}</div>
      <div className="col" style={{flex:1, minWidth:0}}>
        <div className="sec-lbl">{label}</div>
        <div className="sec-hint">{hint}</div>
      </div>
      {pill
        ? <span className={`pill pill-${pillColor}`} style={{fontSize:10, fontWeight:700}}>{pill}</span>
        : onClick && <span className="muted" style={{fontSize:13}}>{ICN.arrowRight}</span>}
    </div>
  );
}

/* Logos SVG inline das redes sociais */
function BrandLogo({ logo }) {
  if (logo === 'linkedin') return (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="#0A66C2"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
  );
  if (logo === 'google') return (
    <svg viewBox="0 0 24 24" width="20" height="20"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
  );
  if (logo === 'whatsapp') return (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/></svg>
  );
  if (logo === 'instagram') return (
    <svg viewBox="0 0 24 24" width="20" height="20"><defs><linearGradient id="ig-grad" x1="0%" y1="100%" x2="100%" y2="0%"><stop offset="0%" stopColor="#f09433"/><stop offset="25%" stopColor="#e6683c"/><stop offset="50%" stopColor="#dc2743"/><stop offset="75%" stopColor="#cc2366"/><stop offset="100%" stopColor="#bc1888"/></linearGradient></defs><path fill="url(#ig-grad)" d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z"/></svg>
  );
  return null;
}

function ConRow({ logo, label, handle, connected }) {
  const toast = useToast();
  const [isConnected, setIsConnected] = React.useState(connected);
  const bgMap = { linkedin:'#EBF3FB', google:'#FEF3EC', whatsapp:'#EDFBF2', instagram:'#FDF0F8' };
  return (
    <div className="con-row">
      <div className="con-logo-wrap" style={{background: bgMap[logo] || '#f3f4f6'}}>
        <BrandLogo logo={logo} />
      </div>
      <div className="col" style={{flex:1, minWidth:0}}>
        <div className="con-name">{label}</div>
        <div className="con-handle">{isConnected ? handle : 'Não conectado'}</div>
      </div>
      {isConnected
        ? <div className="con-connected-wrap">
            <span className="con-status-dot" />
            <span className="con-connected-lbl">Conectado</span>
            <button className="con-disconnect" onClick={() => { setIsConnected(false); toast(`${label} desconectado`); }}>✕</button>
          </div>
        : <button className="btn-primary btn-sm" style={{fontSize:11, padding:'6px 14px'}}
            onClick={() => { setIsConnected(true); toast(`${label} conectado com sucesso ✓`); }}>
            Conectar
          </button>}
    </div>
  );
}

window.Perfil = Perfil;
