// InstantDevis — Dashboard (écran principal)
// KPIs : CA Encaissé, En attente, Retard + bouton Instant Note central
// Abonné à AF_STORE → mise à jour en temps réel sans rechargement

function AfDashboard({ t, currency, userName, onNewNote, setView, onOpenSettings, networkOnline = true }) {
  const { TrendingUp, AlertTriangle, Clock, HardHat, ChevronRight, Settings } = lucide;

  const [allQuotes, setAllQuotes] = React.useState(() => AF_STORE.getAll());
  const [cloudMsg, setCloudMsg] = React.useState(() => (AF_STORE.getLastFirestoreError && AF_STORE.getLastFirestoreError()) || '');

  React.useEffect(() => {
    const tick = () => {
      if (AF_STORE.getLastFirestoreError) {
        setCloudMsg(AF_STORE.getLastFirestoreError() || '');
      }
    };
    const unsub = AF_STORE.subscribe(() => {
      setAllQuotes(AF_STORE.getAll());
      tick();
    });
    const unsubFirestore = AF_STORE.initFirestoreSync();
    const t0 = setTimeout(tick, 900);
    return () => {
      clearTimeout(t0);
      unsub();
      if (unsubFirestore) unsubFirestore();
    };
  }, []);
  const stats = AF_STORE.computeStats(allQuotes);
  const pct = stats.monthTarget > 0
    ? Math.round((stats.monthRevenue / stats.monthTarget) * 100)
    : 0;

  // Tri par date décroissante — nouveaux devis utilisateur toujours en tête
  const recent = allQuotes
    .slice()
    .sort((a, b) => {
      // Les devis créés aujourd'hui (source: voice) remontent en premier
      const aIsNew = a.source === 'voice' ? 1 : 0;
      const bIsNew = b.source === 'voice' ? 1 : 0;
      if (aIsNew !== bIsNew) return bIsNew - aIsNew;
      return new Date(b.createdAt) - new Date(a.createdAt);
    })
    .slice(0, 4);

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      overflowY: 'auto', background: t.bg,
    }}>
      {/* Header */}
      <div style={{
        padding: '16px 20px 12px',
        background: t.primary,
        color: '#fff',
        position: 'relative',
        overflow: 'hidden',
      }}>
        {/* Hazard stripe décorative */}
        <div style={{
          position: 'absolute', top: 0, right: 0, width: 60, height: '100%',
          backgroundImage: 'repeating-linear-gradient(-45deg, rgba(255,107,0,0.3) 0, rgba(255,107,0,0.3) 4px, transparent 4px, transparent 12px)',
          pointerEvents: 'none',
        }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, opacity: 0.7, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 2 }}>
              Bonjour,
            </div>
            <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: -0.4 }}>
              {userName} <HardHat size={18} style={{ marginLeft: 4, verticalAlign: 'middle' }} />
            </div>
          </div>
          <button
            onClick={onOpenSettings}
            style={{
              width: 40, height: 40, borderRadius: 8,
              background: 'rgba(255,255,255,0.15)',
              border: '1px solid rgba(255,255,255,0.2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
          >
            <Settings size={18} color="#fff" />
          </button>
        </div>

        {/* Barre de progression objectif mensuel */}
        <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
            <span style={{ fontSize: 11, fontWeight: 600, opacity: 0.8 }}>Objectif du mois</span>
            <span style={{ fontSize: 11, fontWeight: 800, color: t.safety }}>{pct}%</span>
          </div>
          <div style={{
            height: 6, borderRadius: 3,
            background: 'rgba(255,255,255,0.2)',
            overflow: 'hidden',
          }}>
            <div style={{
              height: '100%', borderRadius: 3,
              width: `${Math.min(pct, 100)}%`,
              background: t.safety,
              transition: 'width 0.6s cubic-bezier(0.2,0.8,0.2,1)',
            }} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
            <span className="af-mono" style={{ fontSize: 12, fontWeight: 700, color: t.safety }}>
              {stats.monthRevenue.toLocaleString('fr-FR')} €
            </span>
            <span className="af-mono" style={{ fontSize: 11, opacity: 0.6 }}>
              / {stats.monthTarget.toLocaleString('fr-FR')} €
            </span>
          </div>
        </div>
      </div>

      {!networkOnline && (
        <div style={{
          margin: '0 16px 0',
          padding: '10px 12px',
          borderRadius: 10,
          background: 'rgba(11, 61, 92, 0.1)',
          border: '1px solid rgba(11, 61, 92, 0.25)',
          fontSize: 12,
          fontWeight: 600,
          color: t.text,
          lineHeight: 1.45,
        }}>
          Réseau indisponible (navigateur) : création et consultation des devis, génération PDF, signature et catalogue (hors import XLSX non mis en cache) restent possibles en local. Synchronisation Firestore, envoi e-mail (Worker) et transcription Worker : au retour de la connexion.
        </div>
      )}

      {cloudMsg && (
        <div style={{
          margin: '0 16px 0',
          padding: '10px 12px',
          borderRadius: 10,
          background: 'rgba(234, 179, 8, 0.12)',
          border: '1px solid rgba(180, 83, 9, 0.35)',
          fontSize: 12,
          fontWeight: 600,
          color: '#92400E',
          lineHeight: 1.45,
        }}>
          {cloudMsg}
        </div>
      )}

      {/* KPI Cards */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        gap: 10, padding: '14px 16px 0',
      }}>
        {/* CA Encaissé */}
        <div style={{
          background: t.bgElevated, borderRadius: 10,
          border: `1px solid ${t.border}`,
          padding: '14px 14px',
          boxShadow: t.shadowSm,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: 'rgba(15,118,110,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <TrendingUp size={15} color="#0F766E" />
            </div>
            <span style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Encaissé
            </span>
          </div>
          <div className="af-mono" style={{ fontSize: 22, fontWeight: 800, color: '#0F766E', letterSpacing: -0.5 }}>
            {stats.monthRevenue.toLocaleString('fr-FR')}€
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, marginTop: 3 }}>ce mois-ci</div>
        </div>

        {/* En attente */}
        <div style={{
          background: t.bgElevated, borderRadius: 10,
          border: `1px solid ${t.border}`,
          padding: '14px 14px',
          boxShadow: t.shadowSm,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: 'rgba(59,130,246,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Clock size={15} color="#3B82F6" />
            </div>
            <span style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              En attente
            </span>
          </div>
          <div className="af-mono" style={{ fontSize: 22, fontWeight: 800, color: '#3B82F6', letterSpacing: -0.5 }}>
            {stats.pendingAmount.toLocaleString('fr-FR')}€
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, marginTop: 3 }}>devis envoyés</div>
        </div>

        {/* En retard */}
        <div style={{
          background: t.bgElevated, borderRadius: 10,
          border: `1px solid rgba(255,107,0,0.3)`,
          padding: '14px 14px',
          boxShadow: t.shadowSm,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: 'rgba(255,107,0,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <AlertTriangle size={15} color={t.safety} style={{ animation: 'af-pulse 1.5s infinite' }} />
            </div>
            <span style={{ fontSize: 10, fontWeight: 700, color: t.safety, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              En retard
            </span>
          </div>
          <div className="af-mono" style={{ fontSize: 22, fontWeight: 800, color: t.safety, letterSpacing: -0.5 }}>
            {stats.overdueAmount.toLocaleString('fr-FR')}€
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, marginTop: 3 }}>
            {stats.overdueCount} devis · relance urgente
          </div>
        </div>

        {/* Devis signés */}
        <div style={{
          background: t.bgElevated, borderRadius: 10,
          border: `1px solid ${t.border}`,
          padding: '14px 14px',
          boxShadow: t.shadowSm,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: `rgba(11,61,92,0.1)`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <lucide.CheckCircle2 size={15} color={t.primary} />
            </div>
            <span style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Signés le mois
            </span>
          </div>
          <div className="af-mono" style={{ fontSize: 22, fontWeight: 800, color: t.primary, letterSpacing: -0.5 }}>
            {stats.signedThisMonth}
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, marginTop: 3 }}>Date sign. ou créa. · {stats.notesThisWeek} notes/sem</div>
        </div>
      </div>

      {/* ⚡ Bouton Instant Note — CTA principal */}
      <div style={{ padding: '18px 16px 0' }}>
        <button
          id="btn-instant-note"
          onClick={onNewNote}
          style={{
            width: '100%', height: 72, borderRadius: 14,
            background: `linear-gradient(135deg, ${t.safety} 0%, #ff8c00 100%)`,
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
            boxShadow: `0 8px 24px rgba(255,107,0,0.45), 0 2px 6px rgba(0,0,0,0.15)`,
            transition: 'transform 0.1s, box-shadow 0.1s',
            position: 'relative', overflow: 'hidden',
          }}
          onMouseDown={e => { e.currentTarget.style.transform = 'scale(0.97)'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(255,107,0,0.4)'; }}
          onMouseUp={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(255,107,0,0.45)'; }}
          onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(255,107,0,0.45)'; }}
        >
          {/* Texture hazard subtile */}
          <div style={{
            position: 'absolute', inset: 0, opacity: 0.08,
            backgroundImage: 'repeating-linear-gradient(-45deg, #fff 0, #fff 2px, transparent 2px, transparent 10px)',
            pointerEvents: 'none',
          }} />
          <lucide.Mic size={28} color="#0D1520" strokeWidth={2.5} />
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: '#0D1520', letterSpacing: -0.3 }}>
              ⚡ Instant Note
            </div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'rgba(13,21,32,0.7)', marginTop: 1 }}>
              Dicter un nouveau devis vocal
            </div>
          </div>
        </button>
      </div>

      {/* Devis récents */}
      <div style={{ padding: '16px 16px 24px' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10,
        }}>
          <span style={{ fontSize: 13, fontWeight: 800, color: t.text, letterSpacing: -0.2 }}>
            Devis récents
          </span>
          <button
            onClick={() => setView('notes')}
            style={{
              fontSize: 11, fontWeight: 700, color: t.primary,
              display: 'flex', alignItems: 'center', gap: 2,
            }}
          >
            Tous les devis <ChevronRight size={14} />
          </button>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {recent.length === 0 && (
            <div style={{
              background: t.bgElevated,
              borderRadius: 10,
              border: `1px dashed ${t.border}`,
              padding: '22px 16px',
              textAlign: 'center',
            }}>
              <div style={{ fontSize: 14, fontWeight: 800, color: t.text, marginBottom: 6 }}>
                Aucun devis pour le moment
              </div>
              <div style={{ fontSize: 12, color: t.textMuted, marginBottom: 14, lineHeight: 1.45 }}>
                Créez votre premier devis à la voix avec Instant Note.
              </div>
              <button
                type="button"
                onClick={onNewNote}
                style={{
                  padding: '12px 18px',
                  borderRadius: 10,
                  background: `linear-gradient(135deg, ${t.safety} 0%, #ff8c00 100%)`,
                  border: 'none',
                  fontSize: 13,
                  fontWeight: 800,
                  color: '#0D1520',
                  cursor: 'pointer',
                  boxShadow: `0 4px 14px rgba(255,107,0,0.35)`,
                }}
              >
                Créer un devis avec Instant Note
              </button>
            </div>
          )}
          {recent.map((q, idx) => {
            const trade = AF_TRADE_META[q.trade] || AF_TRADE_META.multi;
            const o = (typeof AF_DEVIS !== 'undefined' && AF_DEVIS.documentOutput) ? AF_DEVIS.documentOutput(q) : null;
            const ttcR = o ? o.totalTTC : (q.totalTTC != null ? q.totalTTC : q.amount);
            const _dashAcomptePct = typeof AF_PROFILE_STORE !== 'undefined' ? (AF_PROFILE_STORE.get().acomptePercent ?? 30) : 30;
            const acR = o ? o.acompte : (q.acompte != null ? q.acompte : Math.round((Number(ttcR) || 0) * (_dashAcomptePct / 100) * 100) / 100);
            const deposit = Math.round(acR);
            const isNew = q.source === 'voice';
            return (
              <div
                key={q.id}
                onClick={() => setView('detail', q.id)}
                className={isNew ? 'af-slide-up' : ''}
                style={{
                  background: t.bgElevated, borderRadius: 10,
                  border: isNew
                    ? `1.5px solid rgba(16,185,129,0.7)`
                    : `1px solid ${t.border}`,
                  padding: '12px 14px',
                  boxShadow: isNew
                    ? `0 0 0 3px rgba(16,185,129,0.12), ${t.shadowSm}`
                    : t.shadowSm,
                  cursor: 'pointer',
                  display: 'flex', flexDirection: 'column', gap: 6,
                  transition: 'transform 0.1s',
                }}
                onMouseDown={e => e.currentTarget.style.transform = 'scale(0.99)'}
                onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
                onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
              >
                {/* Badge "Nouveau" pour les devis créés via dictée */}
                {isNew && (
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 5,
                    marginBottom: 2,
                  }}>
                    <lucide.CloudUpload size={11} color="#10B981" />
                    <span style={{ fontSize: 10, fontWeight: 800, color: '#10B981', letterSpacing: 0.3 }}>
                      NOUVEAU · Sauvegardé
                    </span>
                  </div>
                )}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 13, fontWeight: 700, color: t.text,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>
                      {q.title}
                    </div>
                    <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>
                      {q.clientName} · <span style={{ color: trade.color }}>{trade.label}</span>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: 10 }}>
                    <div className="af-mono" style={{ fontSize: 15, fontWeight: 800, color: t.text }}>
                      {(o ? o.totalTTC : (q.totalTTC != null ? q.totalTTC : q.amount) || 0).toLocaleString('fr-FR')} €
                    </div>
                    <div style={{ fontSize: 10, color: t.safety, marginTop: 1, fontWeight: 700 }}>
                      Acompte: {deposit.toLocaleString('fr-FR')} €
                    </div>
                  </div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <AfBadge status={q.status || 'brouillon'} t={t} />
                  <span className="af-mono" style={{ fontSize: 10, color: t.textDim }}>
                    {q.id}
                  </span>
                </div>
                {(() => {
                  const p = (typeof AF_STORE !== 'undefined' && AF_STORE.localSyncPresentation)
                    ? AF_STORE.localSyncPresentation(q) : null;
                  if (!p) return null;
                  const c = p.state === 'error' ? t.safety : p.state === 'local_only' ? t.textMuted : p.state === 'synced' ? '#10B981' : t.primary;
                  return (
                    <div style={{ fontSize: 9, fontWeight: 700, color: c, lineHeight: 1.35 }}>
                      {p.title}
                      {p.detail && p.state === 'error' ? ' — ' + String(p.detail).slice(0, 80) : ''}
                    </div>
                  );
                })()}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AfDashboard });
