// js/components/widgets/MonthMetaCard.jsx
// [Wave 12A v223.34 20260520] Extraído de DashboardV2.jsx L325-379 + L822-850 (modal) + state/funcs
// Card "MÊS" — faturamento + lucro bruto/líquido + barra meta global + modal editar meta
//
// Props:
//   user, currentMonth, monthRevenue, monthProfit, monthMargin,
//   monthLucroLiquido, monthMarginLiquida, monthGastos, monthSales (array),
//   metasEmpresa, setMetasEmpresa, metas
//
// Deps runtime: window.fmt, window.Modal, window.toast
(function(){
  'use strict';
  const {useState} = React;

  function MonthMetaCard(props){
    const {
      user, currentMonth,
      monthRevenue=0, monthProfit=0, monthMargin=0,
      monthLucroLiquido=0, monthMarginLiquida=0, monthGastos=0,
      monthSales=[], metasEmpresa={}, setMetasEmpresa, metas={}
    } = props;

    const fmt = typeof window.fmt === 'function' ? window.fmt : (v)=>String(v);
    const Modal = window.Modal;
    const toast = window.toast || ((m)=>console.log('[toast]',m));

    const [editMetaEmpresaModal,setEditMetaEmpresaModal] = useState(false);
    const [editMetaValor,setEditMetaValor] = useState('');

    // [P103 EDIT7 v224.242] seletor de mes (corrente-3 leitura .. corrente+3 edicao).
    // metasEmpresa NAO passa pelo commission_calculate — a resolucao herdada abaixo e o
    // que impede a barra de virar "41% de R$ 0" no dia 01/09 (EDIT 7.3).
    const [mesSel,setMesSel] = useState(currentMonth);
    const mesEditavel = mesSel >= currentMonth;
    const _rEmp = window.znxMetaEmpresaResolve ? window.znxMetaEmpresaResolve(metasEmpresa, mesSel)
                                               : {valor:Number(metasEmpresa?.[mesSel])||0, mesOrigem:mesSel};
    const metaHerdada = _rEmp.mesOrigem && _rEmp.mesOrigem !== mesSel;
    const metaEmpresaAtual = Number(_rEmp.valor) || 0;
    const pctMetaEmpresa = metaEmpresaAtual>0 ? Math.min(100,(monthRevenue/metaEmpresaAtual)*100) : 0;
    const faltaMetaEmpresa = Math.max(0, metaEmpresaAtual - monthRevenue);
    const now = new Date();
    // [v224.232 20260805] dias UTEIS, não corridos. A ZAYNEX não trabalha domingo, e o
    // denominador antigo (diasNoMes - getDate()) contava os 4 domingos de agosto: pedia
    // R$ 99.767,89/dia quando o número real é R$ 128.273,00/dia.
    const _du = window.ZNX.diasUteis;
    const _ritmo = _du.ritmoNecessario(faltaMetaEmpresa, now);
    const diasRestantes = _ritmo.dias;
    const precisaPorDia = faltaMetaEmpresa>0 ? _ritmo.valor : 0;
    const metaCor = pctMetaEmpresa>=100?'#16A34A':pctMetaEmpresa>=95?'#22C55E':pctMetaEmpresa>=80?'#2563EB':pctMetaEmpresa>=60?'#EAB308':pctMetaEmpresa>=40?'#EA580C':pctMetaEmpresa>=20?'#DC2626':'#991B1B';

    function openMetaEmpresaModal(){
      setEditMetaValor(String(metaEmpresaAtual||''));
      setEditMetaEmpresaModal(true);
    }
    function saveMetaEmpresa(){
      const v = Number(editMetaValor);
      if(isNaN(v) || v<0){ toast('⚠️ Valor inválido','warning'); return; }
      if(!mesEditavel){ toast('⚠️ Mês fechado — não editável (P103)','warning'); return; }
      if(typeof setMetasEmpresa !== 'function'){
        console.error('[ZNX Wave 12A] MonthMetaCard: setMetasEmpresa não disponível');
        toast('❌ Erro: meta não pôde ser salva','error');
        return;
      }
      // [P103 EDIT7] grava o MES SELECIONADO — e so ele. Agosto intacto ao criar setembro.
      setMetasEmpresa(prev => ({...(prev||{}), [mesSel]: v}));
      toast('✅ Meta empresa de '+(window.znxMesLabel?window.znxMesLabel(mesSel):mesSel)+' definida: '+fmt(v));
      setEditMetaEmpresaModal(false);
    }

    return (
      <>
        <div className="card" style={{padding:18}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',flexWrap:'wrap',gap:8,marginBottom:10}}>
            <div>
              <div style={{fontSize:11,color:'#9CA3AF',fontWeight:700,textTransform:'uppercase',letterSpacing:1.5,display:'flex',alignItems:'center',gap:8}}>
                📅 {mesSel===currentMonth?'Este mês':'Mês'} —
                <select value={mesSel} onChange={e=>setMesSel(e.target.value)}
                        style={{fontSize:11,fontWeight:700,border:'1px solid #D1D5DB',borderRadius:6,padding:'2px 6px',color:'#374151',background:'#fff'}}>
                  {(window.znxMesesSeletor?window.znxMesesSeletor():[{mes:currentMonth,label:currentMonth,editavel:true}]).map(o=>(
                    <option key={o.mes} value={o.mes}>{o.label}{o.editavel?'':' · fechado'}</option>
                  ))}
                </select>
                {metaHerdada && metaEmpresaAtual>0 && (
                  <span title={'Sem meta definida para '+(window.znxMesLabel?window.znxMesLabel(mesSel):mesSel)+' — herdando'}
                        style={{fontSize:10,fontWeight:700,color:'#92700A',background:'#FFFBEB',border:'1px solid #B8984066',borderRadius:999,padding:'1px 8px',textTransform:'none',letterSpacing:0}}>
                    herdada de {window.znxMesLabel?window.znxMesLabel(_rEmp.mesOrigem):_rEmp.mesOrigem}
                  </span>
                )}
              </div>
              <div style={{display:'flex',alignItems:'baseline',gap:14,flexWrap:'wrap',marginTop:6}}>
                <div style={{fontSize:30,fontWeight:900,color:'#1B2A4A'}}>{fmt(monthRevenue)}</div>
                <div style={{fontSize:13,color:'#6B7280'}}>faturado</div>
                <div style={{borderLeft:'2px solid #E5E7EB',height:22,margin:'0 6px'}}/>
                <div style={{fontSize:18,fontWeight:700,color:'#15803D'}}>{fmt(monthProfit)}</div>
                <div style={{fontSize:12,color:'#6B7280'}}>bruto · margem {monthMargin.toFixed(1)}%</div>
                <div style={{borderLeft:'2px solid #E5E7EB',height:22,margin:'0 6px'}}/>
                <div style={{fontSize:18,fontWeight:700,color:monthLucroLiquido>=0?'#16A34A':'#DC2626'}}>{fmt(monthLucroLiquido)}</div>
                <div style={{fontSize:12,color:'#6B7280'}}>líquido · margem {monthMarginLiquida.toFixed(1)}%{monthGastos>0?` · −${fmt(monthGastos)} gastos`:''}</div>
                <div style={{borderLeft:'2px solid #E5E7EB',height:22,margin:'0 6px'}}/>
                <div style={{fontSize:14,fontWeight:600,color:'#374151'}}>{monthSales.length} vendas</div>
              </div>
            </div>
            {user.role==='admin' && (
              <button onClick={mesEditavel?openMetaEmpresaModal:undefined} disabled={!mesEditavel}
                      title={mesEditavel?undefined:'Mês fechado — editar mês passado reescreveria a base de um período já julgado (P103).'}
                      style={{padding:'7px 12px',background:'#FFFFFF',color:mesEditavel?'#7C3AED':'#9CA3AF',border:'1px solid '+(mesEditavel?'#7C3AED44':'#D1D5DB'),borderRadius:6,fontSize:12,fontWeight:600,cursor:mesEditavel?'pointer':'not-allowed'}}>
                🎯 {(!metaHerdada&&metaEmpresaAtual>0)?'Editar':'Definir'} meta empresa
              </button>
            )}
          </div>

          {metaEmpresaAtual>0 ? (
            <div>
              <div style={{height:14,background:'#F3F4F6',borderRadius:7,overflow:'hidden',position:'relative'}}>
                <div style={{
                  height:'100%',
                  width:Math.min(100,pctMetaEmpresa)+'%',
                  background:`linear-gradient(90deg,${metaCor}88,${metaCor})`,
                  transition:'width .8s cubic-bezier(.34,1.4,.64,1)',
                  boxShadow:`0 0 8px ${metaCor}66`,
                }}/>
                <div style={{position:'absolute',top:0,bottom:0,left:'95%',width:2,background:'#16A34A',opacity:0.5}} title="Tolerância 95%"/>
              </div>
              <div style={{display:'flex',justifyContent:'space-between',marginTop:6,fontSize:12,color:'#6B7280',flexWrap:'wrap',gap:8}}>
                <span><strong style={{color:metaCor,fontSize:14}}>{pctMetaEmpresa.toFixed(1)}%</strong> da meta de <strong>{fmt(metaEmpresaAtual)}</strong></span>
                {pctMetaEmpresa>=100?(
                  <span style={{color:'#16A34A',fontWeight:700}}>🎉 META BATIDA!</span>
                ):(
                  <span>Faltam <strong style={{color:'#DC2626'}}>{fmt(faltaMetaEmpresa)}</strong> · {_du.rotuloDias(diasRestantes)} · <strong>{fmt(precisaPorDia)}/dia útil</strong></span>
                )}
              </div>
            </div>
          ):(
            <div style={{padding:14,background:'#F9FAFB',border:'1px dashed #D1D5DB',borderRadius:8,textAlign:'center',fontSize:12,color:'#6B7280'}}>
              Meta da empresa não definida para {window.znxMesLabel?window.znxMesLabel(mesSel):mesSel}{mesSel>currentMonth?' (nem herdável de mês anterior)':''}.
              {user.role==='admin'?' Defina no botão acima.':' Aguardando admin.'}
            </div>
          )}
        </div>

        {/* MODAL Meta Empresa */}
        {editMetaEmpresaModal && Modal && (
          <Modal title={'🎯 Meta global empresa — '+(window.znxMesLabel?window.znxMesLabel(mesSel):mesSel)} onClose={()=>setEditMetaEmpresaModal(false)}>
            <div style={{display:'flex',flexDirection:'column',gap:14}}>
              <div style={{padding:'10px 14px',background:'#EEF2FF',border:'1px solid #6366F144',borderRadius:8,fontSize:12,color:'#3730A3'}}>
                💡 Esta meta agrega TODAS as vendedoras + canais (não substitui metas individuais).
                <br/>
                Soma das metas individuais hoje: <strong>{fmt(Object.values(metas||{}).reduce((a,b)=>a+(Number(b)||0),0))}</strong>
              </div>
              <div>
                <label style={{fontSize:12,fontWeight:600,color:'#374151',marginBottom:4,display:'block'}}>Meta total da empresa pra {window.znxMesLabel?window.znxMesLabel(mesSel):mesSel} — gravando ESTE mês, não outro</label>
                <input
                  type="number"
                  value={editMetaValor}
                  onChange={e=>setEditMetaValor(e.target.value)}
                  placeholder="Ex: 1500000"
                  min="0" step="1000"
                  style={{width:'100%',padding:'10px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14}}
                  autoFocus
                  onKeyDown={e=>{if(e.key==='Enter')saveMetaEmpresa();}}
                />
              </div>
              <div style={{display:'flex',gap:10,justifyContent:'flex-end'}}>
                <button onClick={()=>setEditMetaEmpresaModal(false)} style={{padding:'10px 20px',background:'#FFFFFF',color:'#374151',border:'1px solid #D1D5DB',borderRadius:6,fontSize:14,fontWeight:600,cursor:'pointer'}}>Cancelar</button>
                <button onClick={saveMetaEmpresa} style={{padding:'10px 20px',background:'#7C3AED',color:'#FFFFFF',border:'none',borderRadius:6,fontSize:14,fontWeight:700,cursor:'pointer'}}>🎯 Salvar meta</button>
              </div>
            </div>
          </Modal>
        )}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.MonthMetaCard = MonthMetaCard;
  window.MonthMetaCard = MonthMetaCard;
})();
