// js/components/pages/ClienteTimeline.jsx
// [Wave 28 v224.9 NUCLEAR EXTRACT 2026-05-24] 450L → ~180L (-60%)
// Padrão Wave 15 VendaTimeline + Wave 27 OrcamentoTimeline cravado (3ª replicação).
// 4 extracts (1 lib + 3 widgets).
//
// Cliente 360º — visão unificada de 1 cliente: KPIs + avisos + ações rápidas + timeline.
// Criado em 2026-05-05 (sistema 4 onda 2) · NUCLEAR refactor 2026-05-24.
//
// Props (15): client, clients, sales, quotes, products, receivables, allUsers, user,
//             health, todayOutreach, onBack, onOpenSale, onOpenQuote, onAddCredit, onEdit
//
// Deps runtime: fmt, fmtDate, today, saleFinalTotal, Icon, znxGuard, sb, toast, computeNextAction
(function() {
  'use strict';
  const {useState, useEffect, useMemo} = React;

  // regra_estender_bloco_refs_fail_loud — bloco agregado (4 refs novos · greenfield)
  // [v224.55 FIX-PREV-1 2026-05-28] vars+check MOVED to component body (preventivo · Babel transpile race)
  // regra_validacao_helpers_runtime_quando_ordem_scripts_uncertain

  function ClienteTimeline({client, clients, sales, quotes, products, receivables, allUsers, user, health, todayOutreach, onBack, onOpenSale, onOpenQuote, onAddCredit, onEdit}){
    // [v224.55 FIX-PREV-1 2026-05-28] vars+check em render time
    const calcs = window.ZNX && window.ZNX.clienteTimeline && window.ZNX.clienteTimeline.calcs;
    const ctW = (window.ZNX && window.ZNX.widgets && window.ZNX.widgets.clienteTimeline) || {};
    const _missing = [];
    if(!calcs) _missing.push('clienteTimeline.calcs');
    if(!ctW.TimelineHeader) _missing.push('TimelineHeader');
    if(!ctW.AvisosPanel) _missing.push('AvisosPanel');
    if(!ctW.TimelineList) _missing.push('TimelineList');
    if(_missing.length){
      const _msg = '[ClienteTimeline v224.9] widgets faltando: ' + _missing.join(', ');
      console.error(_msg);
      if(window.Sentry && typeof window.Sentry.captureMessage === 'function'){
        window.Sentry.captureMessage(_msg, 'error');
      }
    }
    if(!client){
      return (
        <div style={{padding:40,textAlign:'center',color:'#6B7280'}}>
          Nenhum cliente selecionado. Volte pra Lista e clique em um cliente.
        </div>
      );
    }

    // ========= DADOS DERIVADOS via factories =========
    const clientSales = useMemo(function(){return calcs.computeClientSales(sales, client.id);}, [sales, client.id]);
    const clientQuotes = useMemo(function(){return calcs.computeClientQuotes(quotes, client.id);}, [quotes, client.id]);
    const clientReceivables = useMemo(function(){return calcs.computeClientReceivables(receivables, client.id);}, [receivables, client.id]);

    // Histórico de crédito + devoluções (async via factories)
    const [creditHistory, setCreditHistory] = useState([]);
    const [devolucoes, setDevolucoes] = useState([]);

    useEffect(function(){
      if(!client || !client.id) return;
      let cancelled = false;
      calcs.fetchCreditHistory(client.id).then(function(data){if(!cancelled) setCreditHistory(data);});
      const saleIds = clientSales.map(function(s){return s.id;}).filter(Boolean);
      calcs.fetchDevolucoes(saleIds).then(function(data){if(!cancelled) setDevolucoes(data);});
      return function(){cancelled = true;};
    }, [client && client.id, clientSales.length]);

    // KPIs + avisos + topProducts + waLink + timeline via factories
    const kpis = useMemo(function(){return calcs.computeKpis(client, clientSales, clientQuotes);}, [clientSales, clientQuotes, client]);
    const avisos = useMemo(function(){return calcs.computeAvisos(client, kpis, clients);}, [kpis, client, clients]);
    const topProducts = useMemo(function(){return calcs.computeTopProducts(clientSales, products);}, [clientSales, products]);
    const waLink = calcs.buildWhatsAppLink(client, clientSales, clientQuotes);
    const timeline = useMemo(function(){return calcs.computeTimeline(client, clientSales, clientQuotes, clientReceivables, creditHistory, devolucoes);}, [clientSales, clientQuotes, devolucoes, creditHistory, clientReceivables, client]);

    // Filter state + filteredTimeline
    const [filterTypes, setFilterTypes] = useState(function(){return new Set(['sale','quote','devolucao','credit','payment','created']);});
    function toggleFilter(t){
      setFilterTypes(function(prev){
        const next = new Set(prev);
        if(next.has(t)) next.delete(t); else next.add(t);
        return next;
      });
    }
    const filteredTimeline = useMemo(function(){return calcs.filterTimeline(timeline, filterTypes);}, [timeline, filterTypes]);

    // UI vars
    const isPj = client.type === 'PJ';
    const sellerName = ((allUsers||[]).find(function(u){return u.id === client.seller_id || u.id === client.sellerId;}) || {}).name || client.createdBy || '—';

    return (
      <div>
        {/* Header + KPIs (extraído pra TimelineHeader) */}
        {ctW.TimelineHeader && (
          <ctW.TimelineHeader
            client={client}
            kpis={kpis}
            isPj={isPj}
            sellerName={sellerName}
            onBack={onBack}
          />
        )}

        {/* [Onda 4a-fix] TodayOutreach — Missão Cumprida (preservado inline · não vai em widget) */}
        {todayOutreach ? (function(){
          const sentTime = new Date(todayOutreach.sent_at).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
          return (
            <div style={{background:'linear-gradient(135deg, #16A34A12, #16A34A04)',border:'2px solid #16A34A55',borderRadius:12,padding:'16px 20px',marginBottom:14,boxShadow:'0 2px 8px #16A34A20'}}>
              <div style={{display:'flex',alignItems:'center',gap:14}}>
                <div style={{fontSize:36,lineHeight:1}}>✅</div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1.2,fontWeight:700,marginBottom:3}}>🎯 Missão cumprida hoje</div>
                  <div style={{fontSize:16,fontWeight:700,color:'#16A34A',marginBottom:3}}>Mensagem enviada às {sentTime} por {todayOutreach.vendedora_name||'—'}</div>
                  <div style={{fontSize:12,color:'#6B7280',lineHeight:1.4}}>Não envie de novo hoje — espere o cliente responder ou volte amanhã.</div>
                  {todayOutreach.message_sent && (
                    <details style={{marginTop:8}}>
                      <summary style={{cursor:'pointer',fontSize:11,color:'#16A34A',fontWeight:600}}>Ver mensagem enviada</summary>
                      <div style={{marginTop:6,fontSize:12,color:'#374151',background:'#FFFFFF',padding:'8px 12px',borderRadius:6,fontStyle:'italic',lineHeight:1.5,border:'1px solid #16A34A22'}}>"{todayOutreach.message_sent}"</div>
                    </details>
                  )}
                </div>
              </div>
            </div>
          );
        })() : (function(){
          // [Onda 3b] Próxima Ação Sugerida — preservado inline
          if(typeof computeNextAction !== 'function') return null;
          const action = computeNextAction(client, sales, quotes, health, topProducts);
          if(!action) return null;
          return (
            <div style={{background:'linear-gradient(135deg, '+action.color+'10, '+action.color+'03)',border:'2px solid '+action.color+'55',borderRadius:12,padding:'16px 20px',marginBottom:14,boxShadow:'0 2px 8px '+action.color+'20'}}>
              <div style={{display:'flex',alignItems:'center',gap:14}}>
                <div style={{fontSize:36,lineHeight:1}}>{action.icon}</div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:11,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1.2,fontWeight:700,marginBottom:3}}>🎯 Próxima Ação Sugerida</div>
                  <div style={{fontSize:16,fontWeight:700,color:action.color,marginBottom:3}}>{action.title}</div>
                  <div style={{fontSize:12,color:'#6B7280',lineHeight:1.4}}>{action.description}</div>
                </div>
                {action.whatsappLink && (
                  <a href={action.whatsappLink} target="_blank" rel="noopener"
                    style={{display:'flex',alignItems:'center',gap:6,padding:'10px 18px',background:'#25D366',color:'#FFFFFF',borderRadius:8,fontWeight:700,fontSize:13,textDecoration:'none',whiteSpace:'nowrap',boxShadow:'0 2px 6px rgba(37,211,102,.3)'}}
                    title="Enviar mensagem pré-formatada no WhatsApp">
                    📱 Mandar agora
                  </a>
                )}
              </div>
            </div>
          );
        })()}

        {/* [Onda 3a] Health Score — barra horizontal (preservado inline) */}
        {health && (
          <div style={{background:'#FFFFFF',border:'1.5px solid '+health.color+'33',borderRadius:12,padding:'14px 18px',marginBottom:16,boxShadow:'0 1px 2px rgba(0,0,0,0.04)'}}>
            <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:8}}>
              <div style={{fontSize:30}}>{health.emoji}</div>
              <div style={{flex:1}}>
                <div style={{fontSize:13,color:'#9CA3AF',textTransform:'uppercase',letterSpacing:1,fontWeight:600,marginBottom:2}}>Health Score</div>
                <div style={{display:'flex',alignItems:'baseline',gap:10}}>
                  <span style={{fontSize:28,fontWeight:800,color:health.color}}>{health.score}</span>
                  <span style={{fontSize:14,color:'#9CA3AF'}}>/100</span>
                  <span style={{fontSize:16,fontWeight:700,color:health.color,marginLeft:4}}>{health.label}</span>
                </div>
              </div>
              <div style={{textAlign:'right',fontSize:11,color:'#6B7280',lineHeight:1.5}}>
                <div>Recência: <strong style={{color:health.color}}>{health.recencyPts}</strong>/40</div>
                <div>Frequência: <strong style={{color:health.color}}>{health.frequencyPts}</strong>/30</div>
                <div>Valor: <strong style={{color:health.color}}>{health.valuePts}</strong>/30</div>
              </div>
            </div>
            <div style={{height:8,background:'#F3F4F6',borderRadius:4,overflow:'hidden',display:'flex'}}>
              <div style={{width:(health.recencyPts/40*40)+'%',background:'#16A34A',transition:'width .3s'}} title={'Recência '+health.recencyPts+'/40'}/>
              <div style={{width:(health.frequencyPts/30*30)+'%',background:'#2563EB',transition:'width .3s'}} title={'Frequência '+health.frequencyPts+'/30'}/>
              <div style={{width:(health.valuePts/30*30)+'%',background:'#C8A951',transition:'width .3s'}} title={'Valor '+health.valuePts+'/30'}/>
            </div>
            <div style={{display:'flex',justifyContent:'space-between',marginTop:4,fontSize:10,color:'#9CA3AF'}}>
              <span>0</span><span>30</span><span>60</span><span>80</span><span>100</span>
            </div>
          </div>
        )}

        {/* Avisos + Ações rápidas (extraído pra AvisosPanel) */}
        {ctW.AvisosPanel && (
          <ctW.AvisosPanel
            avisos={avisos}
            client={client}
            waLink={waLink}
            user={user}
            onOpenSale={onOpenSale}
            onOpenQuote={onOpenQuote}
            onAddCredit={onAddCredit}
            onEdit={onEdit}
          />
        )}

        {/* 2-col grid: Top Produtos + Timeline (extraído pra TimelineList) */}
        {ctW.TimelineList && (
          <ctW.TimelineList
            topProducts={topProducts}
            filteredTimeline={filteredTimeline}
            filterTypes={filterTypes}
            toggleFilter={toggleFilter}
          />
        )}
      </div>
    );
  }

  // Namespace
  window.ZNX = window.ZNX || {};
  window.ZNX.pages = window.ZNX.pages || {};
  window.ZNX.pages.ClienteTimeline = ClienteTimeline;
  window.ClienteTimeline = ClienteTimeline; // Compatibilidade global
  // [Wave 28 marker v224.9] confirma extract executado
  window.ClienteTimeline_v224_9_wave28 = true;
})();
