// DemoStock.jsx — auto-looping demo: stock inteligente (IA local).
// Timeline ~10s: stock do cimento esgota-se → alerta IA com previsão de rutura
// → cursor clica "Criar ordem de compra" → OC criada + chip "+400 a caminho".

(function () {
  const STR = {
    pt: {
      stOk: 'OK', stLow: 'Baixo', stCrit: 'Crítico',
      unit: 'un',
      winTitle: 'Armazém · Stock',
      iaBadge: 'Alertas de stock',
      colItem: 'Artigo', colStock: 'Stock', colStatus: 'Estado',
      prodCement: 'Cimento CEM II 32,5N · 25 kg',
      prodSand: 'Areia fina 0/4 · big bag',
      prodBrick: 'Tijolo cerâmico 30×20×15',
      onTheWay: '+400 a caminho',
      alertTitle: 'Stock mínimo atingido',
      alertRate: '· consumo 68 un/dia',
      alertSuggestion: 'Repor: 400 un · Cimpor, S.A. — entrega 48 h',
      btnCreatePO: 'Criar ordem de compra',
      ocCreated: 'criada · 400 un · Cimpor, S.A.',
      delivery48: 'entrega 48 h',
      toast: 'Ordem de compra enviada ao fornecedor',
    },
    en: {
      stOk: 'OK', stLow: 'Low', stCrit: 'Critical',
      unit: 'pcs',
      winTitle: 'Warehouse · Stock',
      iaBadge: 'Stock alerts',
      colItem: 'Item', colStock: 'Stock', colStatus: 'Status',
      prodCement: 'Cement CEM II 32,5N · 25 kg',
      prodSand: 'Fine sand 0/4 · big bag',
      prodBrick: 'Ceramic brick 30×20×15',
      onTheWay: '+400 on the way',
      alertTitle: 'Below minimum stock',
      alertRate: '· usage 68 pcs/day',
      alertSuggestion: 'Reorder: 400 pcs · Cimpor, S.A. — 48 h delivery',
      btnCreatePO: 'Create purchase order',
      ocCreated: 'created · 400 pcs · Cimpor, S.A.',
      delivery48: '48 h delivery',
      toast: 'Purchase order sent to the supplier',
    },
    es: {
      stOk: 'OK', stLow: 'Bajo', stCrit: 'Crítico',
      unit: 'ud',
      winTitle: 'Almacén · Stock',
      iaBadge: 'Alertas de stock',
      colItem: 'Artículo', colStock: 'Stock', colStatus: 'Estado',
      prodCement: 'Cemento CEM II 32,5N · 25 kg',
      prodSand: 'Arena fina 0/4 · big bag',
      prodBrick: 'Ladrillo cerámico 30×20×15',
      onTheWay: '+400 en camino',
      alertTitle: 'Stock mínimo alcanzado',
      alertRate: '· consumo 68 ud/día',
      alertSuggestion: 'Reponer: 400 ud · Cimpor, S.A. — entrega en 48 h',
      btnCreatePO: 'Crear orden de compra',
      ocCreated: 'creada · 400 ud · Cimpor, S.A.',
      delivery48: 'entrega 48 h',
      toast: 'Orden de compra enviada al proveedor',
    },
  };

  function chipFor(stock, s) {
    if (stock >= 300) return { cls: 'bg-zinc-100 border-zinc-200 text-zinc-500', label: s.stOk };
    if (stock >= 150) return { cls: 'bg-amber-50 border-amber-200 text-amber-700', label: s.stLow };
    return { cls: 'bg-red-50 border-red-200 text-red-700', label: s.stCrit };
  }

  function StockRow({ name, sku, stock, max, chip, extra, unit }) {
    const pct = Math.max(3, Math.round((stock / max) * 100));
    const barColor = pct > 50 ? '#A1A1AA' : pct > 20 ? '#F59E0B' : '#EF4444';
    return (
      <div className="grid grid-cols-[1fr_150px_96px] items-center gap-3 px-3 h-12 border-b border-zinc-100">
        <div className="min-w-0">
          <div className="text-[12.5px] text-zinc-900 truncate leading-tight">{name}</div>
          <div className="font-mono text-[10.5px] text-zinc-400 leading-tight">{sku}</div>
        </div>
        <div className="flex items-center gap-2">
          <div className="flex-1 h-1.5 rounded-full bg-zinc-100 overflow-hidden">
            <div className="h-full rounded-full" style={{ width: pct + '%', background: barColor, transition: 'width .2s linear, background .4s' }}></div>
          </div>
          <span className="font-mono text-[11px] text-zinc-500 w-14 text-right tabular-nums">
            {stock.toLocaleString('pt-PT')} {unit}
          </span>
        </div>
        <div className="flex justify-end">
          {extra || (
            <span className={'inline-flex items-center h-5 px-2 rounded-full border text-[10.5px] font-medium ' + chip.cls}>
              {chip.label}
            </span>
          )}
        </div>
      </div>
    );
  }

  function DemoStock() {
    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, 8300);
    const { dkProg, dkEase, dkCursor } = window;
    const { DemoCursor, DemoToast, MiniWindow, DemoStage } = window;

    const stock1 = Math.round(600 - 536 * dkEase(dkProg(t, 600, 2600)));
    const alertOn = t >= 3000;
    const ordered = t >= 5400;
    const toast = t >= 5900 && t < 9300;

    const cur = dkCursor(t, [
      { at: 0, x: 540, y: 390, hidden: true },
      { at: 4100, x: 540, y: 390 },
      { at: 4350, x: 442, y: 290 },
      { at: 6600, x: 540, y: 390, hidden: true },
    ], [5200]);

    const iaBadge = (
      <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="bell" className="w-3 h-3" />{s.iaBadge}
      </span>
    );

    return (
      <DemoStage t={t} dur={D}>
        <MiniWindow title={s.winTitle} icon="warehouse" width={490} right={iaBadge}>
          <div className="p-3.5 pt-3">
            <div className="grid grid-cols-[1fr_150px_96px] gap-3 px-3 h-7 items-center text-[10.5px] uppercase tracking-wider text-zinc-400 font-medium">
              <span>{s.colItem}</span><span>{s.colStock}</span><span className="text-right">{s.colStatus}</span>
            </div>

            <StockRow
              name={s.prodCement} sku="CEM-25"
              stock={stock1} max={600} chip={chipFor(stock1, s)} unit={s.unit}
              extra={ordered ? (
                <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 demo-rise whitespace-nowrap">
                  <L name="truck" className="w-3 h-3" />{s.onTheWay}
                </span>
              ) : null}
            />
            <StockRow name={s.prodSand} sku="ARE-04" stock={1240} max={1600} chip={chipFor(1240, s)} unit={s.unit} />
            <StockRow name={s.prodBrick} sku="TIJ-30" stock={8400} max={12000} chip={chipFor(8400, s)} unit={s.unit} />

            <div className="mt-2.5 h-[64px]">
              {alertOn && !ordered && (
                <div className="rounded-lg border border-indigo-200 bg-indigo-50/60 px-3 py-2.5 flex items-center gap-3 demo-rise">
                  <span className="h-7 w-7 rounded-md text-white flex items-center justify-center shrink-0" style={{ background: '#4F6EF7' }}>
                    <L name="sparkles" className="w-3.5 h-3.5" />
                  </span>
                  <div className="flex-1 min-w-0">
                    <div className="text-[12px] font-medium text-zinc-900 leading-tight truncate">
                      {s.alertTitle} <span className="text-zinc-400 font-normal">{s.alertRate}</span>
                    </div>
                    <div className="text-[11px] text-zinc-500 leading-tight mt-0.5 truncate">
                      {s.alertSuggestion}
                    </div>
                  </div>
                  <button className="h-8 px-3 rounded-md text-white text-[11.5px] font-medium shrink-0 whitespace-nowrap" style={{ background: '#4F6EF7' }}>
                    {s.btnCreatePO}
                  </button>
                </div>
              )}
              {ordered && (
                <div className="rounded-lg border border-emerald-200 bg-emerald-50/60 px-3 flex items-center gap-2.5 demo-rise h-[64px]">
                  <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">
                    <span className="font-mono">OC-2026-0118</span> {s.ocCreated}
                  </div>
                  <span className="ml-auto text-[11px] text-zinc-400 shrink-0">{s.delivery48}</span>
                </div>
              )}
            </div>
          </div>
        </MiniWindow>

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

  window.DemoStock = DemoStock;
})();
