// DemoChat.jsx — auto-looping demo: assistente IA (ConstructHub).
// O utilizador pergunta pelas faturas em atraso; o assistente responde com
// dados reais e oferece uma ação — enviar lembretes — que o cursor executa.

(function () {
  const STR = {
    pt: {
      windowTitle: 'Assistente ConstructHub',
      badgeLocal: 'Privado por padrão',
      question: 'Que faturas estão em atraso?',
      answerPre: 'Tem ',
      answerStrong: '2 faturas em atraso',
      answerMid: ', num total de ',
      answerPost: ':',
      btnRemind: 'Enviar lembretes',
      btnBilling: 'Ver faturação',
      remindedOk: 'Lembretes enviados aos 2 clientes',
      placeholder: 'Pergunte ao assistente…',
      toast: '2 lembretes enviados por email',
      invoices: [
        { num: 'FT 2026/0061', client: 'Construções Santa Cruz', value: '€ 4.980,00', days: '12 dias' },
        { num: 'FT 2026/0044', client: 'Obras do Mar', value: '€ 2.450,00', days: '5 dias' },
      ],
    },
    en: {
      windowTitle: 'ConstructHub Assistant',
      badgeLocal: 'Private by default',
      question: 'Which invoices are overdue?',
      answerPre: 'You have ',
      answerStrong: '2 overdue invoices',
      answerMid: ', totaling ',
      answerPost: ':',
      btnRemind: 'Send reminders',
      btnBilling: 'View invoicing',
      remindedOk: 'Reminders sent to 2 clients',
      placeholder: 'Ask the assistant…',
      toast: '2 reminders sent by email',
      invoices: [
        { num: 'FT 2026/0061', client: 'Construções Santa Cruz', value: '€ 4.980,00', days: '12 days' },
        { num: 'FT 2026/0044', client: 'Obras do Mar', value: '€ 2.450,00', days: '5 days' },
      ],
    },
    es: {
      windowTitle: 'Asistente ConstructHub',
      badgeLocal: 'Privado por defecto',
      question: '¿Qué facturas están vencidas?',
      answerPre: 'Tiene ',
      answerStrong: '2 facturas vencidas',
      answerMid: ', por un total de ',
      answerPost: ':',
      btnRemind: 'Enviar recordatorios',
      btnBilling: 'Ver facturación',
      remindedOk: 'Recordatorios enviados a los 2 clientes',
      placeholder: 'Pregunte al asistente…',
      toast: '2 recordatorios enviados por correo',
      invoices: [
        { num: 'FT 2026/0061', client: 'Construções Santa Cruz', value: '€ 4.980,00', days: '12 días' },
        { num: 'FT 2026/0044', client: 'Obras do Mar', value: '€ 2.450,00', days: '5 días' },
      ],
    },
  };

  function DemoChat() {
    const lang = (window.__DEMO_LANG === 'en' || window.__DEMO_LANG === 'es') ? window.__DEMO_LANG : 'pt';
    const s = STR[lang];
    const D = 10500;
    const t = window.useDemoLoop(D, 9000);
    const { dkTyped, dkCursor } = window;
    const { DemoCaret, DemoCursor, DemoToast, MiniWindow, DemoStage } = window;

    const question = s.question;
    const typedQ = dkTyped(question, t, 600, 2400);
    const typing = t >= 600 && t < 2400;
    const sent = t >= 3000;
    const thinking = t >= 3200 && t < 4400;
    const answer = t >= 4400;
    const rowOn = [t >= 5000, t >= 5400];
    const chips = t >= 6000;
    const reminded = t >= 7300;
    const toast = t >= 7800 && t < 10200;

    const cur = dkCursor(t, [
      { at: 0, x: 540, y: 390, hidden: true },
      { at: 2000, x: 540, y: 390 },
      { at: 2200, x: 482, y: 328 },
      { at: 5800, x: 122, y: 240 },
      { at: 8200, x: 540, y: 390, hidden: true },
    ], [2800, 7100]);

    return (
      <DemoStage t={t} dur={D}>
        <MiniWindow title={s.windowTitle} icon="sparkles" width={460} right={
          <span className="inline-flex items-center gap-1 h-5 px-2 rounded-full bg-indigo-50 border border-indigo-200 text-indigo-700 text-[10.5px] font-medium">
            <L name="lock" className="w-3 h-3" />{s.badgeLocal}
          </span>
        }>
          <div className="h-[220px] p-3 flex flex-col gap-2 overflow-hidden">
            {sent && (
              <div className="demo-rise self-end max-w-[75%] rounded-lg rounded-br-sm bg-zinc-900 text-zinc-50 px-3 py-2 text-[12px] leading-snug">
                {question}
              </div>
            )}
            {thinking && (
              <div className="demo-rise self-start inline-flex items-center gap-1 rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2.5">
                <span className="demo-dot"></span>
                <span className="demo-dot" style={{ animationDelay: '.15s' }}></span>
                <span className="demo-dot" style={{ animationDelay: '.3s' }}></span>
              </div>
            )}
            {answer && (
              <div className="demo-rise self-start max-w-[92%] rounded-lg rounded-bl-sm border border-zinc-200 bg-zinc-50 p-2.5">
                <div className="text-[12px] text-zinc-900 leading-snug">
                  {s.answerPre}<strong>{s.answerStrong}</strong>{s.answerMid}<span className="font-mono font-semibold">€ 7.430,00</span>{s.answerPost}
                </div>
                <div className="mt-1.5 flex flex-col gap-1">
                  {s.invoices.map((f, i) => (
                    <div key={f.num}
                      className="flex items-center gap-2 rounded-md border border-zinc-200 bg-white px-2 h-[26px] text-[10.5px]"
                      style={{ opacity: rowOn[i] ? 1 : 0, transform: rowOn[i] ? 'none' : 'translateY(5px)', transition: 'all .4s cubic-bezier(.2,.8,.2,1)' }}>
                      <span className="font-mono text-zinc-900 whitespace-nowrap">{f.num}</span>
                      <span className="text-zinc-500 truncate">{f.client}</span>
                      <span className="font-mono text-zinc-900 ml-auto whitespace-nowrap">{f.value}</span>
                      <span className="inline-flex items-center h-4 px-1.5 rounded-full bg-red-50 border border-red-200 text-red-700 text-[8.5px] font-medium whitespace-nowrap">{f.days}</span>
                    </div>
                  ))}
                </div>
                <div className="mt-2 h-7">
                  {chips && !reminded && (
                    <div className="demo-rise flex items-center gap-1.5">
                      <button className="h-7 px-2.5 rounded-md text-white text-[10.5px] font-medium whitespace-nowrap" style={{ background: '#18181B' }}>
                        {s.btnRemind}
                      </button>
                      <button className="h-7 px-2.5 rounded-md border border-zinc-200 bg-white text-zinc-700 text-[10.5px] font-medium whitespace-nowrap">
                        {s.btnBilling}
                      </button>
                    </div>
                  )}
                  {reminded && (
                    <div className="demo-rise inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md bg-emerald-50 border border-emerald-200 text-emerald-700 text-[10.5px] font-medium whitespace-nowrap">
                      <L name="check" className="w-3 h-3" />
                      {s.remindedOk}
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          <div className="border-t border-zinc-100 p-2.5 flex items-center gap-2">
            <div className="flex-1 h-9 px-3 rounded-md border border-zinc-200 bg-white flex items-center text-[12px] text-zinc-900">
              {!sent && typedQ}
              <DemoCaret show={typing} />
              {!sent && !typedQ && !typing && <span className="text-zinc-400">{s.placeholder}</span>}
              {sent && <span className="text-zinc-400">{s.placeholder}</span>}
            </div>
            <button className="h-9 w-9 rounded-md flex items-center justify-center text-white shrink-0" style={{ background: '#18181B' }}>
              <L name="arrow-up" className="w-4 h-4" />
            </button>
          </div>
        </MiniWindow>

        <DemoCursor s={cur} />
        <DemoToast show={toast} text={s.toast} icon="send" />
      </DemoStage>
    );
  }

  window.DemoChat = DemoChat;
})();
