/* COMERCIAL · DAILY BRIEFING — briefing diário IA, mobile-first
   Layout: header (saudação + bloco IA + botões) → card pipeline → BP */

// ── Helpers de semáforo ──────────────────────────────────────────────────────
const _semColor = c =>
  c === 'g' ? 'var(--dgd-green-700,#15803d)'
  : c === 'y' ? 'var(--dgd-yellow-600,#ca8a04)'
  : c === 'r' ? 'var(--dgd-red-700,#b91c1c)'
  : 'var(--dgd-fg-2)';
const _semBg = c =>
  c === 'g' ? 'var(--dgd-green-50,#f0fdf4)'
  : c === 'y' ? 'var(--dgd-yellow-50,#fefce8)'
  : c === 'r' ? 'var(--dgd-red-50,#fef2f2)'
  : 'var(--dgd-bg-surface-2,#f8f9fb)';

// ── BriefingKPICard ──────────────────────────────────────────────────────────────────
const BriefingKPICard = ({ label, value, sub, color, bar, desc }) => {
  const dot = color === 'g' ? 'var(--dgd-green-600,#16a34a)'
    : color === 'y' ? 'var(--dgd-yellow-500,#eab308)'
    : color === 'r' ? 'var(--dgd-red-600,#dc2626)'
    : 'var(--dgd-primary-400,#60a5fa)';
  const valC = color === 'g' ? 'var(--dgd-green-700,#15803d)'
    : color === 'y' ? 'var(--dgd-yellow-700,#a16207)'
    : color === 'r' ? 'var(--dgd-red-700,#b91c1c)'
    : 'var(--dgd-fg-1)';
  return (
    <div title={desc} style={{
      background: 'var(--dgd-bg-surface)',
      border: '1px solid var(--dgd-border,#e2e6ea)',
      borderRadius: 'var(--dgd-radius-lg,10px)',
      padding: '14px 16px',
      display: 'flex', flexDirection: 'column', gap: 3,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        <div style={{ width: 7, height: 7, borderRadius: '50%', background: dot, flexShrink: 0 }} />
        <div style={{ fontSize: 9, fontFamily: 'var(--dgd-font-mono)', color: 'var(--dgd-fg-3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
          {label}
        </div>
      </div>
      <div style={{ fontSize: 24, fontWeight: 700, color: valC, letterSpacing: '-0.02em', lineHeight: 1 }}>
        {value}
      </div>
      {bar != null && (
        <div style={{ height: 2, background: 'var(--dgd-grey-100,#f3f4f6)', borderRadius: 2, overflow: 'hidden', margin: '4px 0 2px' }}>
          <div style={{ height: '100%', width: `${Math.round(Math.min(bar, 1) * 100)}%`, background: dot, borderRadius: 2, transition: 'width 0.4s' }} />
        </div>
      )}
      <div style={{ fontSize: 10.5, color: 'var(--dgd-fg-3)', marginTop: 1 }}>{sub || ''}</div>
    </div>
  );
};

// ── DigiBriefingKPICards ─────────────────────────────────────────────────────────────
// Todos os dados vêm por props (sem hooks próprios) — pai fornece tudo
const DigiBriefingKPICards = ({ pipelineData, bpArr, fm, faturado, margemMensal }) => {
  const curMonth = new Date().getMonth(); // 0-indexed

  const sumSlice = (arr, end) => (arr || []).slice(0, end).reduce((s, v) => s + (v || 0), 0);
  const sumArr   = arr => (arr || []).reduce((s, v) => s + (v || 0), 0);
  const fmtE = v => v == null ? '—'
    : v >= 1e6 ? (v / 1e6).toFixed(1).replace('.', ',') + 'M €'
    : v >= 1e3 ? Math.round(v / 1e3) + 'k €'
    : Math.round(v) + ' €';
  const sem = (v, thG, thY) => v == null ? null : v >= thG ? 'g' : v >= thY ? 'y' : 'r';

  // BP
  const bpYTD  = bpArr ? sumSlice(bpArr, curMonth + 1) : null;
  const bpRest = bpArr ? sumArr(bpArr.slice(curMonth + 1)) : null;
  const bpAnual = bpArr ? sumArr(bpArr) : null;

  // Pipeline
  const wonYTD  = pipelineData?.wonValue || null;
  const openVal = pipelineData ? (pipelineData.openValue || 0) + (pipelineData.priorValue || 0) : null;

  // FM pipeline (win rate)
  const wonFM  = fm ? sumSlice(fm.wonValor  || [], curMonth + 1) : null;
  const lostFM = fm ? sumSlice(fm.lostValor || [], curMonth + 1) : null;

  // YTD Primavera (margem)
  const fatYTD = faturado     ? sumSlice(faturado,     curMonth + 1) : null;
  const marYTD = margemMensal ? sumSlice(margemMensal, curMonth + 1) : null;

  // Previsao — OPs estrela (Opt_Top)
  const allRecs  = [...(pipelineData?.records || []).filter(r => r.Status === 'OPEN'), ...(pipelineData?.priorRecords || [])];
  const previsao = pipelineData
    ? allRecs.filter(r => r.Opt_Top === '1' || r.Opt_Top === 1)
             .reduce((s, r) => s + (parseFloat(r.Produto_Valor_K || 0) * 1000), 0) || null
    : null;

  // KPI values
  const bpAch     = (wonYTD != null && bpYTD > 0)                    ? wonYTD / bpYTD : null;
  const cobertura = (openVal != null && bpRest   > 0)                ? openVal / bpRest
                  : (openVal != null && bpAnual > 0)                  ? openVal / bpAnual : null;
  const winRate   = (wonFM  != null && (wonFM + lostFM) > 0)         ? wonFM / (wonFM + lostFM) : null;
  const margem    = (fatYTD > 0     && marYTD != null)                ? marYTD / fatYTD : null;

  // RPC Score composto
  const rpcColors = [sem(bpAch,0.95,0.70), sem(cobertura,4,2), sem(winRate,0.25,0.15), sem(margem,0.35,0.25)].filter(Boolean);
  const rpcScore  = rpcColors.length
    ? rpcColors.reduce((s, c) => s + (c === 'g' ? 2 : c === 'y' ? 1 : 0), 0) / (rpcColors.length * 2)
    : null;

  const kpis = [
    {
      label: 'BP Achievement',
      value: bpAch != null ? Math.round(bpAch * 100) + '%' : '—',
      sub:   bpYTD  ? `Meta YTD ${fmtE(bpYTD)}` : '',
      color: sem(bpAch, 0.95, 0.70),
      bar:   bpAch,
      desc:  'Faturado YTD vs objectivo BP',
    },
    {
      label: 'Cobertura Pipeline',
      value: cobertura != null ? cobertura.toFixed(1) + '\u00d7' : '—',
      sub:   openVal != null ? `${fmtE(openVal)} activo` : '',
      color: sem(cobertura, 4, 2),
      bar:   cobertura != null ? Math.min(cobertura / 6, 1) : null,
      desc:  'Pipeline activo vs BP restante do ano',
    },
    {
      label: 'Win Rate',
      value: winRate != null ? Math.round(winRate * 100) + '%' : '—',
      sub:   wonFM != null ? `${fmtE(wonFM)} ganho YTD` : 'a carregar...',
      color: sem(winRate, 0.25, 0.15),
      bar:   winRate != null ? Math.min(winRate / 0.5, 1) : null,
      desc:  'Taxa de conversao: valor ganho vs perdido YTD',
    },
    {
      label: 'Margem Bruta',
      value: margem != null ? Math.round(margem * 100) + '%' : '—',
      sub:   marYTD != null ? `${fmtE(marYTD)} margem YTD` : fatYTD != null ? 'sem dados de margem' : 'a carregar...',
      color: sem(margem, 0.35, 0.25),
      bar:   margem != null ? Math.min(margem / 0.5, 1) : null,
      desc:  'Margem bruta sobre facturacao YTD (Primavera)',
    },
    {
      label: 'Previsao Quentes',
      value: previsao != null ? fmtE(previsao) : '—',
      sub:   (previsao != null && bpRest > 0) ? `${Math.round(previsao / bpRest * 100)}% do BP restante` : 'OPs estrela',
      color: (previsao != null && bpRest > 0) ? sem(previsao / bpRest, 1.0, 0.5) : null,
      bar:   (previsao != null && bpAnual > 0) ? Math.min(previsao / bpAnual, 1) : null,
      desc:  'Valor total OPs estrela (Opt_Top) — previsao directa',
    },
    {
      label: 'RPC Rating',
      value: rpcScore != null ? Math.round(rpcScore * 100) + '%' : '—',
      sub:   rpcColors.length
        ? `${rpcColors.filter(c => c === 'g').length} verde · ${rpcColors.filter(c => c === 'y').length} amarelo · ${rpcColors.filter(c => c === 'r').length} vermelho`
        : '',
      color: sem(rpcScore, 0.65, 0.40),
      bar:   rpcScore,
      desc:  'Score composto: BP + Cobertura + WinRate + Margem',
    },
  ];

  const loading = !pipelineData && !bpArr;

  if (loading) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        {[1,2,3,4,5,6].map(i => (
          <div key={i} style={{ height: 88, borderRadius: 'var(--dgd-radius-lg,10px)', background: 'var(--dgd-grey-100,#f3f4f6)', border: '1px solid var(--dgd-border,#e2e6ea)' }} />
        ))}
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
      {kpis.map(kpi => <BriefingKPICard key={kpi.label} {...kpi} />)}
    </div>
  );
};

const ScreenComercialDailyBriefing = ({ onOpenChat, onNav, userName, vendedorId }) => {
  const { isMobile } = window.useBreakpoint ? window.useBreakpoint() : { isMobile: window.innerWidth < 640 };
  const [bpStage, setBpStage] = React.useState(null);

  // Data hooks (exportados de screen_comercial_dashboard.jsx)
  const erpCodes     = window.useDashErpCodes?.(vendedorId);
  const pipeline     = window.useDashPipeline?.(vendedorId) || {};
  const pipelineData = pipeline.data || null;
  const bpArr        = window.useDashRPCBP?.(vendedorId, window.DASH_RPC_ANO);
  const fm           = window.useDashRPCFM?.(vendedorId, window.DASH_RPC_ANO);
  const { faturado, margemMensal } = window.useDashRPCYTD?.(vendedorId, window.DASH_RPC_ANO) || {};

  // Saudação
  const firstName = (userName || 'Comercial').split(' ')[0];
  const nowStr = (() => {
    const d = new Date();
    const dias  = ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];
    const meses = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
    return `${dias[d.getDay()]}, ${d.getDate()} de ${meses[d.getMonth()]}`;
  })();
  const greeting = React.useMemo(() => {
    const G = window.HERO_GREETINGS;
    if (!G) return `Bom dia, ${firstName}.`;
    const h = new Date().getHours();
    const period = h < 5 ? 'madrugada' : h < 12 ? 'manha' : h < 19 ? 'tarde' : 'noite';
    const pool = G[period](firstName);
    return pool[Math.floor(Math.random() * pool.length)];
  }, [firstName]);

  // Resumo pipeline
  const fmtE = v => v == null ? '—'
    : v >= 1e6 ? (v / 1e6).toFixed(1).replace('.', ',') + 'M €'
    : v >= 1e3 ? Math.round(v / 1e3) + 'k €'
    : Math.round(v) + ' €';

  const bpYTD = bpArr
    ? bpArr.slice(0, new Date().getMonth() + 1).reduce((s, v) => s + (v || 0), 0)
    : null;

  const pipeSummary = pipelineData ? (() => {
    const liveTotal    = (pipelineData.openValue ?? 0) + (pipelineData.priorValue ?? 0);
    const liveOpsCount = (pipelineData.active ?? 0) + (pipelineData.priorActive ?? 0);
    const liveWon      = pipelineData.wonValue || 0;
    const bottleneck   = [...(pipelineData.openByStage || [])].sort((a, b) => b.value - a.value)[0];
    const pctBP        = bpYTD ? Math.round(liveWon / bpYTD * 100) : null;
    return { liveTotal, liveOpsCount, liveWon, bottleneck, pctBP };
  })() : null;

  const pad = isMobile ? 16 : 24;
  const sk  = { borderRadius: 4, background: 'var(--dgd-grey-200,#eceef4)' };

  return (
    <div className="dgd-design-system scrollbar"
         style={{ height: '100%', overflow: 'auto', background: 'var(--dgd-bg-app)' }}>
      <div style={{ padding: `${pad}px ${pad}px 60px`, maxWidth: '100%', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* ── HEADER: saudação + IA + botões ─────────────────────────────── */}
        <div style={{ background: 'var(--dgd-bg-surface)', borderRadius: 'var(--dgd-radius-xl)', boxShadow: 'var(--dgd-shadow-card)', padding: pad, display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Data + saudação + resumo pipeline */}
          <div>
            <div style={{ fontSize: 10, fontFamily: 'var(--dgd-font-mono)', color: 'var(--dgd-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>
              Comercial · {nowStr}
            </div>
            <h1 style={{ margin: 0, fontSize: isMobile ? 22 : 28, fontWeight: 700, letterSpacing: '-0.015em', color: 'var(--dgd-fg-1)', lineHeight: 1.2 }}>
              {greeting}
            </h1>
            {pipeSummary ? (
              <p style={{ margin: '8px 0 0', fontSize: isMobile ? 13 : 14, color: 'var(--dgd-fg-2)', lineHeight: 1.6 }}>
                Tens{' '}
                <strong style={{ color: 'var(--dgd-fg-1)' }}>{fmtE(pipeSummary.liveTotal)} no pipeline</strong>
                {' '}({pipeSummary.liveOpsCount} OPs) e fechaste{' '}
                <strong style={{ color: 'var(--dgd-fg-1)' }}>{fmtE(pipeSummary.liveWon)}</strong>
                {pipeSummary.pctBP != null && (
                  <> (<strong style={{ color: pipeSummary.liveWon >= bpYTD ? 'var(--dgd-green-700,#15803d)' : 'var(--dgd-red-700,#b91c1c)' }}>{pipeSummary.pctBP}% do BP YTD</strong>)</>
                )}.
                {pipeSummary.bottleneck && (
                  <> Maior em aberto: <strong style={{ color: 'var(--dgd-fg-1)' }}>{pipeSummary.bottleneck.stage}</strong> — {fmtE(pipeSummary.bottleneck.value)} em {pipeSummary.bottleneck.count} OPs.</>
                )}
              </p>
            ) : (
              <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {[90, 72, 50].map(w => <div key={w} style={{ ...sk, height: 12, width: `${w}%` }} />)}
              </div>
            )}
          </div>

        </div>

        {/* ── BLOCO IA (v2 — KPIs + 3 blocos do Chairman) ─────── */}
        {(() => { const C = window.BriefingDigiAI; return C ? <C onNav={onNav} vendedorId={vendedorId} noCard /> : null; })()}

        {/* ── BOTÕES ──────────────────────────────────────────────────────── */}
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', paddingBottom: 4 }}>
          <button onClick={() => onNav?.('rpc')} className="dgd-btn dgd-btn-primary"
                  style={{ flex: isMobile ? 1 : 'none' }}>
            Ver RPC
          </button>
          <button onClick={() => onNav?.('oportunidades')} className="dgd-btn dgd-btn-dark"
                  style={{ flex: isMobile ? 1 : 'none' }}>
            Ver Pipeline
          </button>
        </div>

        {/* Pipeline & BP movidos para página Oportunidades */}

      </div>
    </div>
  );
};

window.ScreenComercialDailyBriefing = ScreenComercialDailyBriefing;
