// DemoCalendar.jsx — auto-looping demo: calendários de trabalho (Scheduler).
// Espelha a "Biblioteca de calendários": o cursor torna o Sábado útil no
// calendário de obra, a semana passa de Seg–Sex a Seg–Sáb (40 h → 48 h) e o
// agendamento CPM reagenda as atividades do projeto.

(function () {
  const STR = {
    pt: {
      days: ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'],
      title: 'Scheduler · Biblioteca de calendários',
      calName: 'Obra — Fase 2',
      rangeMonSat: 'Seg–Sáb',
      rangeMonFri: 'Seg–Sex',
      calDesc: 'Frente de obra. Domingos e feriados não úteis.',
      calMeta: '15 feriados · 1 projeto · 24 atividades',
      workWeek: 'Semana de trabalho',
      off: 'Folga',
      totalPre: 'Total semanal',
      totalPost: 'úteis',
      recalc: 'A recalcular CPM…',
      updated: 'Agendamento atualizado',
      save: 'Guardar e reagendar',
      toast: '24 atividades reagendadas no projeto',
    },
    en: {
      days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      title: 'Scheduler · Calendar library',
      calName: 'Site — Phase 2',
      rangeMonSat: 'Mon–Sat',
      rangeMonFri: 'Mon–Fri',
      calDesc: 'Site work front. Sundays and holidays non-working.',
      calMeta: '15 holidays · 1 project · 24 activities',
      workWeek: 'Working week',
      off: 'Off',
      totalPre: 'Weekly total',
      totalPost: 'of work',
      recalc: 'Recalculating CPM…',
      updated: 'Schedule updated',
      save: 'Save and reschedule',
      toast: '24 activities rescheduled in the project',
    },
    es: {
      days: ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'],
      title: 'Scheduler · Biblioteca de calendarios',
      calName: 'Obra — Fase 2',
      rangeMonSat: 'Lun–Sáb',
      rangeMonFri: 'Lun–Vie',
      calDesc: 'Frente de obra. Domingos y festivos no laborables.',
      calMeta: '15 festivos · 1 proyecto · 24 actividades',
      workWeek: 'Semana laboral',
      off: 'Libre',
      totalPre: 'Total semanal',
      totalPost: 'útiles',
      recalc: 'Recalculando CPM…',
      updated: 'Programación actualizada',
      save: 'Guardar y reprogramar',
      toast: '24 actividades reprogramadas en el proyecto',
    },
  };

  function WeekDots({ useful, days }) {
    return (
      <span className="inline-flex items-center gap-[3px]">
        {days.map((d, i) => (
          <span key={i} className="h-[7px] w-[7px] rounded-[2px]"
            style={{ background: useful[i] ? '#4F6EF7' : '#E4E4E7', transition: 'background .3s' }}></span>
        ))}
      </span>
    );
  }

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

    const satOn = t >= 2800;
    const hours = Math.round(40 + 8 * dkEase(dkProg(t, 2800, 3600)));
    const saving = t >= 5300 && t < 6600;
    const saved = t >= 6600;
    const toast = t >= 6900 && t < 9400;
    const useful = [true, true, true, true, true, satOn, false];

    const cur = dkCursor(t, [
      { at: 0, x: 540, y: 390, hidden: true },
      { at: 1600, x: 540, y: 390 },
      { at: 1800, x: 418, y: 240 },
      { at: 4400, x: 438, y: 296 },
      { at: 7600, x: 540, y: 390, hidden: true },
    ], [2600, 5200]);

    return (
      <DemoStage t={t} dur={D}>
        <MiniWindow title={s.title} icon="calendar-days" width={510} right={
          <span className="inline-flex items-center h-5 px-2 rounded-full bg-zinc-100 border border-zinc-200 text-zinc-500 text-[10.5px] font-medium whitespace-nowrap">CPM</span>
        }>
          <div className="p-3.5">
            {/* library row */}
            <div className="rounded-lg border border-zinc-200 p-3 flex items-center gap-3">
              <span className="h-9 w-9 rounded-md bg-indigo-50 border border-indigo-100 flex items-center justify-center shrink-0">
                <L name="calendar-days" className="w-4 h-4" style={{ color: '#4F6EF7' }} />
              </span>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-[12.5px] font-medium text-zinc-900 truncate">{s.calName}</span>
                  <span key={satOn ? 'b' : 'a'} className="demo-rise font-mono text-[10px] text-zinc-400 whitespace-nowrap">
                    {satOn ? s.rangeMonSat : s.rangeMonFri}
                  </span>
                </div>
                <div className="text-[10.5px] text-zinc-500 truncate mt-0.5">{s.calDesc}</div>
              </div>
              <div className="flex flex-col items-end gap-1 shrink-0">
                <WeekDots useful={useful} days={s.days} />
                <span className="inline-flex items-center gap-1 text-[10px] text-zinc-500 whitespace-nowrap">
                  <span className="h-[6px] w-[6px] rounded-[2px] bg-amber-500"></span>
                  {s.calMeta}
                </span>
              </div>
            </div>

            {/* week editor */}
            <div className="text-[9.5px] uppercase tracking-widest text-zinc-400 font-medium mt-2.5 mb-1.5">{s.workWeek}</div>
            <div className="grid grid-cols-7 gap-1.5">
              {s.days.map((d, i) => {
                const on = useful[i];
                const isSat = i === 5;
                return (
                  <div key={i}
                    className={
                      'rounded-md border h-14 flex flex-col items-center justify-center gap-0.5 ' +
                      (on ? 'border-zinc-200 bg-white' : 'border-zinc-200 bg-zinc-50') +
                      (isSat && satOn && t < 3600 ? ' demo-pulse' : '')
                    }
                    style={isSat && satOn ? { borderColor: '#C7D2FE' } : undefined}
                  >
                    <span className={'text-[10px] font-medium ' + (on ? 'text-zinc-700' : 'text-zinc-400')}>{d}</span>
                    <span className={'font-mono text-[10.5px] ' + (on ? 'text-zinc-900' : 'text-zinc-400')}>
                      {on ? '8 h' : s.off}
                    </span>
                  </div>
                );
              })}
            </div>

            {/* footer */}
            <div className="mt-3 flex items-center justify-between">
              <span className="text-[11px] text-zinc-500">
                {s.totalPre} <span className="font-mono font-semibold text-zinc-900 tabular-nums">{hours} h</span> {s.totalPost}
              </span>
              <button
                className="inline-flex items-center gap-2 h-9 px-4 rounded-md text-white text-[12px] font-medium whitespace-nowrap"
                style={{ background: saved ? '#059669' : '#18181B', transition: 'background .4s' }}
              >
                {saving ? (
                  <span className="inline-flex items-center gap-2"><L name="loader-2" className="w-3.5 h-3.5 animate-spin" />{s.recalc}</span>
                ) : saved ? (
                  <span className="inline-flex items-center gap-2"><L name="check" className="w-3.5 h-3.5" />{s.updated}</span>
                ) : (
                  <span className="inline-flex items-center gap-2"><L name="calendar-check" className="w-3.5 h-3.5" />{s.save}</span>
                )}
              </button>
            </div>
          </div>
        </MiniWindow>

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

  window.DemoCalendar = DemoCalendar;
})();
