// Bellia — Module Automatisation (variante A : grille uniforme de cartes d'agents)

const AGENTS = [
  { id: 'tva',  name: 'TVA',          icon: 'percent', desc: 'Collecte TVA mensuelle et prépare l\'écriture comptable',         freq: 'Mensuel · 1er du mois',  last: 'il y a 12 min', next: '1 juin 06:00',  status: 'actif',     actions: 12, cost: 1.80 },
  { id: 'compta', name: 'Comptabilité', icon: 'euro',    desc: 'Pré-saisit les écritures et synchronise avec le cabinet',         freq: 'Quotidien · 06:00',      last: 'ce matin',      next: 'demain 06:00',  status: 'actif',     actions: 18, cost: 2.40 },
  { id: 'emp',  name: 'Employés',     icon: 'users',   desc: 'Tient à jour les contrats, heures et absences de l\'équipe',       freq: 'Sur déclencheur',        last: 'hier',          next: 'auto',          status: 'actif',     actions: 6,  cost: 0.65 },
  { id: 'plan', name: 'Planning',     icon: 'cal',     desc: 'Génère le planning hebdo et alerte si trous de couverture',        freq: 'Hebdo · dim. 18:00',     last: 'dim. 18:00',    next: 'dim. 18:00',    status: 'actif',     actions: 4,  cost: 0.95 },
  { id: 'tdb',  name: 'Tableau de bord', icon: 'dashboard', desc: 'Met à jour les KPI et alertes du dashboard principal',       freq: 'Temps réel',             last: 'à l\'instant',  next: 'continu',       status: 'actif',     actions: 0,  cost: 0.10 },
  { id: 'rap',  name: 'Rapports',     icon: 'file',    desc: 'Génère et envoie le rapport hebdo aux destinataires',              freq: 'Hebdo · lun. 08:00',     last: 'lun. 08:00',    next: 'lun. 08:00',    status: 'actif',     actions: 1,  cost: 0.45 },
  { id: 'ana',  name: 'Analyse',      icon: 'chart',   desc: 'Détecte les dérives et propose des leviers d\'optimisation',       freq: 'Hebdo · ven. 09:00',     last: 'ven. 09:00',    next: 'ven. 09:00',    status: 'actif',     actions: 3,  cost: 0.80 },
  { id: 'use',  name: 'Utilisations', icon: 'activity', desc: 'Suit l\'usage de Bellia par votre équipe et coache les retards', freq: 'Quotidien · 22:00',      last: 'hier 22:00',    next: 'ce soir 22:00', status: 'actif',     actions: 2,  cost: 0.30 },
  { id: 'ven',  name: 'Ventes',       icon: 'bag',     desc: 'Consolide les ventes des caisses et détecte les anomalies',        freq: 'Toutes les 4 h',         last: 'il y a 2 h',    next: 'dans 2 h',      status: 'actif',     actions: 1,  cost: 0.55 },
  { id: 'dep',  name: 'Dépenses',     icon: 'receipt', desc: 'Traite les factures fournisseurs et les pré-impute',               freq: 'Sur réception',          last: 'il y a 5 h',    next: 'auto',          status: 'en cours',  actions: 4,  cost: 1.20 },
  { id: 'fou',  name: 'Fournisseurs', icon: 'truck',   desc: 'Compare prix d\'achat et alerte sur les hausses inhabituelles',    freq: 'Hebdo · mar. 10:00',     last: '—',             next: 'mar. 10:00',    status: 'inactif',   actions: 0,  cost: 0 },
  { id: 'pay',  name: 'Paiements',    icon: 'card',    desc: 'Programme les paiements fournisseurs selon les échéances',         freq: 'Quotidien · 11:00',      last: '—',             next: '—',             status: 'inactif',   actions: 0,  cost: 0 },
];

const STATUS_META = {
  actif:    { c: C.ok,   bg: C.okSft,   label: 'Actif' },
  'en cours': { c: C.warn, bg: C.warnSft, label: 'En cours' },
  inactif:  { c: C.mute, bg: C.cardSoft, label: 'Inactif' },
};

const AutomationScreen = ({ onNav }) => {
  const [open, setOpen] = React.useState(null);  // agent ID

  const active = AGENTS.filter(a => a.status === 'actif').length;
  const totalActions = AGENTS.reduce((a, b) => a + b.actions, 0);
  const totalCost = AGENTS.reduce((a, b) => a + b.cost, 0);

  return (
    <PageShell current="automation" onNav={onNav}>
      <Header
        title="Automatisation"
        subtitle="12 agents IA travaillent pour République — vous reprenez la main quand vous voulez"
        right={<>
          <Btn kind="ghost" onClick={() => onNav('chat')} icon={<Icon name="bot" size={14} color={C.ink2} />}>Parler à un agent</Btn>
          <Btn kind="primary" icon={<Icon name="plus" size={14} />}>Nouveau workflow</Btn>
        </>}
      />

      {/* ====== STATUS BANNER ====== */}
      <div style={{
        background: `linear-gradient(135deg, ${C.orangeWh} 0%, ${C.cardSoft} 100%)`,
        border: `1px solid ${C.line}`, borderRadius: 22, padding: 22, marginBottom: 20,
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr auto', gap: 24, alignItems: 'center',
      }}>
        <BannerStat label="Agents actifs" value={`${active} / 12`} icon="power" />
        <BannerStat label="Actions ce mois" value={num(47)} icon="activity" delta="+12" />
        <BannerStat label="Coût Claude" value={eur(totalCost, 2)} icon="sparkles" />
        <BannerStat label="Temps gagné" value="~14 h" icon="coffee" delta="ce mois" deltaPlain />
        <Btn kind="primaryDark" icon={<Icon name="play" size={13} />}>Lancer un test</Btn>
      </div>

      {/* ====== TOOLBAR ====== */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <div style={{ display: 'inline-flex', padding: 4, background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, gap: 2 }}>
          {[
            { id: 'all', l: 'Tous', n: 12 },
            { id: 'on',  l: 'Actifs', n: 9 },
            { id: 'busy',l: 'En cours', n: 1 },
            { id: 'off', l: 'Inactifs', n: 2 },
          ].map((f, i) => (
            <button key={f.id} style={{
              padding: '7px 14px', borderRadius: 999, background: i === 0 ? C.orange : 'transparent',
              color: i === 0 ? '#fff' : C.mute, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              fontSize: 11, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {f.l} <span style={{ fontSize: 10, opacity: 0.85 }}>{f.n}</span>
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: C.mute }}>Trier par</span>
          <button style={{
            padding: '7px 12px', background: C.card, border: `1px solid ${C.line}`, borderRadius: 999,
            cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: C.ink2,
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>Dernière exécution <Icon name="chevDown" size={12} color={C.mute} /></button>
        </div>
      </div>

      {/* ====== GRID ====== */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        {AGENTS.map(a => (
          <AgentCard key={a.id} agent={a} onOpen={() => setOpen(a.id)} />
        ))}
      </div>

      {/* ====== SIDE PANEL ====== */}
      {open && <AgentPanel agent={AGENTS.find(a => a.id === open)} onClose={() => setOpen(null)} />}
    </PageShell>
  );
};

const AgentCard = ({ agent, onOpen }) => {
  const s = STATUS_META[agent.status];
  const [on, setOn] = React.useState(agent.status !== 'inactif');
  return (
    <div onClick={onOpen} style={{
      background: C.card, border: `1px solid ${C.line}`, borderRadius: 20, padding: 18,
      display: 'flex', flexDirection: 'column', cursor: 'pointer',
      transition: 'transform .15s ease, box-shadow .15s ease, border-color .15s ease',
    }}
    onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 12px 28px -22px rgba(36,27,18,0.28)'; e.currentTarget.style.borderColor = C.orangeSft; }}
    onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = C.line; }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{
          width: 42, height: 42, borderRadius: 13,
          background: agent.status === 'inactif' ? C.cardSoft : C.orangeWh,
          color: agent.status === 'inactif' ? C.mute : C.orangeDp,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name={agent.icon} size={20} />
        </div>
        <Switch on={on} onChange={(v) => { setOn(v); }} stop />
      </div>

      <div style={{ marginTop: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: C.ink, letterSpacing: -0.2 }}>{agent.name}</div>
        <div style={{ fontSize: 11, color: C.mute, marginTop: 4, lineHeight: 1.45, minHeight: 32, textWrap: 'pretty' }}>{agent.desc}</div>
      </div>

      <div style={{ marginTop: 14, paddingTop: 12, borderTop: `1px dashed ${C.line}`, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <Row k="Fréquence" v={agent.freq} />
        <Row k="Dernière" v={agent.last} />
        <Row k="Prochaine" v={agent.next} accent={agent.status === 'actif'} />
      </div>

      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Pill kind={agent.status === 'actif' ? 'ok' : agent.status === 'en cours' ? 'warn' : 'neutral'} icon={
          <span style={{ width: 6, height: 6, borderRadius: 999, background: s.c, animation: agent.status === 'en cours' ? 'pulse 1.5s ease-in-out infinite' : 'none' }} />
        }>{s.label}</Pill>
        <button onClick={(e) => { e.stopPropagation(); onOpen(); }} style={{
          background: 'transparent', border: 'none', cursor: 'pointer', color: C.orangeDp,
          fontFamily: 'inherit', fontSize: 11, fontWeight: 600, padding: 0,
          display: 'inline-flex', alignItems: 'center', gap: 3,
        }}>Configurer <Icon name="arrowR" size={12} /></button>
      </div>
    </div>
  );
};

const Row = ({ k, v, accent }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, fontSize: 11 }}>
    <span style={{ color: C.mute }}>{k}</span>
    <span style={{ color: accent ? C.orangeDp : C.ink2, fontWeight: 600, fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{v}</span>
  </div>
);

const Switch = ({ on, onChange, stop }) => (
  <button onClick={(e) => { if (stop) e.stopPropagation(); onChange?.(!on); }} aria-checked={on} role="switch" style={{
    width: 36, height: 22, borderRadius: 999, background: on ? C.orange : C.cardSoft,
    border: `1px solid ${on ? C.orange : C.line}`, position: 'relative', cursor: 'pointer', padding: 0,
    transition: 'background .18s ease', flexShrink: 0,
  }}>
    <span style={{
      position: 'absolute', top: 2, left: on ? 16 : 2, width: 16, height: 16, borderRadius: 999, background: '#fff',
      transition: 'left .18s ease', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
    }} />
  </button>
);

const BannerStat = ({ label, value, icon, delta, deltaPlain }) => (
  <div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
      <div style={{ width: 26, height: 26, borderRadius: 8, background: C.card, color: C.orangeDp, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={14} />
      </div>
      <span style={{ fontSize: 10, color: C.orangeDp, fontWeight: 700, letterSpacing: 0.6 }}>{label.toUpperCase()}</span>
    </div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
      <div style={{ fontSize: 22, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>{value}</div>
      {delta && <span style={{ fontSize: 11, color: deltaPlain ? C.mute : C.ok, fontWeight: 600 }}>{delta}</span>}
    </div>
  </div>
);

// ====== SIDE PANEL ======
const AgentPanel = ({ agent, onClose }) => {
  const s = STATUS_META[agent.status];
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(36,27,18,0.18)', zIndex: 50, backdropFilter: 'blur(2px)' }} />
      <aside style={{
        position: 'fixed', top: 12, right: 12, bottom: 12, width: 520, background: C.card,
        borderRadius: 28, boxShadow: '0 30px 80px -30px rgba(36,27,18,0.4)', zIndex: 51,
        display: 'flex', flexDirection: 'column', overflow: 'hidden', fontFamily: 'Inter, sans-serif',
      }}>
        {/* header */}
        <div style={{ padding: '22px 26px', borderBottom: `1px solid ${C.line}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', gap: 14 }}>
              <div style={{ width: 50, height: 50, borderRadius: 14, background: C.orangeWh, color: C.orangeDp, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={agent.icon} size={24} />
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <h3 style={{ fontSize: 20, fontWeight: 700, color: C.ink, margin: 0, letterSpacing: -0.4 }}>Agent {agent.name}</h3>
                  <Pill kind={agent.status === 'actif' ? 'ok' : agent.status === 'en cours' ? 'warn' : 'neutral'} icon={<span style={{ width: 6, height: 6, borderRadius: 999, background: s.c }} />}>{s.label}</Pill>
                </div>
                <div style={{ fontSize: 12, color: C.mute, marginTop: 4 }}>{agent.freq}</div>
              </div>
            </div>
            <button onClick={onClose} aria-label="Fermer" style={{
              width: 36, height: 36, borderRadius: 999, background: C.cardSoft, border: 'none',
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: C.ink2,
            }}>
              <Icon name="x" size={16} />
            </button>
          </div>
          <p style={{ fontSize: 13, color: C.ink2, marginTop: 14, lineHeight: 1.55 }}>{agent.desc}.</p>
        </div>

        {/* body scroll */}
        <div style={{ flex: 1, overflow: 'auto', padding: 26 }}>
          {/* mini stats */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 22 }}>
            <MiniStat label="Actions ce mois" value={num(agent.actions)} />
            <MiniStat label="Coût Claude" value={eur(agent.cost, 2)} />
            <MiniStat label="Taux de succès" value={pct(99.2)} />
          </div>

          {/* params */}
          <SectionTitle>Paramètres</SectionTitle>
          <div style={{ background: C.cardWash, borderRadius: 16, padding: 16, display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 22 }}>
            <Param label="Fréquence d'exécution" value={agent.freq} />
            <Param label="Seuil d'alerte (food cost)" value="28 %" />
            <Param label="Destinataires" value="yannis@cantine-corner.fr, +1" />
            <Param label="Validation requise" value="Au-dessus de 500 €" />
          </div>

          {/* history */}
          <SectionTitle right={<button style={{ background: 'transparent', border: 'none', color: C.orangeDp, fontWeight: 600, fontSize: 11, cursor: 'pointer', fontFamily: 'inherit' }}>Tout voir</button>}>Historique des 10 dernières actions</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { ok: true,  t: `Export ${agent.name} — avril 2026`, when: 'il y a 12 min', cost: '0,15 €', n: '1 fichier' },
              { ok: true,  t: `Synthèse hebdomadaire`,             when: 'hier 18:30',    cost: '0,18 €', n: '2 destinataires' },
              { ok: true,  t: `Contrôle de cohérence`,             when: 'hier 06:00',    cost: '0,08 €', n: '0 anomalie' },
              { ok: false, t: `Tentative — facture #4218 illisible`, when: 'il y a 2 j',  cost: '0,05 €', n: 'à corriger' },
              { ok: true,  t: `Mise à jour des seuils`,            when: 'il y a 3 j',    cost: '0,02 €', n: '—' },
              { ok: true,  t: `Sauvegarde mensuelle`,              when: 'il y a 5 j',    cost: '0,11 €', n: '14 Mo' },
            ].map((h, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 14px', borderRadius: 14, background: C.card, border: `1px solid ${C.lineSoft}` }}>
                <div style={{ width: 24, height: 24, borderRadius: 999, background: h.ok ? C.okSft : C.warnSft, color: h.ok ? C.ok : C.warn, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name={h.ok ? 'check' : 'alertC'} size={12} stroke={2.5} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: C.ink, fontWeight: 600 }}>{h.t}</div>
                  <div style={{ fontSize: 10, color: C.mute, marginTop: 3 }}>{h.when} · {h.cost} · {h.n}</div>
                </div>
                <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: C.mute, display: 'flex', padding: 4 }}>
                  <Icon name="arrowUp" size={12} />
                </button>
              </div>
            ))}
          </div>

          {/* cost history */}
          <SectionTitle style={{ marginTop: 24 }}>Coût mensuel</SectionTitle>
          <div style={{ background: C.cardWash, borderRadius: 16, padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 22, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums' }}>{eur(agent.cost, 2)}</div>
                <div style={{ fontSize: 11, color: C.mute, marginTop: 2 }}>Mai 2026 · stable vs avril</div>
              </div>
              <Pill kind="ok">−6 % vs mars</Pill>
            </div>
            <div style={{ marginTop: 12, display: 'flex', alignItems: 'flex-end', gap: 6, height: 50 }}>
              {[0.4, 0.6, 0.7, 0.5, 0.8, 0.9].map((h, i) => (
                <div key={i} style={{ flex: 1, height: `${h * 100}%`, background: i === 5 ? C.orange : C.orangeSft, borderRadius: 4 }} />
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
              {['déc', 'jan', 'fév', 'mar', 'avr', 'mai'].map(m => (
                <span key={m} style={{ fontSize: 9, color: C.mute, flex: 1, textAlign: 'center' }}>{m}</span>
              ))}
            </div>
          </div>
        </div>

        {/* footer actions */}
        <div style={{ padding: 20, borderTop: `1px solid ${C.line}`, display: 'flex', gap: 10, background: C.cardWash }}>
          <Btn kind="ghost" icon={<Icon name="play" size={13} color={C.ink2} />}>Lancer maintenant</Btn>
          <Btn kind="primary" full icon={<Icon name="settings" size={13} />}>Configurer l'agent</Btn>
        </div>
      </aside>
    </>
  );
};

const SectionTitle = ({ children, right, style }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, ...style }}>
    <h4 style={{ fontSize: 11, fontWeight: 700, color: C.mute, margin: 0, letterSpacing: 0.7, textTransform: 'uppercase' }}>{children}</h4>
    {right}
  </div>
);

const MiniStat = ({ label, value }) => (
  <div style={{ background: C.cardWash, borderRadius: 14, padding: 12 }}>
    <div style={{ fontSize: 10, color: C.mute, fontWeight: 600, letterSpacing: 0.4 }}>{label.toUpperCase()}</div>
    <div style={{ fontSize: 16, fontWeight: 700, color: C.ink, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
  </div>
);

const Param = ({ label, value }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
    <span style={{ fontSize: 12, color: C.mute }}>{label}</span>
    <span style={{ fontSize: 12, color: C.ink, fontWeight: 600 }}>{value}</span>
  </div>
);

window.AutomationScreen = AutomationScreen;
