
// ============================================================
// JuFlow — Marketing
// ============================================================
const { useState: useStMK } = React;
const UMK = window.JFUtils;

const MK_TEMPLATES = {
  birthday: 'Oi {{nome}}! 🎉 Hoje queremos celebrar você! Toda a equipe do Studio JuFlow deseja um feliz aniversário. Como presente, preparamos um cupom exclusivo: BDAY15 (15% off em qualquer serviço durante este mês). Te esperamos!',
  inactive: 'Olá {{nome}}! Sentimos sua falta aqui no Studio JuFlow. Que tal agendar uma sessão? Como incentivo para você voltar, oferecemos 20% de desconto no seu próximo atendimento. Use o código VOLTEI20 ao agendar.',
};

const Marketing = ({ appointments, addToast }) => {
  const [tab, setTab] = useStMK('overview');
  const [bulk, setBulk] = useStMK({ open:false, type:'birthday', message:'', recipients:[], selected:{} });

  const birthdays     = window.JF.CLIENTS.filter(c => UMK.isBirthdayThisMonth(c.birthdate));
  const inactive      = window.JF.CLIENTS.filter(c => c.lastVisit && UMK.daysBetween(c.lastVisit, window.JF.TODAY) > 60);
  const reviews       = window.JF.REVIEWS;
  const avgRating     = reviews.reduce((s,r) => s+r.rating, 0) / reviews.length;

  const openBulk = (type, recipients, focusedId = null) => {
    const selected = {};
    recipients.forEach(c => { selected[c.id] = focusedId ? c.id === focusedId : true; });
    setBulk({ open:true, type, message: MK_TEMPLATES[type], recipients, selected });
  };
  const closeBulk = () => setBulk(b => ({ ...b, open:false }));
  const toggleRecipient = (id) => setBulk(b => ({ ...b, selected: { ...b.selected, [id]: !b.selected[id] } }));
  const toggleAll = (val) => setBulk(b => {
    const sel = {}; b.recipients.forEach(c => { sel[c.id] = val; });
    return { ...b, selected: sel };
  });
  const sendBulk = () => {
    const count = bulk.recipients.filter(c => bulk.selected[c.id]).length;
    if (count === 0) { addToast('Selecione ao menos um destinatário.', 'warning'); return; }
    const verb = bulk.type === 'birthday' ? 'aniversário' : 'reativação';
    addToast(`${count} mensagem(ns) de ${verb} enviada(s) via WhatsApp! 📲`, 'success');
    closeBulk();
  };
  const selectedCount = bulk.recipients.filter(c => bulk.selected[c.id]).length;
  const allSelected = bulk.recipients.length > 0 && selectedCount === bulk.recipients.length;

  const ActionCard = ({ title, subtitle, icon, color, count, children, actionLabel, onAction }) => (
    <div style={{ background:'#fff', borderRadius:14, overflow:'hidden', boxShadow:'0 2px 8px rgba(10,31,68,.06)', border:'1px solid #E2E8F0' }}>
      <div style={{ padding:'16px 20px', borderBottom:'1px solid #F0F4F8', display:'flex', alignItems:'center', gap:12 }}>
        <div style={{ width:40, height:40, borderRadius:10, background:UMK.hexToRgba(color,.12), display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name={icon} size={20} color={color} />
        </div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:15, fontWeight:700, color:'#0A1F44' }}>{title}</div>
          <div style={{ fontSize:12, color:'#9CA3AF' }}>{subtitle}</div>
        </div>
        {count !== undefined && (
          <div style={{ fontSize:22, fontWeight:800, color }}>
            {count}
          </div>
        )}
      </div>
      <div style={{ padding:'14px 20px' }}>
        {children}
        {actionLabel && (
          <Button variant="primary" icon="Send" size="sm" style={{ marginTop:12 }} onClick={onAction}>{actionLabel}</Button>
        )}
      </div>
    </div>
  );

  const StarRating = ({ rating }) => (
    <div style={{ display:'flex', gap:2 }}>
      {[1,2,3,4,5].map(i => (
        <Icon key={i} name="Star" size={13} color={i <= rating ? '#FBBF24' : '#E2E8F0'} />
      ))}
    </div>
  );

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Metrics */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Aniversariantes" value={birthdays.length} icon="Cake" color="#7C3AED" subtitle="este mês" />
        <MetricCard title="Clientes Inativos" value={inactive.length} icon="UserX" color="#EF4444" subtitle="há +60 dias" />
        <MetricCard title="Avaliações" value={reviews.length} icon="Star" color="#FBBF24" subtitle="recebidas" />
        <MetricCard title="Nota Média" value={avgRating.toFixed(1)} icon="ThumbsUp" color="#059669" subtitle="das avaliações" />
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
        {/* Birthdays */}
        <ActionCard title="Aniversariantes do Mês" subtitle={`${birthdays.length} clientes fazem aniversário`} icon="Cake" color="#7C3AED" count={birthdays.length}
          actionLabel="Enviar mensagens em lote" onAction={() => openBulk('birthday', birthdays)}
        >
          <div style={{ display:'flex', flexDirection:'column', gap:8, maxHeight:220, overflow:'auto' }}>
            {birthdays.length === 0 ? (
              <p style={{ fontSize:13, color:'#9CA3AF', textAlign:'center', padding:'12px 0' }}>Nenhum aniversariante este mês</p>
            ) : birthdays.map(c => (
              <div key={c.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'6px 0', borderBottom:'1px solid #F9FAFB' }}>
                <Avatar name={c.name} color="#7C3AED" size={32} />
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{c.name}</div>
                  <div style={{ fontSize:11, color:'#9CA3AF' }}>
                    {UMK.formatDate(c.birthdate,'dd/MM')} · {UMK.age(c.birthdate)} anos
                  </div>
                </div>
                <button
                  onClick={() => openBulk('birthday', birthdays, c.id)}
                  style={{ padding:'4px 10px', borderRadius:20, fontSize:11, fontWeight:600, background:'rgba(124,58,237,.12)', color:'#7C3AED', border:'none', cursor:'pointer' }}
                >Enviar</button>
              </div>
            ))}
          </div>
        </ActionCard>

        {/* Inactive clients */}
        <ActionCard title="Clientes Inativos" subtitle="Sem visita há mais de 60 dias" icon="UserX" color="#EF4444" count={inactive.length}
          actionLabel="Reativar todos" onAction={() => openBulk('inactive', inactive)}
        >
          <div style={{ display:'flex', flexDirection:'column', gap:8, maxHeight:220, overflow:'auto' }}>
            {inactive.length === 0 ? (
              <p style={{ fontSize:13, color:'#9CA3AF', textAlign:'center', padding:'12px 0' }}>Nenhum cliente inativo 🎉</p>
            ) : inactive.map(c => {
              const days = UMK.daysBetween(c.lastVisit, window.JF.TODAY);
              return (
                <div key={c.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'6px 0', borderBottom:'1px solid #F9FAFB' }}>
                  <Avatar name={c.name} color="#EF4444" size={32} />
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{c.name}</div>
                    <div style={{ fontSize:11, color:'#EF4444', fontWeight:600 }}>Ausente há {days} dias</div>
                  </div>
                  <button
                    onClick={() => openBulk('inactive', inactive, c.id)}
                    style={{ padding:'4px 10px', borderRadius:20, fontSize:11, fontWeight:600, background:'rgba(239,68,68,.1)', color:'#EF4444', border:'none', cursor:'pointer' }}
                  >Contatar</button>
                </div>
              );
            })}
          </div>
        </ActionCard>

        {/* Reviews */}
        <ActionCard title="Avaliações dos Clientes" subtitle={`Nota média: ${avgRating.toFixed(1)}/5.0`} icon="Star" color="#FBBF24">
          <div style={{ display:'flex', alignItems:'center', gap:16, marginBottom:14, padding:'10px 14px', background:'#FFFBEB', borderRadius:10 }}>
            <div style={{ fontSize:36, fontWeight:800, color:'#D97706' }}>{avgRating.toFixed(1)}</div>
            <div>
              <div style={{ display:'flex', gap:2, marginBottom:4 }}>
                {[1,2,3,4,5].map(i => <Icon key={i} name="Star" size={18} color={i <= Math.round(avgRating) ? '#FBBF24' : '#E2E8F0'} />)}
              </div>
              <div style={{ fontSize:12, color:'#9CA3AF' }}>{reviews.length} avaliações</div>
            </div>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:10, maxHeight:240, overflow:'auto' }}>
            {reviews.map(rev => {
              const client = UMK.getClient(rev.clientId);
              const prof   = UMK.getProfessional(rev.professionalId);
              return (
                <div key={rev.id} style={{ background:'#F9FAFB', borderRadius:10, padding:'12px 14px' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:6 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <Avatar name={client?.name} color="#0A1F44" size={26} />
                      <div>
                        <div style={{ fontSize:12, fontWeight:700, color:'#0A1F44' }}>{client?.name}</div>
                        <div style={{ fontSize:10, color:'#9CA3AF' }}>{prof?.name} · {UMK.formatDate(rev.date)}</div>
                      </div>
                    </div>
                    <div style={{ display:'flex', gap:1 }}>
                      {[1,2,3,4,5].map(i => <Icon key={i} name="Star" size={11} color={i<=rev.rating?'#FBBF24':'#E2E8F0'} />)}
                    </div>
                  </div>
                  <p style={{ fontSize:12, color:'#374151', margin:0, lineHeight:1.5, fontStyle:'italic' }}>"{rev.comment}"</p>
                </div>
              );
            })}
          </div>
        </ActionCard>

        {/* Smart suggestions */}
        <ActionCard title="Sugestões Inteligentes" subtitle="Ações recomendadas pelo sistema" icon="Lightbulb" color="#FF6B35">
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {[
              { client: window.JF.CLIENTS.find(c=>c.status==='inactive'), type:'reactivate', msg:'não retorna há 97 dias. Envie uma oferta especial!', urgency:'high' },
              { client: window.JF.CLIENTS.find(c=>c.tags.includes('Inadimplente')), type:'payment', msg:'possui um débito em aberto. Entre em contato.', urgency:'medium' },
              { client: birthdays[0], type:'birthday', msg:`faz aniversário em ${birthdays[0] ? UMK.formatDate(birthdays[0].birthdate,'dd/MM') : ''}. Envie parabéns!`, urgency:'low' },
            ].filter(s => s.client).map((s, i) => {
              const urgencyColor = { high:'#EF4444', medium:'#D97706', low:'#059669' }[s.urgency];
              return (
                <div key={i} style={{ padding:'12px 14px', borderRadius:10, background:'#FFF0EA', border:'1px solid #FED7AA', display:'flex', gap:10 }}>
                  <div style={{ width:6, borderRadius:99, background:urgencyColor, flexShrink:0 }} />
                  <div style={{ flex:1 }}>
                    <span style={{ fontSize:12, fontWeight:700, color:'#0A1F44' }}>{s.client?.name}</span>
                    <span style={{ fontSize:12, color:'#6B7280' }}> {s.msg}</span>
                  </div>
                  <button onClick={() => addToast(`Mensagem enviada para ${s.client?.name}!`, 'success')}
                    style={{ padding:'4px 10px', borderRadius:20, fontSize:11, fontWeight:700, background:'#FF6B35', color:'#fff', border:'none', cursor:'pointer', whiteSpace:'nowrap' }}
                  >Agir</button>
                </div>
              );
            })}
          </div>
        </ActionCard>
      </div>

      {/* Bulk message modal */}
      <Modal
        open={bulk.open}
        onClose={closeBulk}
        title={bulk.type === 'birthday' ? '🎂 Envio em lote — Aniversariantes' : '💬 Campanha de Reativação'}
        width={620}
        footer={<>
          <Button variant="secondary" onClick={closeBulk}>Cancelar</Button>
          <Button variant="primary" icon="Send" onClick={sendBulk}>
            Enviar {selectedCount > 0 ? `(${selectedCount})` : ''}
          </Button>
        </>}
      >
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
              <Icon name="MessageCircle" size={16} color="#25D366" />
              <span style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>Mensagem (WhatsApp)</span>
              <span style={{ fontSize:11, color:'#9CA3AF' }}>· use {'{{nome}}'} para personalizar</span>
            </div>
            <Textarea
              value={bulk.message}
              onChange={v => setBulk(b => ({ ...b, message: v }))}
              rows={5}
              placeholder="Escreva a mensagem..."
            />
            {bulk.recipients.length > 0 && (() => {
              const firstSelected = bulk.recipients.find(c => bulk.selected[c.id]) || bulk.recipients[0];
              return (
                <div style={{ marginTop:10, padding:'10px 12px', background:'#F0FDF4', border:'1px solid #BBF7D0', borderRadius:8, fontSize:12, color:'#166534', lineHeight:1.5 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#15803D', textTransform:'uppercase', letterSpacing:.5, marginBottom:4 }}>Prévia para {firstSelected.name}</div>
                  {bulk.message.replace(/\{\{nome\}\}/g, firstSelected.name.split(' ')[0])}
                </div>
              );
            })()}
          </div>

          <div>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <Icon name="Users" size={16} color="#0A1F44" />
                <span style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>Destinatários</span>
                <span style={{ fontSize:11, color:'#9CA3AF' }}>{selectedCount} de {bulk.recipients.length} selecionados</span>
              </div>
              <button
                onClick={() => toggleAll(!allSelected)}
                style={{ padding:'4px 10px', borderRadius:6, border:'1px solid #E2E8F0', background:'#fff', fontSize:11, fontWeight:600, color:'#6B7280', cursor:'pointer' }}
              >{allSelected ? 'Desmarcar todos' : 'Selecionar todos'}</button>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:6, maxHeight:240, overflow:'auto', border:'1px solid #E2E8F0', borderRadius:10, padding:6 }}>
              {bulk.recipients.length === 0 ? (
                <div style={{ padding:'18px 14px', textAlign:'center', fontSize:12, color:'#9CA3AF' }}>Nenhum destinatário disponível.</div>
              ) : bulk.recipients.map(c => {
                const checked = !!bulk.selected[c.id];
                const accent = bulk.type === 'birthday' ? '#7C3AED' : '#EF4444';
                return (
                  <label key={c.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 10px', borderRadius:8, background: checked ? UMK.hexToRgba(accent,.06) : '#fff', cursor:'pointer', transition:'background .15s' }}>
                    <input type="checkbox" checked={checked} onChange={() => toggleRecipient(c.id)} style={{ accentColor: accent, cursor:'pointer' }} />
                    <Avatar name={c.name} color={accent} size={28} />
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{c.name}</div>
                      <div style={{ fontSize:11, color:'#9CA3AF' }}>
                        {bulk.type === 'birthday'
                          ? `${UMK.formatDate(c.birthdate,'dd/MM')} · ${UMK.age(c.birthdate)} anos`
                          : `Ausente há ${UMK.daysBetween(c.lastVisit, window.JF.TODAY)} dias`}
                      </div>
                    </div>
                    <span style={{ fontSize:11, color:'#9CA3AF' }}>{c.phone || ''}</span>
                  </label>
                );
              })}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { Marketing });
