// Bellia — Écran de conversation avec un agent IA

const AGENT_LIST = [
  { id: 'ana', name: 'Analyse',     icon: 'chart',    desc: 'Détecte les dérives & propose des leviers', online: true },
  { id: 'dep', name: 'Dépenses',    icon: 'receipt',  desc: 'Traite les factures fournisseurs', online: true, badge: 4 },
  { id: 'plan',name: 'Planning',    icon: 'cal',      desc: 'Génère et alerte sur le planning', online: true },
  { id: 'tva', name: 'TVA',         icon: 'percent',  desc: 'Collecte TVA et pré-comptable', online: true },
  { id: 'ven', name: 'Ventes',      icon: 'bag',      desc: 'Consolide les ventes des caisses', online: true },
  { id: 'fou', name: 'Fournisseurs',icon: 'truck',    desc: 'Compare prix et alerte hausses', online: false },
];

const CONVERSATIONS = {
  ana: [
    { role: 'agent', t: 'agent', text: 'Bonjour Yannis. J\'ai terminé l\'analyse de la semaine du 4 au 10 mai. Voici les 3 points qui méritent ton attention.', time: '14:32' },
    { role: 'agent', t: 'cards', cards: [
      { kind: 'warn',  title: 'Food cost en dérive', value: '32,0 %', delta: '+4,0 pts vs cible', detail: 'Boucherie : +18 % vs avril. Boulangerie : stable. Primeurs : +6 %.' },
      { kind: 'accent', title: 'Panier moyen midi en hausse', value: '28,50 €', delta: '+1,80 € vs avril', detail: 'Effet menu « formule printemps ». Bonne dynamique sur les desserts.' },
      { kind: 'warn',  title: 'Productivité salle samedi soir', value: '–11 %', delta: 'vs samedis d\'avril', detail: 'Plus de couverts mais service plus lent. À investiguer.' },
    ] },
    { role: 'agent', t: 'agent', text: 'Veux-tu que je creuse l\'écart de food cost sur la boucherie ?', time: '14:32', suggestions: ['Oui, montre-moi l\'écart par fournisseur', 'Compare avec mai 2025', 'Propose un plan d\'action'] },
    { role: 'user', t: 'user', text: 'Oui, montre-moi l\'écart par fournisseur boucherie', time: '14:34' },
    { role: 'agent', t: 'agent', text: 'Voici la comparaison avril / mai sur les 3 fournisseurs de boucherie. Metro Cash & Carry a augmenté ses prix sur l\'entrecôte (+22 %) et la côte de bœuf (+18 %).', time: '14:34' },
    { role: 'agent', t: 'chart' },
    { role: 'agent', t: 'agent', text: 'Trois pistes concrètes :', time: '14:35', list: [
      'Demander un devis comparatif à Boucherie Hugo (notre fournisseur secondaire) — économie estimée 280 €/mois',
      'Réduire la grammage entrecôte de 220g à 200g — gain 6 % marge sans impact perçu',
      'Remplacer la côte de bœuf par une bavette d\'aloyau sur le menu chasse — marge × 1,4',
    ], suggestions: ['Lance la demande de devis', 'Prépare un mémo pour la cuisine', 'Programme un suivi hebdomadaire'] },
  ],
  dep: [
    { role: 'agent', t: 'agent', text: 'Bonjour. 4 factures sont en attente de ta validation pour un total de 2 967,50 €. Je les ai toutes pré-imputées.', time: '09:12' },
  ],
};

const ChatAgentScreen = ({ onNav }) => {
  const [active, setActive] = React.useState('ana');
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  const agent = AGENT_LIST.find(a => a.id === active);
  const messages = CONVERSATIONS[active] || [
    { role: 'agent', t: 'agent', text: `Bonjour ! Je suis l'agent ${agent.name}. Que veux-tu savoir ?`, time: '14:00' }
  ];

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [active]);

  return (
    <PageShell current="automation" onNav={onNav}>
      <Header
        title="Conversation"
        subtitle="Pose une question à un agent IA — il a accès à toutes les données de République"
        right={<>
          <Btn kind="ghost" icon={<Icon name="refresh" size={14} color={C.ink2} />}>Nouvelle conversation</Btn>
          <Btn kind="ghost" onClick={() => onNav('automation')} icon={<Icon name="settings" size={14} color={C.ink2} />}>Tous les agents</Btn>
        </>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 16, height: 'calc(100vh - 180px)', minHeight: 600 }}>
        {/* ===== Agent list ===== */}
        <div style={{ background: C.cardWash, border: `1px solid ${C.line}`, borderRadius: 22, padding: 14, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '4px 10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: C.mute, letterSpacing: 0.7, textTransform: 'uppercase' }}>Agents</span>
            <span style={{ fontSize: 11, color: C.mute }}>{AGENT_LIST.filter(a => a.online).length} en ligne</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, overflow: 'auto' }}>
            {AGENT_LIST.map(a => {
              const sel = a.id === active;
              return (
                <button key={a.id} onClick={() => setActive(a.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: 12, borderRadius: 14,
                  background: sel ? C.card : 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                  textAlign: 'left', boxShadow: sel ? '0 6px 14px -10px rgba(36,27,18,0.25)' : 'none',
                  transition: 'background .12s ease',
                }}
                onMouseEnter={e => !sel && (e.currentTarget.style.background = C.card)}
                onMouseLeave={e => !sel && (e.currentTarget.style.background = 'transparent')}
                >
                  <div style={{ position: 'relative' }}>
                    <div style={{
                      width: 38, height: 38, borderRadius: 12,
                      background: sel ? C.orange : C.orangeWh, color: sel ? '#fff' : C.orangeDp,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <Icon name={a.icon} size={18} />
                    </div>
                    {a.online && <span style={{ position: 'absolute', bottom: -1, right: -1, width: 10, height: 10, borderRadius: 999, background: C.ok, border: `2px solid ${sel ? C.card : C.cardWash}` }} />}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: C.ink, letterSpacing: -0.1, display: 'flex', alignItems: 'center', gap: 6 }}>
                      Agent {a.name}
                      {a.badge && <span style={{ fontSize: 9, padding: '2px 6px', borderRadius: 999, background: C.orange, color: '#fff', fontWeight: 700 }}>{a.badge}</span>}
                    </div>
                    <div style={{ fontSize: 10, color: C.mute, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.desc}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* ===== Chat area ===== */}
        <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 22, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {/* Chat header */}
          <div style={{ padding: '14px 22px', borderBottom: `1px solid ${C.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ position: 'relative' }}>
                <div style={{ width: 40, height: 40, borderRadius: 13, background: C.orangeWh, color: C.orangeDp, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={agent.icon} size={20} />
                </div>
                <span style={{ position: 'absolute', bottom: -1, right: -1, width: 11, height: 11, borderRadius: 999, background: C.ok, border: `2px solid ${C.card}` }} />
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, color: C.ink, letterSpacing: -0.2 }}>Agent {agent.name}</div>
                <div style={{ fontSize: 11, color: C.mute, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 5, height: 5, borderRadius: 999, background: C.ok }} />
                  En ligne · accède aux données de République
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <Pill kind="accent" icon={<Icon name="sparkles" size={10} />}>Claude Sonnet</Pill>
              <button style={iconBtnStyle} aria-label="Plus">
                <Icon name="more" size={16} color={C.ink2} />
              </button>
            </div>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '24px 28px', background: C.cardWash }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
              <span style={{ fontSize: 10, color: C.mute, padding: '4px 10px', background: C.card, borderRadius: 999, border: `1px solid ${C.line}`, fontWeight: 600 }}>Aujourd'hui · lun. 11 mai 2026</span>
            </div>

            {messages.map((m, i) => (
              <Message key={i} m={m} agent={agent} />
            ))}

            {/* typing */}
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end' }}>
              <div style={{ width: 32, height: 32, borderRadius: 11, background: C.orangeWh, color: C.orangeDp, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={agent.icon} size={15} />
              </div>
              <div style={{ padding: '12px 16px', background: C.card, border: `1px solid ${C.line}`, borderRadius: '4px 18px 18px 18px', display: 'inline-flex', gap: 4 }}>
                <Dot delay={0} /><Dot delay={0.2} /><Dot delay={0.4} />
              </div>
            </div>
          </div>

          {/* Input */}
          <div style={{ padding: 18, borderTop: `1px solid ${C.line}`, background: C.card }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
              {['Résume la semaine', 'Compare avec mai 2025', 'Plan d\'action food cost', 'Top 5 produits'].map(s => (
                <button key={s} onClick={() => setInput(s)} style={{
                  padding: '6px 12px', background: C.cardWash, border: `1px solid ${C.line}`, borderRadius: 999,
                  cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: C.ink2,
                }}>{s}</button>
              ))}
            </div>
            <div style={{
              display: 'flex', alignItems: 'flex-end', gap: 10, padding: 8, paddingLeft: 16,
              background: C.cardWash, border: `1px solid ${C.line}`, borderRadius: 18,
            }}>
              <textarea
                value={input}
                onChange={e => setInput(e.target.value)}
                placeholder={`Pose une question à l'agent ${agent.name}…`}
                rows={1}
                style={{
                  flex: 1, border: 'none', outline: 'none', background: 'transparent', resize: 'none',
                  fontFamily: 'inherit', fontSize: 13, color: C.ink, padding: '8px 0', maxHeight: 120,
                }}
              />
              <button aria-label="Joindre un fichier" style={iconBtnSoftStyle}>
                <Icon name="file" size={15} color={C.mute} />
              </button>
              <Btn kind="primary" size="sm" icon={<Icon name="arrowR" size={13} />}>Envoyer</Btn>
            </div>
            <div style={{ fontSize: 10, color: C.mute, marginTop: 8, display: 'flex', justifyContent: 'space-between' }}>
              <span>Coût estimé de cette conversation : 0,08 €</span>
              <span>↵ envoyer · ⇧↵ saut de ligne</span>
            </div>
          </div>
        </div>
      </div>
    </PageShell>
  );
};

const iconBtnStyle = {
  width: 36, height: 36, borderRadius: 999, background: C.cardSoft, border: 'none',
  display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
};
const iconBtnSoftStyle = {
  width: 34, height: 34, borderRadius: 999, background: 'transparent', border: 'none',
  display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
};

const Dot = ({ delay }) => (
  <span style={{
    width: 7, height: 7, borderRadius: 999, background: C.mute2,
    animation: `pulse 1.2s ease-in-out ${delay}s infinite`,
  }} />
);

const Message = ({ m, agent }) => {
  if (m.role === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 18 }}>
        <div style={{ maxWidth: '70%' }}>
          <div style={{ padding: '12px 16px', background: C.orange, color: '#fff', borderRadius: '18px 18px 4px 18px', fontSize: 13, lineHeight: 1.55 }}>
            {m.text}
          </div>
          <div style={{ fontSize: 10, color: C.mute, marginTop: 4, textAlign: 'right' }}>{m.time}</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', gap: 12, marginBottom: 18, alignItems: 'flex-start' }}>
      <div style={{ width: 32, height: 32, borderRadius: 11, background: C.orangeWh, color: C.orangeDp, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 2 }}>
        <Icon name={agent.icon} size={15} />
      </div>
      <div style={{ flex: 1, minWidth: 0, maxWidth: '85%' }}>
        {m.text && (
          <div style={{ padding: '12px 16px', background: C.card, border: `1px solid ${C.line}`, borderRadius: '4px 18px 18px 18px', fontSize: 13, lineHeight: 1.6, color: C.ink }}>
            {m.text}
            {m.list && (
              <ol style={{ margin: '10px 0 0 0', paddingLeft: 18, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {m.list.map((l, i) => <li key={i} style={{ color: C.ink2 }}>{l}</li>)}
              </ol>
            )}
          </div>
        )}

        {m.t === 'cards' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
            {m.cards.map((c, i) => <InsightCard key={i} c={c} />)}
          </div>
        )}

        {m.t === 'chart' && (
          <div style={{ marginTop: 8, padding: 16, background: C.card, border: `1px solid ${C.line}`, borderRadius: 18 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
              <div>
                <div style={{ fontSize: 12, color: C.mute, fontWeight: 600 }}>BOUCHERIE — ÉCART AVRIL / MAI</div>
                <div style={{ fontSize: 18, fontWeight: 700, color: C.ink, marginTop: 2, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>+218 € · +18 %</div>
              </div>
              <Pill kind="err">Dérive</Pill>
            </div>
            <FournisseurBars />
            <button style={{ marginTop: 12, fontSize: 11, color: C.orangeDp, fontWeight: 600, background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              Voir le détail <Icon name="arrowR" size={11} />
            </button>
          </div>
        )}

        {m.suggestions && (
          <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
            {m.suggestions.map((s, i) => (
              <button key={i} style={{
                padding: '7px 12px', background: C.card, border: `1px solid ${C.orangeSft}`, borderRadius: 999,
                cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: C.orangeDp,
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}><Icon name="sparkles" size={10} /> {s}</button>
            ))}
          </div>
        )}

        {m.time && <div style={{ fontSize: 10, color: C.mute, marginTop: 6 }}>{m.time}</div>}
      </div>
    </div>
  );
};

const InsightCard = ({ c }) => {
  const map = {
    warn:   { bar: C.warn,    bg: C.warnSft,   pill: 'warn' },
    accent: { bar: C.orange,  bg: C.orangeWh,  pill: 'accent' },
    ok:     { bar: C.ok,      bg: C.okSft,     pill: 'ok' },
  };
  const m = map[c.kind];
  return (
    <div style={{
      display: 'flex', gap: 14, padding: 14, background: C.card, border: `1px solid ${C.line}`, borderRadius: 16,
      borderLeft: `4px solid ${m.bar}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: C.ink, letterSpacing: -0.1 }}>{c.title}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
          <span style={{ fontSize: 20, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>{c.value}</span>
          <span style={{ fontSize: 11, color: m.bar, fontWeight: 600 }}>{c.delta}</span>
        </div>
        <div style={{ fontSize: 11, color: C.mute, marginTop: 4, lineHeight: 1.5 }}>{c.detail}</div>
      </div>
    </div>
  );
};

const FournisseurBars = () => {
  const data = [
    { name: 'Metro Cash & Carry', avr: 880, mai: 1078, c: C.err },
    { name: 'Boucherie Hugo',     avr: 410, mai: 422,  c: C.ok  },
    { name: 'Sysco',              avr: 295, mai: 303,  c: C.ok  },
  ];
  const max = Math.max(...data.flatMap(d => [d.avr, d.mai]));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {data.map(d => (
        <div key={d.name}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
            <span style={{ color: C.ink, fontWeight: 600 }}>{d.name}</span>
            <span style={{ color: C.mute, fontVariantNumeric: 'tabular-nums' }}>{eur(d.avr)} → <strong style={{ color: d.c }}>{eur(d.mai)}</strong></span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ height: 6, background: C.cardSoft, borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: `${(d.avr / max) * 100}%`, height: '100%', background: C.mute2, borderRadius: 999 }} />
            </div>
            <div style={{ height: 6, background: C.cardSoft, borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: `${(d.mai / max) * 100}%`, height: '100%', background: d.c, borderRadius: 999 }} />
            </div>
          </div>
        </div>
      ))}
      <div style={{ display: 'flex', gap: 14, marginTop: 4, fontSize: 10, color: C.mute }}>
        <span><span style={{ display: 'inline-block', width: 8, height: 8, background: C.mute2, borderRadius: 2, marginRight: 4 }} />Avril</span>
        <span><span style={{ display: 'inline-block', width: 8, height: 8, background: C.err, borderRadius: 2, marginRight: 4 }} />Mai</span>
      </div>
    </div>
  );
};

window.ChatAgentScreen = ChatAgentScreen;
