// DemoPortal.jsx — auto-looping demo: portal B2B.
// O cliente pesquisa "tijolo", adiciona dois artigos ao carrinho e confirma a
// encomenda — que aparece logo no painel de vendas do distribuidor.
// i18n: lê window.__DEMO_LANG ('pt' | 'en' | 'es') a cada render.

(function () {
  const STR = {
    pt: {
      windowTitle: 'Portal B2B · Materiais Faria, Lda.',
      searchQuery: 'tijolo',
      searchPlaceholder: 'Pesquisar no catálogo…',
      productNames: ['Tijolo térmico 11×20×30 cm', 'Tijolo face vista 7×11×24 cm'],
      perUnit: 's/ IVA · por unidade',
      add: 'Adicionar',
      added: 'Adicionado',
      item: 'artigo',
      items: 'artigos',
      plusVat: ' + IVA',
      confirmOrder: 'Confirmar encomenda',
      orderPre: 'Encomenda',
      orderPost: 'recebida',
      emailNote: 'confirmação por email',
      toast: 'Nova encomenda no painel de vendas',
    },
    en: {
      windowTitle: 'B2B Portal · Materiais Faria, Lda.',
      searchQuery: 'brick',
      searchPlaceholder: 'Search the catalog…',
      productNames: ['Thermal brick 11×20×30 cm', 'Facing brick 7×11×24 cm'],
      perUnit: 'excl. VAT · per unit',
      add: 'Add',
      added: 'Added',
      item: 'item',
      items: 'items',
      plusVat: ' + VAT',
      confirmOrder: 'Confirm order',
      orderPre: 'Order',
      orderPost: 'received',
      emailNote: 'email confirmation',
      toast: 'New order in the sales dashboard',
    },
    es: {
      windowTitle: 'Portal B2B · Materiais Faria, Lda.',
      searchQuery: 'ladrillo',
      searchPlaceholder: 'Buscar en el catálogo…',
      productNames: ['Ladrillo térmico 11×20×30 cm', 'Ladrillo cara vista 7×11×24 cm'],
      perUnit: 'sin IVA · por unidad',
      add: 'Añadir',
      added: 'Añadido',
      item: 'artículo',
      items: 'artículos',
      plusVat: ' + IVA',
      confirmOrder: 'Confirmar pedido',
      orderPre: 'Pedido',
      orderPost: 'recibido',
      emailNote: 'confirmación por email',
      toast: 'Nuevo pedido en el panel de ventas',
    },
  };

  const PORTAL_PRODUCTS = [
    { sku: 'TIJ-7715', price: '€ 0,42', icon: 'layers' },
    { sku: 'TIJ-7720', price: '€ 0,68', icon: 'package' },
  ];

  function PortalCard({ p, name, visible, added, s }) {
    return (
      <div
        className="rounded-lg border border-zinc-200 bg-white overflow-hidden"
        style={{ opacity: visible ? 1 : 0, transform: visible ? 'none' : 'translateY(8px)', transition: 'all .45s cubic-bezier(.2,.8,.2,1)', boxShadow: '0 1px 2px rgba(0,0,0,.04)' }}
      >
        <div className="h-16 grid place-items-center bg-zinc-50 border-b border-zinc-100">
          <L name={p.icon} className="w-6 h-6 text-zinc-300" strokeWidth={1.25} />
        </div>
        <div className="p-2.5">
          <div className="font-mono text-[9.5px] text-zinc-400 tracking-tight">{p.sku}</div>
          <div className="text-[11.5px] font-medium text-zinc-900 leading-snug h-[30px] overflow-hidden mt-0.5">{name}</div>
          <div className="flex items-end justify-between mt-1.5">
            <div>
              <div className="text-[13px] font-semibold text-zinc-900">{p.price}</div>
              <div className="text-[9px] text-zinc-500 whitespace-nowrap">{s.perUnit}</div>
            </div>
            <button
              className={'h-7 px-2.5 rounded-md text-[10.5px] font-medium inline-flex items-center gap-1 whitespace-nowrap ' +
                (added ? 'border border-emerald-200 bg-emerald-50 text-emerald-700' : 'bg-zinc-900 text-white')}
              style={{ transition: 'all .35s' }}
            >
              <L name={added ? 'check' : 'plus'} className="w-3 h-3" />
              {added ? s.added : s.add}
            </button>
          </div>
        </div>
      </div>
    );
  }

  function DemoPortal() {
    const lang = (window.__DEMO_LANG === 'en' || window.__DEMO_LANG === 'es') ? window.__DEMO_LANG : 'pt';
    const s = STR[lang];

    const D = 10000;
    const t = window.useDemoLoop(D, 8600);
    const { dkTyped, dkCursor } = window;
    const { DemoCaret, DemoCursor, DemoToast, MiniWindow, DemoStage } = window;

    const query = dkTyped(s.searchQuery, t, 500, 1300);
    const typing = t >= 500 && t < 1300;
    const cardOn = [t >= 1700, t >= 2000];
    const added = [t >= 3100, t >= 4000];
    const count = (added[0] ? 1 : 0) + (added[1] ? 1 : 0);
    const total = added[1] ? '€ 380,00' : added[0] ? '€ 210,00' : '€ 0,00';
    const confirmed = t >= 6100;
    const toast = t >= 6550 && t < 9300;

    const cur = dkCursor(t, [
      { at: 0, x: 545, y: 390, hidden: true },
      { at: 2300, x: 545, y: 390 },
      { at: 2450, x: 224, y: 269 },
      { at: 3300, x: 464, y: 269 },
      { at: 4800, x: 426, y: 326 },
      { at: 7000, x: 545, y: 390, hidden: true },
    ], [3000, 3900, 5700]);

    const cart = (
      <span className="relative inline-flex items-center text-zinc-500">
        <L name="shopping-cart" className="w-4 h-4" />
        <span key={count} className="demo-rise absolute -top-1.5 -right-2 h-4 min-w-4 px-1 rounded-full text-[9.5px] font-semibold flex items-center justify-center text-white"
          style={{ background: count > 0 ? '#4F6EF7' : '#A1A1AA' }}>
          {count}
        </span>
      </span>
    );

    return (
      <DemoStage t={t} dur={D}>
        <MiniWindow title={s.windowTitle} icon="building-2" width={500} right={cart}>
          <div className="p-4">
            <div className="flex items-center gap-2 h-9 px-3 rounded-md border border-zinc-200 bg-white shadow-sm text-[13px] text-zinc-900">
              <L name="search" className="w-3.5 h-3.5 text-zinc-400" />
              {query}
              <DemoCaret show={typing} />
              {!query && !typing && <span className="text-zinc-400">{s.searchPlaceholder}</span>}
            </div>

            <div className="grid grid-cols-2 gap-3 mt-3">
              <PortalCard p={PORTAL_PRODUCTS[0]} name={s.productNames[0]} visible={cardOn[0]} added={added[0]} s={s} />
              <PortalCard p={PORTAL_PRODUCTS[1]} name={s.productNames[1]} visible={cardOn[1]} added={added[1]} s={s} />
            </div>

            <div className="mt-3 h-[52px] rounded-lg border border-zinc-200 bg-zinc-50 px-3 flex items-center">
              {!confirmed ? (
                <div className="flex items-center justify-between w-full">
                  <div className="text-[12px] text-zinc-500">
                    {count} {count === 1 ? s.item : s.items} ·{' '}
                    <span className="font-mono text-zinc-900 font-medium">{total}</span>
                    <span className="text-zinc-400">{s.plusVat}</span>
                  </div>
                  <button
                    className="h-8 px-3.5 rounded-md text-white text-[11.5px] font-medium whitespace-nowrap"
                    style={{ background: count > 0 ? '#4F6EF7' : '#A1A1AA', transition: 'background .35s' }}
                  >
                    {s.confirmOrder}
                  </button>
                </div>
              ) : (
                <div key="ok" className="demo-rise flex items-center gap-2.5 w-full">
                  <L name="check-circle-2" className="w-4 h-4 text-emerald-600 shrink-0" />
                  <div className="text-[12px] text-zinc-900 font-medium truncate">
                    {s.orderPre} <span className="font-mono">ENC-2026-0103</span> {s.orderPost}
                  </div>
                  <span className="ml-auto text-[10.5px] text-zinc-500 shrink-0 whitespace-nowrap">{s.emailNote}</span>
                </div>
              )}
            </div>
          </div>
        </MiniWindow>

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

  window.DemoPortal = DemoPortal;
})();
