// Scene 5 — Grilla quincena: tabla quincenal que se completa y
// finaliza con un click que exporta a Excel.

function SceneGrilla({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      {({ localTime, duration }) => {
        const appT = clamp(localTime / 0.6, 0, 1);
        const app = Easing.easeOutCubic(appT);
        const exitT = clamp((localTime - (duration - 0.5)) / 0.5, 0, 1);
        const exit = Easing.easeInCubic(exitT);

        return (
          <div style={{
            position: 'absolute', inset: 0,
            background: OP_COLORS.bg,
            opacity: 1 - exit,
            transform: `translateY(${exit * -30}px)`,
          }}>
            <ChapterTag index={3} total={3} title="Grilla quincena · liquidación" />

            <GrillaWindow localTime={localTime} app={app} />

            {/* Caption */}
            <Caption2 localTime={localTime} />

            {/* Excel download toast, fires late */}
            <ExcelToast localTime={localTime} />
          </div>
        );
      }}
    </Sprite>
  );
}

function GrillaWindow({ localTime, app }) {
  const days = ['L 1', 'M 2', 'M 3', 'J 4', 'V 5', 'S 6', 'L 8', 'M 9', 'M 10', 'J 11', 'V 12', 'S 13', 'L 15'];
  const obras = [
    { name: 'Av. San Martín 1250', row: [1,1,1,2,1,3,1,1,2,1,1,3,1] },
    { name: 'Edificio Puerto Norte', row: [1,1,2,1,1,3,1,2,1,1,1,3,2] },
    { name: 'Ruta 11 Km 42',         row: [2,1,1,1,3,3,1,1,1,2,1,3,1] },
    { name: 'Depósito Oeste',        row: [1,3,1,1,1,3,1,1,3,1,1,3,1] },
    { name: 'Escuela N°7',           row: [1,1,1,2,1,3,2,1,1,1,1,3,1] },
  ];
  // status codes: 1=aprobado (verde), 2=pendiente (azul), 3=sin actividad (neutro)
  const statusMap = {
    1: { bg: `${OP_COLORS.green}22`, border: `${OP_COLORS.green}66`, color: OP_COLORS.greenLight, label: '✓' },
    2: { bg: `${OP_COLORS.blue}22`,  border: `${OP_COLORS.blue}66`,  color: OP_COLORS.blueLight,  label: '●' },
    3: { bg: 'rgba(148,163,184,0.08)', border: OP_COLORS.border, color: OP_COLORS.textMute, label: '–' },
  };

  return (
    <div style={{
      position: 'absolute',
      left: 120, top: 130,
      right: 120, bottom: 200,
      background: OP_COLORS.surface,
      borderRadius: 18,
      border: `1px solid ${OP_COLORS.border2}`,
      boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
      overflow: 'hidden',
      opacity: app,
      transform: `translateY(${(1 - app) * 30}px)`,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '16px 22px',
        borderBottom: `1px solid ${OP_COLORS.border}`,
        background: OP_COLORS.bg2,
        fontFamily: SANS, color: OP_COLORS.text,
      }}>
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.01em' }}>
            Quincena · 1 – 15 abril
          </div>
          <div style={{ fontSize: 13, color: OP_COLORS.textDim, marginTop: 2 }}>
            Todos los partes del período · 5 obras · 65 registros
          </div>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 10 }}>
          <div style={{
            padding: '8px 14px', borderRadius: 8,
            border: `1px solid ${OP_COLORS.border2}`,
            color: OP_COLORS.textDim,
            fontSize: 13, fontFamily: SANS, fontWeight: 500,
          }}>Filtrar</div>
          <ExcelButton localTime={localTime} />
        </div>
      </div>

      {/* Grid */}
      <div style={{ flex: 1, overflow: 'hidden', padding: 22 }}>
        {/* Days header */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: `260px repeat(${days.length}, 1fr)`,
          gap: 6,
          marginBottom: 10,
        }}>
          <div style={{
            fontSize: 11, fontWeight: 600, color: OP_COLORS.textMute,
            fontFamily: MONO, letterSpacing: '0.15em',
            padding: '6px 0',
          }}>OBRA</div>
          {days.map((d, i) => (
            <div key={i} style={{
              fontSize: 12, fontWeight: 600,
              color: OP_COLORS.textDim,
              textAlign: 'center', fontFamily: MONO,
              padding: '6px 0',
            }}>{d}</div>
          ))}
        </div>

        {/* Rows */}
        {obras.map((o, ri) => (
          <div key={ri} style={{
            display: 'grid',
            gridTemplateColumns: `260px repeat(${days.length}, 1fr)`,
            gap: 6,
            marginBottom: 6,
          }}>
            <div style={{
              fontSize: 14, fontWeight: 600, color: OP_COLORS.text,
              fontFamily: SANS,
              padding: '8px 12px',
              background: OP_COLORS.bg2,
              borderRadius: 8,
              display: 'flex', alignItems: 'center',
            }}>{o.name}</div>
            {o.row.map((s, ci) => {
              // Cells fill in left-to-right, row-by-row
              const cellT = 0.7 + (ri * 0.15) + (ci * 0.05);
              const visible = localTime > cellT;
              const fadeIn = clamp((localTime - cellT) / 0.25, 0, 1);
              const st = statusMap[s];
              if (!visible) {
                return <div key={ci} style={{
                  background: 'rgba(148,163,184,0.04)',
                  borderRadius: 6, minHeight: 40,
                }} />;
              }
              return (
                <div key={ci} style={{
                  background: st.bg,
                  border: `1px solid ${st.border}`,
                  color: st.color,
                  borderRadius: 6,
                  minHeight: 40,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: MONO, fontSize: 15, fontWeight: 700,
                  opacity: fadeIn,
                  transform: `scale(${0.7 + 0.3 * fadeIn})`,
                }}>{st.label}</div>
              );
            })}
          </div>
        ))}

        {/* Legend */}
        <div style={{
          marginTop: 16, display: 'flex', gap: 20,
          fontFamily: SANS, fontSize: 12, color: OP_COLORS.textDim,
        }}>
          <Legend color={OP_COLORS.greenLight} label="Aprobado" />
          <Legend color={OP_COLORS.blueLight}  label="Pendiente revisión" />
          <Legend color={OP_COLORS.textMute}   label="Sin actividad" />
        </div>
      </div>
    </div>
  );
}

function Legend({ color, label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ width: 10, height: 10, borderRadius: 3, background: color }} />
      <span>{label}</span>
    </div>
  );
}

function ExcelButton({ localTime }) {
  const clickT = 4.5;
  const pulse = localTime > clickT - 0.4 && localTime < clickT + 0.3;
  const clicked = localTime > clickT && localTime < clickT + 0.25;

  return (
    <div style={{
      position: 'relative',
      padding: '8px 14px', borderRadius: 8,
      background: OP_COLORS.green,
      color: '#fff',
      fontSize: 13, fontFamily: SANS, fontWeight: 700,
      display: 'flex', alignItems: 'center', gap: 8,
      boxShadow: pulse ? `0 0 0 ${Math.abs(Math.sin(localTime * 8)) * 8 + 2}px ${OP_COLORS.green}55` : 'none',
      transform: clicked ? 'scale(0.95)' : 'scale(1)',
      transition: 'transform 0.15s',
    }}>
      <svg width={14} height={14} viewBox="0 0 16 16" fill="#fff">
        <path d="M8 1v10m-3-3l3 3 3-3" stroke="#fff" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M2 12v2a1 1 0 001 1h10a1 1 0 001-1v-2" stroke="#fff" strokeWidth="1.8" fill="none" strokeLinecap="round"/>
      </svg>
      Exportar a Excel
      {localTime > clickT && localTime < clickT + 0.8 && (
        <Cursor x={-30} y={-12} />
      )}
    </div>
  );
}

function Cursor({ x, y }) {
  return (
    <svg style={{ position: 'absolute', left: x, top: y }} width={22} height={22} viewBox="0 0 24 24">
      <path d="M4 2 L4 18 L9 14 L12 22 L15 21 L12 13 L19 13 Z" fill="#fff" stroke="#000" strokeWidth="1" />
    </svg>
  );
}

function Caption2({ localTime }) {
  const t = clamp((localTime - 0.8) / 0.5, 0, 1);
  const t2 = clamp((localTime - 1.3) / 0.5, 0, 1);
  return (
    <div style={{
      position: 'absolute',
      left: 120, bottom: 50,
      fontFamily: SANS,
    }}>
      <div style={{
        fontSize: 38, fontWeight: 700, color: OP_COLORS.text,
        letterSpacing: '-0.02em',
        opacity: Easing.easeOutCubic(t),
        transform: `translateY(${(1 - t) * 12}px)`,
      }}>La quincena, liquidada en un click.</div>
      <div style={{
        fontSize: 18, color: OP_COLORS.textDim, marginTop: 8,
        opacity: Easing.easeOutCubic(t2),
      }}>
        Gerencia revisa, aprueba y exporta a Excel con una fila por persona.
      </div>
    </div>
  );
}

function ExcelToast({ localTime }) {
  const startT = 4.8;
  if (localTime < startT) return null;
  const t = clamp((localTime - startT) / 0.5, 0, 1);
  return (
    <div style={{
      position: 'absolute',
      right: 140, bottom: 230,
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '14px 20px',
      background: '#107c41',
      border: `1px solid #1e9a57`,
      borderRadius: 12,
      color: '#fff', fontFamily: SANS,
      boxShadow: '0 20px 50px rgba(16,124,65,0.45)',
      opacity: Easing.easeOutCubic(t),
      transform: `translateY(${(1 - t) * 30}px) scale(${0.9 + 0.1 * t})`,
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 8,
        background: '#fff', color: '#107c41',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: SANS, fontWeight: 800, fontSize: 18,
      }}>X</div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 15 }}>quincena-abril-1.xlsx</div>
        <div style={{ fontSize: 12, opacity: 0.85, fontFamily: MONO }}>65 filas · descargado</div>
      </div>
    </div>
  );
}

Object.assign(window, { SceneGrilla });
