// Cofre Pessoal — senhas, contas bancárias, e-mails, anotações
// Armazenado em state.vault, sincronizado via cloud sync.
// ⚠️ Sem criptografia: aviso é mostrado no topo da tela.

const VAULT_TYPES = [
  { id: 'senha', label: 'Senha', icon: 'lock', color: '#B197FC' },
  { id: 'conta', label: 'Conta bancária', icon: 'wallet', color: '#5EE3A8' },
  { id: 'email', label: 'E-mail', icon: 'sparkle', color: '#6FB8FF' },
  { id: 'nota', label: 'Anotação', icon: 'edit', color: '#FFB547' },
];

function vaultIcon(type) {
  const t = VAULT_TYPES.find(x => x.id === type);
  return t ? t.icon : 'lock';
}
function vaultColor(type) {
  const t = VAULT_TYPES.find(x => x.id === type);
  return t ? t.color : CDV.brand;
}
function vaultLabel(type) {
  const t = VAULT_TYPES.find(x => x.id === type);
  return t ? t.label : type;
}

const VaultScreen = ({ state, setState, navigate, showToast }) => {
  const items = (state && state.vault) || [];
  const [filter, setFilter] = React.useState('todos');
  const [search, setSearch] = React.useState('');
  const [showNew, setShowNew] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [detailId, setDetailId] = React.useState(null);

  const filtered = items
    .filter(i => filter === 'todos' || i.type === filter)
    .filter(i => !search || (i.title || '').toLowerCase().includes(search.toLowerCase()));

  const detail = items.find(i => i.id === detailId);
  const editing = items.find(i => i.id === editingId);

  const addItem = (item) => {
    const now = new Date().toISOString();
    setState(s => ({
      ...s,
      vault: [...((s && s.vault) || []), { ...item, id: 'v' + Date.now(), createdAt: now, updatedAt: now }],
    }));
    setShowNew(false);
    showToast('Item salvo no cofre');
  };
  const updateItem = (id, patch) => {
    const now = new Date().toISOString();
    setState(s => ({
      ...s,
      vault: (s.vault || []).map(i => i.id === id ? { ...i, ...patch, updatedAt: now } : i),
    }));
    setEditingId(null);
    showToast('Item atualizado');
  };
  const deleteItem = (id) => {
    if (window.confirm && !window.confirm('Excluir este item do cofre?')) return;
    setState(s => ({ ...s, vault: (s.vault || []).filter(i => i.id !== id) }));
    setDetailId(null);
    setEditingId(null);
    showToast('Item removido');
  };

  const counts = {
    todos: items.length,
    senha: items.filter(i => i.type === 'senha').length,
    conta: items.filter(i => i.type === 'conta').length,
    email: items.filter(i => i.type === 'email').length,
    nota: items.filter(i => i.type === 'nota').length,
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Cofre Pessoal" subtitle="SUAS INFORMAÇÕES PRIVADAS" onBack={() => navigate('more')} right={
        <button onClick={() => setShowNew(true)} style={{
          background: CDV.brandGrad, border: 'none', width: 38, height: 38, borderRadius: 99,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
          boxShadow: '0 6px 20px -6px rgba(177,151,252,0.6)',
        }}><Icon name="plus" size={18} /></button>
      } />

      {/* Aviso de segurança */}
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{
          padding: 12, borderRadius: 14,
          background: CDV.amberSoft, border: `1px solid ${CDV.amber}30`,
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <Icon name="shield" size={14} color={CDV.amber} style={{ marginTop: 2, flexShrink: 0 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: CDV.amber, letterSpacing: 0.3, textTransform: 'uppercase' }}>Atenção</div>
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 3, lineHeight: 1.5 }}>
              Os itens são salvos sem criptografia avançada. Para senhas críticas (banco, e-mail principal), recomendamos um gerenciador dedicado como 1Password ou Bitwarden.
            </div>
          </div>
        </div>
      </div>

      {/* Busca */}
      <div style={{ padding: '0 22px 12px' }}>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar no cofre..."
          style={{
            width: '100%', height: 44, borderRadius: 12, border: `1px solid ${CDV.stroke}`,
            background: CDV.surface, color: CDV.text, padding: '0 14px', fontSize: 13,
            outline: 'none', fontFamily: 'inherit',
          }} />
      </div>

      {/* Filtros por tipo */}
      <div style={{ padding: '0 22px 14px', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {[
          { id: 'todos', label: `Todos · ${counts.todos}` },
          { id: 'senha', label: `Senhas · ${counts.senha}` },
          { id: 'conta', label: `Contas · ${counts.conta}` },
          { id: 'email', label: `E-mails · ${counts.email}` },
          { id: 'nota', label: `Anotações · ${counts.nota}` },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            flex: '0 0 auto', height: 32, padding: '0 14px', borderRadius: 99,
            background: filter === f.id ? CDV.text : CDV.surface,
            color: filter === f.id ? '#000' : CDV.textDim,
            border: `1px solid ${filter === f.id ? 'transparent' : CDV.stroke}`,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>{f.label}</button>
        ))}
      </div>

      {/* Lista */}
      {filtered.length === 0 ? (
        <div style={{ padding: '0 22px' }}>
          <div style={{ padding: 30, borderRadius: 16, background: CDV.surface, border: `1px dashed ${CDV.stroke}`, color: CDV.textDim, fontSize: 13, textAlign: 'center' }}>
            <Icon name="lock" size={28} color={CDV.textMuted} />
            <div style={{ color: CDV.text, fontWeight: 600, marginTop: 10 }}>
              {items.length === 0 ? 'Cofre vazio' : 'Nada encontrado'}
            </div>
            <div style={{ marginTop: 4 }}>
              {items.length === 0
                ? 'Adicione senhas, contas, e-mails e anotações pessoais.'
                : 'Ajuste a busca ou filtro.'}
            </div>
          </div>
        </div>
      ) : (
        <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {filtered.map(item => (
            <VaultListItem key={item.id} item={item} onClick={() => setDetailId(item.id)} />
          ))}
        </div>
      )}

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Novo item no cofre">
        <NewVaultItemForm onSubmit={addItem} />
      </Sheet>

      <Sheet open={!!detail} onClose={() => setDetailId(null)} title="Detalhes">
        {detail && (
          <VaultDetail
            item={detail}
            onEdit={() => { setEditingId(detail.id); setDetailId(null); }}
            onDelete={() => deleteItem(detail.id)}
            showToast={showToast}
          />
        )}
      </Sheet>

      <Sheet open={!!editing} onClose={() => setEditingId(null)} title="Editar item">
        {editing && (
          <NewVaultItemForm
            initial={editing}
            onSubmit={(patch) => updateItem(editing.id, patch)}
          />
        )}
      </Sheet>
    </div>
  );
};

// ── Linha da lista ─────────────────────────────────────────
const VaultListItem = ({ item, onClick }) => {
  const c = vaultColor(item.type);
  return (
    <div onClick={onClick} style={{
      padding: 14, paddingLeft: 16, borderRadius: 14,
      background: `linear-gradient(135deg, ${c}0d 0%, ${CDV.surface} 60%)`,
      border: `1px solid ${c}22`,
      position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      boxShadow: `0 4px 14px -10px ${c}40`,
    }}>
      <div style={{
        position: 'absolute', left: 0, top: 12, bottom: 12, width: 3, borderRadius: 99,
        background: `linear-gradient(180deg, ${c}, ${c}40)`,
        boxShadow: `0 0 10px ${c}80`,
      }} />
      <div style={{
        width: 38, height: 38, borderRadius: 11,
        background: `linear-gradient(135deg, ${c}38, ${c}14)`,
        border: `1px solid ${c}30`, color: c, flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: `0 6px 14px -6px ${c}80, inset 0 0 0 1px rgba(255,255,255,0.06)`,
      }}><Icon name={vaultIcon(item.type)} size={16} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: CDV.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {item.title}
        </div>
        <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>
          {vaultLabel(item.type)}{item.data && item.data.user ? ` · ${item.data.user}` : ''}{item.data && item.data.email ? ` · ${item.data.email}` : ''}
        </div>
      </div>
      <Icon name="chevronRight" size={14} color={CDV.textMuted} />
    </div>
  );
};

// ── Form de criação/edição ─────────────────────────────────
const NewVaultItemForm = ({ onSubmit, initial }) => {
  const [type, setType] = React.useState((initial && initial.type) || 'senha');
  const [title, setTitle] = React.useState((initial && initial.title) || '');
  const [data, setData] = React.useState((initial && initial.data) || {});
  const setField = (k, v) => setData(d => ({ ...d, [k]: v }));
  const c = vaultColor(type);
  const canSave = title.trim().length > 0;

  return (
    <div style={{ padding: '12px 22px 28px' }}>
      {!initial && (
        <>
          <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Tipo</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 14 }}>
            {VAULT_TYPES.map(t => {
              const active = type === t.id;
              return (
                <button key={t.id} onClick={() => setType(t.id)} style={{
                  padding: '10px 12px', borderRadius: 12, textAlign: 'left',
                  background: active ? t.color + '22' : CDV.surfaceHi,
                  border: `1.5px solid ${active ? t.color : CDV.stroke}`,
                  color: active ? t.color : CDV.textDim,
                  fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8,
                  fontSize: 13, fontWeight: 600,
                }}>
                  <Icon name={t.icon} size={14} color={active ? t.color : CDV.textDim} />
                  {t.label}
                </button>
              );
            })}
          </div>
        </>
      )}

      <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Título (ex: Nubank, Gmail pessoal...)" autoFocus
        style={{
          width: '100%', height: 50, borderRadius: 12, border: `1px solid ${CDV.stroke}`,
          background: CDV.surfaceHi, color: CDV.text, padding: '0 14px', fontSize: 14,
          outline: 'none', fontFamily: 'inherit', marginBottom: 12,
        }} />

      {/* Campos por tipo */}
      {type === 'senha' && <>
        <VaultField label="Site / Serviço" value={data.site || ''} onChange={v => setField('site', v)} placeholder="nubank.com.br" />
        <VaultField label="Usuário / E-mail" value={data.user || ''} onChange={v => setField('user', v)} placeholder="lucas@email.com" />
        <VaultField label="Senha" value={data.password || ''} onChange={v => setField('password', v)} placeholder="••••••••" sensitive />
        <VaultField label="Notas (opcional)" value={data.notes || ''} onChange={v => setField('notes', v)} placeholder="..." textarea />
      </>}

      {type === 'conta' && <>
        <VaultField label="Banco" value={data.banco || ''} onChange={v => setField('banco', v)} placeholder="Nubank" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
          <VaultField inline label="Agência" value={data.agencia || ''} onChange={v => setField('agencia', v)} placeholder="0001" />
          <VaultField inline label="Conta" value={data.conta || ''} onChange={v => setField('conta', v)} placeholder="12345-6" />
        </div>
        <VaultField label="Tipo de conta" value={data.tipoConta || ''} onChange={v => setField('tipoConta', v)} placeholder="Corrente / Poupança" />
        <VaultField label="Notas (opcional)" value={data.notes || ''} onChange={v => setField('notes', v)} placeholder="..." textarea />
      </>}

      {type === 'email' && <>
        <VaultField label="Provedor" value={data.provedor || ''} onChange={v => setField('provedor', v)} placeholder="Gmail, Outlook..." />
        <VaultField label="E-mail" value={data.email || ''} onChange={v => setField('email', v)} placeholder="lucas@email.com" />
        <VaultField label="Senha" value={data.password || ''} onChange={v => setField('password', v)} placeholder="••••••••" sensitive />
        <VaultField label="Notas (opcional)" value={data.notes || ''} onChange={v => setField('notes', v)} placeholder="..." textarea />
      </>}

      {type === 'nota' && <>
        <VaultField label="Anotação" value={data.text || ''} onChange={v => setField('text', v)} placeholder="Escreva aqui..." textarea big />
      </>}

      <button onClick={() => canSave && onSubmit({ type, title: title.trim(), data })} style={{
        marginTop: 18, width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
        opacity: canSave ? 1 : 0.4, cursor: canSave ? 'pointer' : 'not-allowed',
        fontFamily: 'inherit',
      }}>{initial ? 'Salvar alterações' : 'Salvar no cofre'}</button>
    </div>
  );
};

const VaultField = ({ label, value, onChange, placeholder, sensitive, textarea, big, inline }) => {
  const [show, setShow] = React.useState(false);
  const isPassword = sensitive && !show;
  return (
    <div style={{ marginBottom: inline ? 0 : 10 }}>
      <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      <div style={{ position: 'relative' }}>
        {textarea ? (
          <textarea value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
            rows={big ? 6 : 3}
            style={{
              width: '100%', borderRadius: 12, border: `1px solid ${CDV.stroke}`,
              background: CDV.surfaceHi, color: CDV.text, padding: '10px 12px', fontSize: 14,
              outline: 'none', fontFamily: 'inherit', resize: 'vertical', minHeight: big ? 140 : 70,
            }} />
        ) : (
          <input
            type={isPassword ? 'password' : 'text'}
            value={value}
            onChange={e => onChange(e.target.value)}
            placeholder={placeholder}
            style={{
              width: '100%', height: 46, borderRadius: 12, border: `1px solid ${CDV.stroke}`,
              background: CDV.surfaceHi, color: CDV.text, padding: '0 12px', paddingRight: sensitive ? 40 : 12, fontSize: 14,
              outline: 'none', fontFamily: 'inherit',
            }} />
        )}
        {sensitive && !textarea && (
          <button onClick={() => setShow(s => !s)} type="button" style={{
            position: 'absolute', right: 6, top: 7, width: 32, height: 32, borderRadius: 8,
            background: 'transparent', border: 'none', color: CDV.textDim, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name={show ? 'eyeOff' : 'eye'} size={15} /></button>
        )}
      </div>
    </div>
  );
};

// ── Detalhe do item ────────────────────────────────────────
const VaultDetail = ({ item, onEdit, onDelete, showToast }) => {
  const c = vaultColor(item.type);
  const copy = (label, val) => {
    if (!val) return;
    try { navigator.clipboard.writeText(val); showToast && showToast(`${label} copiado`); } catch (e) {}
  };
  return (
    <div style={{ padding: '8px 22px 28px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: `linear-gradient(135deg, ${c}38, ${c}14)`,
          border: `1px solid ${c}30`, color: c,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 8px 18px -8px ${c}80`,
        }}><Icon name={vaultIcon(item.type)} size={20} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, color: c, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>{vaultLabel(item.type)}</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text, letterSpacing: -0.2, marginTop: 2 }}>{item.title}</div>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {item.type === 'senha' && <>
          <VaultRow label="Site / Serviço" value={item.data.site} onCopy={() => copy('Site', item.data.site)} />
          <VaultRow label="Usuário" value={item.data.user} onCopy={() => copy('Usuário', item.data.user)} />
          <VaultRow label="Senha" value={item.data.password} sensitive onCopy={() => copy('Senha', item.data.password)} />
          {item.data.notes && <VaultRow label="Notas" value={item.data.notes} multiline />}
        </>}
        {item.type === 'conta' && <>
          <VaultRow label="Banco" value={item.data.banco} onCopy={() => copy('Banco', item.data.banco)} />
          <VaultRow label="Agência" value={item.data.agencia} onCopy={() => copy('Agência', item.data.agencia)} />
          <VaultRow label="Conta" value={item.data.conta} onCopy={() => copy('Conta', item.data.conta)} />
          <VaultRow label="Tipo" value={item.data.tipoConta} />
          {item.data.notes && <VaultRow label="Notas" value={item.data.notes} multiline />}
        </>}
        {item.type === 'email' && <>
          <VaultRow label="Provedor" value={item.data.provedor} />
          <VaultRow label="E-mail" value={item.data.email} onCopy={() => copy('E-mail', item.data.email)} />
          <VaultRow label="Senha" value={item.data.password} sensitive onCopy={() => copy('Senha', item.data.password)} />
          {item.data.notes && <VaultRow label="Notas" value={item.data.notes} multiline />}
        </>}
        {item.type === 'nota' && (
          <VaultRow label="Anotação" value={item.data.text} multiline onCopy={() => copy('Anotação', item.data.text)} />
        )}
      </div>

      <div style={{ fontSize: 11, color: CDV.textMuted, marginTop: 14, textAlign: 'center' }}>
        Criado em {new Date(item.createdAt).toLocaleDateString('pt-BR')}
        {item.updatedAt !== item.createdAt ? ` · atualizado ${new Date(item.updatedAt).toLocaleDateString('pt-BR')}` : ''}
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
        <button onClick={onEdit} style={{
          flex: 1, height: 48, borderRadius: 14, background: CDV.surfaceHi,
          border: `1px solid ${CDV.stroke}`, color: CDV.text,
          fontSize: 13, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}><Icon name="edit" size={14} /> Editar</button>
        <button onClick={onDelete} style={{
          flex: 1, height: 48, borderRadius: 14, background: 'transparent',
          border: `1px solid ${CDV.coral}30`, color: CDV.coral,
          fontSize: 13, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}><Icon name="trash" size={14} /> Excluir</button>
      </div>
    </div>
  );
};

const VaultRow = ({ label, value, sensitive, multiline, onCopy }) => {
  const [show, setShow] = React.useState(false);
  if (!value) return null;
  const display = sensitive && !show ? '•'.repeat(Math.min(value.length, 12)) : value;
  return (
    <div style={{
      padding: '10px 12px', borderRadius: 10,
      background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
        <div style={{ display: 'flex', gap: 4 }}>
          {sensitive && (
            <button onClick={() => setShow(s => !s)} style={{
              background: 'transparent', border: 'none', color: CDV.textDim, cursor: 'pointer',
              width: 24, height: 24, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name={show ? 'eyeOff' : 'eye'} size={12} /></button>
          )}
          {onCopy && (
            <button onClick={onCopy} style={{
              background: 'transparent', border: 'none', color: CDV.brand, cursor: 'pointer',
              width: 24, height: 24, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="check" size={12} /></button>
          )}
        </div>
      </div>
      <div style={{
        fontSize: 14, color: CDV.text, marginTop: 4,
        wordBreak: 'break-word', whiteSpace: multiline ? 'pre-wrap' : 'nowrap',
        overflow: multiline ? 'visible' : 'hidden', textOverflow: 'ellipsis',
        fontFamily: sensitive && !show ? fontMono : 'inherit',
      }}>{display}</div>
    </div>
  );
};

Object.assign(window, { VaultScreen });
