/* ============================================================
   Devonew — Painel da Igreja · Visitantes
   Quem chega pelo site e clica em "Quero visitar" cai aqui.
   A recepção vê quem confirmou presença, quem pediu oração/ajuda
   e quem deixou contato — e acompanha: novo → contatado →
   integrado. Pode promover o visitante para o módulo de Cuidado.
   Fonte: D1 (/api/visitors) na igreja real; localStorage na demo.
   ============================================================ */
const { useState: useStateVis, useMemo: useMemoVis } = React;

/* demo (comunidadevida): exemplos para a aba nunca parecer vazia.
   Zerados para qualquer igreja real no setupTenant do admin.jsx. */
window.ADMIN.visitorsSeed = [
  { id: 'vs1', name: 'Marina Castro', first_time: 1, service: 'Domingo · 09h00 · Culto da Família',
    prayer: 'Estou passando por uma fase difícil no trabalho e queria oração.', prayer_private: 0, help: '', urgent: 0,
    message: 'Vi vocês pelo Instagram e quero conhecer.', phone: '(11) 98888-1020', email: '', best_time: 'à noite',
    contact_ok: 1, status: 'novo', created_at: Date.now() - 1000 * 60 * 60 * 5 },
  { id: 'vs2', name: 'Rodrigo Pina', first_time: 0, service: 'Domingo · 18h00 · Culto da Noite',
    prayer: '', prayer_private: 0, help: 'Estou desempregado e preciso de ajuda com uma cesta básica.', urgent: 1,
    message: '', phone: '(11) 97777-3344', email: 'rodrigo@email.com', best_time: '', contact_ok: 1,
    status: 'novo', created_at: Date.now() - 1000 * 60 * 60 * 26 },
  { id: 'vs3', name: 'Família Almeida', first_time: 1, service: '',
    prayer: '', prayer_private: 0, help: '', urgent: 0, message: 'Queremos visitar com as crianças no próximo domingo.',
    phone: '', email: '', best_time: '', contact_ok: 0, status: 'contatado', created_at: Date.now() - 1000 * 60 * 60 * 72 },
];

const VIS_INI = (n) => (n || '').trim().split(/\s+/).map((w) => w[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || 'V';
const VIS_STATUS = {
  novo: { label: 'Novo', color: 'var(--accent-strong)', bg: 'var(--accent-tint)' },
  contatado: { label: 'Contatado', color: '#7a6a2e', bg: '#fbf3da' },
  integrado: { label: 'Integrado', color: '#2f7a52', bg: '#e4f4ea' },
  arquivado: { label: 'Arquivado', color: 'var(--muted)', bg: 'var(--surface-2)' },
};
function visWhen(ts) {
  const d = Date.now() - (ts || 0), h = Math.floor(d / 3.6e6);
  if (h < 1) return 'agora há pouco';
  if (h < 24) return 'há ' + h + 'h';
  const dd = Math.floor(h / 24);
  if (dd === 1) return 'ontem';
  if (dd < 7) return 'há ' + dd + ' dias';
  try { return new Date(ts).toLocaleDateString('pt-BR'); } catch (e) { return ''; }
}
const visWa = (phone) => { const n = String(phone || '').replace(/\D/g, ''); return n ? 'https://wa.me/' + (n.length <= 11 ? '55' + n : n) : null; };

/* badges do que o visitante pediu */
function VisBadges({ v }) {
  const b = [];
  if (v.first_time) b.push(['1ª vez', 'var(--accent-strong)', 'var(--accent-tint)']);
  if (v.service) b.push(['Presença confirmada', '#2f7a52', '#e4f4ea']);
  if (v.prayer) b.push(['Pedido de oração', '#6b4ea0', '#efe9f7']);
  if (v.help) b.push([v.urgent ? 'Ajuda · URGENTE' : 'Pediu ajuda', v.urgent ? '#b3261e' : '#a8773f', v.urgent ? '#fdeceb' : '#fbf3da']);
  if (v.contact_ok && (v.phone || v.email)) b.push(['Deixou contato', 'var(--muted)', 'var(--surface-2)']);
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6 }}>
      {b.map(([t, c, bg], i) => (
        <span key={i} style={{ fontSize: 11.5, fontWeight: 600, color: c, background: bg, padding: '3px 9px', borderRadius: 999 }}>{t}</span>
      ))}
    </div>
  );
}

function VisitorDetail({ v, onClose, onStatus, onSendCare, onRemove }) {
  const [notes, setNotes] = useStateVis(v.notes || '');
  const wa = visWa(v.phone);
  const st = VIS_STATUS[v.status] || VIS_STATUS.novo;
  const row = (label, value) => value ? (
    <div style={{ marginBottom: 12 }}>
      <div className="field-lab" style={{ marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.5, whiteSpace: 'pre-line' }}>{value}</div>
    </div>
  ) : null;
  return (
    <div className="modal-ov" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 540 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
          <div className="avatar">{VIS_INI(v.name)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h3 style={{ margin: 0 }}>{v.name}</h3>
            <div className="sub">{v.first_time ? 'Primeira visita' : 'Já visitou antes'} · {visWhen(v.created_at)}</div>
          </div>
          <span style={{ fontSize: 12, fontWeight: 700, color: st.color, background: st.bg, padding: '5px 11px', borderRadius: 999 }}>{st.label}</span>
        </div>
        <VisBadges v={v} />
        <div style={{ height: 1, background: 'var(--line)', margin: '16px 0' }} />
        {row('Encontro que confirmou', v.service)}
        {row(v.prayer_private ? 'Pedido de oração · confidencial' : 'Pedido de oração', v.prayer)}
        {row(v.urgent ? 'Pedido de ajuda · URGENTE' : 'Pedido de ajuda', v.help)}
        {row('Recado', v.message)}
        {(v.phone || v.email || v.best_time) && (
          <div style={{ marginBottom: 12 }}>
            <div className="field-lab" style={{ marginBottom: 2 }}>Contato {v.contact_ok ? '· autorizado' : '· (sem autorização explícita)'}</div>
            <div style={{ fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.6 }}>
              {v.phone && <div>📱 {v.phone}</div>}
              {v.email && <div>✉️ {v.email}</div>}
              {v.best_time && <div className="muted" style={{ fontSize: 13 }}>Melhor horário: {v.best_time}</div>}
            </div>
          </div>
        )}
        <div style={{ marginBottom: 14 }}>
          <div className="field-lab" style={{ marginBottom: 4 }}>Anotações internas</div>
          <textarea className="inp" rows={2} value={notes} placeholder="Visível só para a equipe…"
            onChange={(e) => setNotes(e.target.value)} onBlur={() => notes !== (v.notes || '') && onStatus(v, { notes })} style={{ resize: 'vertical' }} />
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {wa && <a className="btn btn-primary btn-sm" href={wa} target="_blank" rel="noopener"><Icon name="chat" size={15} />Chamar no WhatsApp</a>}
          {v.status !== 'contatado' && <button className="btn btn-quiet btn-sm" onClick={() => onStatus(v, { status: 'contatado' })}><Icon name="check" size={15} />Marcar contatado</button>}
          <button className="btn btn-quiet btn-sm" onClick={() => onSendCare(v)}><Icon name="heart" size={15} />Enviar para o Cuidado</button>
        </div>
        <div className="modal-actions" style={{ marginTop: 16 }}>
          <button className="btn btn-quiet btn-sm" onClick={() => onRemove(v)} style={{ color: '#b3261e' }}><Icon name="trash" size={14} />Remover</button>
          <div className="flex1" />
          {v.status !== 'arquivado'
            ? <button className="btn btn-quiet btn-sm" onClick={() => onStatus(v, { status: 'arquivado' })}>Arquivar</button>
            : <button className="btn btn-quiet btn-sm" onClick={() => onStatus(v, { status: 'novo' })}>Restaurar</button>}
          <button className="btn btn-primary btn-sm" onClick={onClose}>Fechar</button>
        </div>
      </div>
    </div>
  );
}

function VisitantesScreen({ visitors, setVisitors, isDemo, onSendToCare, toast }) {
  const [filter, setFilter] = useStateVis('ativos');
  const [search, setSearch] = useStateVis('');
  const [openId, setOpenId] = useStateVis(null);

  const persist = (v, changes) => {
    setVisitors((list) => list.map((x) => (x.id === v.id ? { ...x, ...changes } : x)));
    if (!isDemo) {
      const next = { ...v, ...changes };
      fetch('/api/visitors', { method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: v.id, status: next.status, notes: next.notes || '' }) }).catch(() => {});
    }
  };
  const remove = (v) => {
    setVisitors((list) => list.filter((x) => x.id !== v.id));
    setOpenId(null);
    if (!isDemo) fetch('/api/visitors', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: v.id }) }).catch(() => {});
    toast('Visitante removido');
  };
  const sendCare = (v) => {
    const yr = new Date().getFullYear();
    const noteParts = [];
    if (v.service) noteParts.push('Confirmou presença: ' + v.service + '.');
    if (v.prayer) noteParts.push('Oração: ' + v.prayer);
    if (v.help) noteParts.push((v.urgent ? '[URGENTE] ' : '') + 'Ajuda: ' + v.help);
    if (v.message) noteParts.push('Recado: ' + v.message);
    if (v.phone || v.email) noteParts.push('Contato: ' + [v.phone, v.email].filter(Boolean).join(' · '));
    onSendToCare({
      id: 'vis:' + v.id, name: v.name, initials: VIS_INI(v.name), role: 'Visitante', cell: '—',
      joined: yr, joinedDaysAgo: 1, lastSeenWeeks: 0, appActiveDays: 1, journeyStep: 0,
      prayer: !!v.prayer, flags: ['visitante', 'novo'], assignedTo: '—', status: 'aberto', lastTouchDays: 0,
      scores: { presenca: 60, comunhao: 15, devocional: 20, servico: 5, generosidade: 0, discipulado: 10 },
      touches: [{ date: new Date().toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' }), by: 'Recepção do site', channel: 'site',
        note: noteParts.join(' ') || 'Chegou pelo site e quer visitar.' }],
    });
    persist(v, { status: 'integrado' });
    setOpenId(null);
    toast(v.name + ' enviado para o Cuidado pastoral ✓');
  };

  const weekAgo = Date.now() - 7 * 864e5;
  const stats = useMemoVis(() => ({
    week: visitors.filter((v) => v.created_at >= weekAgo).length,
    presence: visitors.filter((v) => v.service && v.status !== 'arquivado').length,
    prayer: visitors.filter((v) => v.prayer && v.status === 'novo').length,
    waiting: visitors.filter((v) => v.contact_ok && (v.phone || v.email) && v.status === 'novo').length,
  }), [visitors]);

  const list = useMemoVis(() => {
    let l = visitors.slice().sort((a, b) => (b.created_at || 0) - (a.created_at || 0));
    if (filter === 'ativos') l = l.filter((v) => v.status !== 'arquivado');
    else if (filter === 'novos') l = l.filter((v) => v.status === 'novo');
    else if (filter === 'oracao') l = l.filter((v) => v.prayer);
    else if (filter === 'ajuda') l = l.filter((v) => v.help);
    else if (filter === 'contato') l = l.filter((v) => v.contact_ok && (v.phone || v.email) && v.status !== 'integrado');
    else if (filter === 'arquivados') l = l.filter((v) => v.status === 'arquivado');
    const q = search.trim().toLowerCase();
    if (q) l = l.filter((v) => (v.name || '').toLowerCase().includes(q));
    return l;
  }, [visitors, filter, search]);

  const FILTERS = [
    ['ativos', 'Ativos'], ['novos', 'Novos'], ['oracao', 'Oração'],
    ['ajuda', 'Ajuda'], ['contato', 'Aguardando contato'], ['arquivados', 'Arquivados'],
  ];
  const open = visitors.find((v) => v.id === openId);

  return (
    <div className="awrap">
      <div className="kpi-grid">
        {[['Visitantes na semana', stats.week, 'userPlus'], ['Presença confirmada', stats.presence, 'check'],
          ['Oração em aberto', stats.prayer, 'heart'], ['Aguardando contato', stats.waiting, 'chat']].map(([lab, val, ico]) => (
          <div className="kpi" key={lab}>
            <div className="kpi-ico"><Icon name={ico} size={20} /></div>
            <div className="kpi-value">{val}</div>
            <div className="kpi-label">{lab}</div>
          </div>
        ))}
      </div>

      <div className="panel" style={{ marginTop: 18 }}>
        <div className="panel-head">
          <div><h3>Visitantes</h3><div className="sub">Quem chegou pelo site e quer ser recebido</div></div>
          <div className="searchbox" style={{ maxWidth: 220 }}>
            <Icon name="search" size={15} /><input placeholder="Buscar pelo nome…" value={search} onChange={(e) => setSearch(e.target.value)} />
          </div>
        </div>
        <div className="panel-pad" style={{ paddingTop: 12 }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 14 }}>
            {FILTERS.map(([id, lab]) => (
              <button key={id} className={'btn btn-sm ' + (filter === id ? 'btn-primary' : 'btn-quiet')} onClick={() => setFilter(id)}>{lab}</button>
            ))}
          </div>

          {list.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '46px 20px', color: 'var(--muted)' }}>
              <Icon name="userPlus" size={30} />
              <p style={{ margin: '12px 0 0', fontSize: 15 }}>
                {visitors.length === 0
                  ? 'Ainda não chegou nenhum visitante pelo site. Quando alguém clicar em "Quero visitar", aparece aqui.'
                  : 'Nenhum visitante neste filtro.'}
              </p>
            </div>
          ) : list.map((v) => {
            const st = VIS_STATUS[v.status] || VIS_STATUS.novo;
            return (
              <button key={v.id} className="lrow" onClick={() => setOpenId(v.id)}
                style={{ width: '100%', textAlign: 'left', border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 'var(--r-md)', padding: '13px 15px', cursor: 'pointer', marginBottom: 9, alignItems: 'flex-start' }}>
                <div className="avatar sm">{VIS_INI(v.name)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="t" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    {v.name}
                    <span style={{ fontSize: 11, fontWeight: 700, color: st.color, background: st.bg, padding: '2px 8px', borderRadius: 999 }}>{st.label}</span>
                  </div>
                  <VisBadges v={v} />
                </div>
                <div className="meta" style={{ flex: 'none' }}>{visWhen(v.created_at)}</div>
              </button>
            );
          })}
        </div>
      </div>

      {open && <VisitorDetail v={open} onClose={() => setOpenId(null)} onStatus={persist} onSendCare={sendCare} onRemove={remove} />}
    </div>
  );
}

window.VisitantesScreen = VisitantesScreen;
