// Scene 4 — Parte diario: mobile phone. Encargado dicta por voz
// los datos del día. El formulario se completa solo.

function SceneParteDiario({ 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: `radial-gradient(70% 70% at 70% 50%, ${OP_COLORS.surface} 0%, ${OP_COLORS.bg} 60%)`,
            opacity: 1 - exit,
            transform: `translateY(${exit * -30}px)`,
          }}>
            <ChapterTag index={2} total={3} title="Parte diario en el celular" />

            {/* Phone on the right */}
            <Phone localTime={localTime} />

            {/* Left-side copy */}
            <LeftCopy localTime={localTime} app={app} />

            {/* Sound wave visualization during dictation */}
            <VoiceIndicator localTime={localTime} />
          </div>
        );
      }}
    </Sprite>
  );
}

function LeftCopy({ localTime, app }) {
  const line1T = clamp((localTime - 0.5) / 0.5, 0, 1);
  const line2T = clamp((localTime - 1.1) / 0.5, 0, 1);
  const bulletsT = [
    clamp((localTime - 1.8) / 0.4, 0, 1),
    clamp((localTime - 2.3) / 0.4, 0, 1),
    clamp((localTime - 2.8) / 0.4, 0, 1),
  ];

  return (
    <div style={{
      position: 'absolute',
      left: 140, top: 230,
      width: 720,
      fontFamily: SANS,
      opacity: app,
    }}>
      <div style={{
        fontFamily: MONO, fontSize: 14, letterSpacing: '0.25em',
        color: OP_COLORS.greenLight, textTransform: 'uppercase',
        opacity: Easing.easeOutCubic(line1T),
        transform: `translateY(${(1 - line1T) * 12}px)`,
        marginBottom: 20,
      }}>
        Cero papeles en la obra
      </div>

      <div style={{
        fontSize: 92, fontWeight: 800, letterSpacing: '-0.035em',
        color: OP_COLORS.text, lineHeight: 1.0,
        opacity: Easing.easeOutCubic(line2T),
        transform: `translateY(${(1 - line2T) * 20}px)`,
      }}>
        El encargado <br/>
        <span style={{
          background: `linear-gradient(90deg, ${OP_COLORS.greenLight}, ${OP_COLORS.blueLight})`,
          WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
        }}>dicta el parte.</span>
      </div>

      <div style={{ marginTop: 50, display: 'flex', flexDirection: 'column', gap: 18 }}>
        {[
          { i: '🎙', label: 'Dictado por voz', sub: 'Sin tipear en la obra.' },
          { i: '✓',  label: 'Asistencia del personal', sub: 'Un toque por persona.' },
          { i: '→',  label: 'Envía a gerencia', sub: 'Listo para revisar y aprobar.' },
        ].map((b, i) => (
          <Bullet key={i} t={bulletsT[i]} icon={b.i} label={b.label} sub={b.sub} />
        ))}
      </div>
    </div>
  );
}

function Bullet({ t, icon, label, sub }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 16,
      opacity: Easing.easeOutCubic(t),
      transform: `translateX(${(1 - t) * 20}px)`,
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: `${OP_COLORS.green}22`,
        border: `1px solid ${OP_COLORS.green}66`,
        color: OP_COLORS.greenLight,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 22, fontFamily: SANS, flexShrink: 0,
      }}>{icon}</div>
      <div>
        <div style={{
          color: OP_COLORS.text, fontFamily: SANS,
          fontWeight: 700, fontSize: 22,
        }}>{label}</div>
        <div style={{
          color: OP_COLORS.textDim, fontFamily: SANS,
          fontSize: 15, marginTop: 2,
        }}>{sub}</div>
      </div>
    </div>
  );
}

// ── Phone frame ───────────
function Phone({ localTime }) {
  const appT = clamp((localTime - 0.3) / 0.7, 0, 1);
  const app = Easing.easeOutCubic(appT);
  return (
    <div style={{
      position: 'absolute',
      right: 160, top: 80,
      width: 420, height: 860,
      background: '#000',
      borderRadius: 52,
      padding: 12,
      boxShadow: '0 40px 100px rgba(0,0,0,0.7), 0 0 0 2px rgba(255,255,255,0.05)',
      opacity: app,
      transform: `translateY(${(1 - app) * 50}px) rotate(${(1 - app) * 4}deg)`,
    }}>
      <div style={{
        width: '100%', height: '100%',
        borderRadius: 42,
        background: OP_COLORS.bg,
        overflow: 'hidden',
        position: 'relative',
      }}>
        {/* Notch */}
        <div style={{
          position: 'absolute', top: 12, left: '50%',
          transform: 'translateX(-50%)',
          width: 120, height: 30, borderRadius: 20,
          background: '#000',
          zIndex: 10,
        }} />

        {/* Status bar */}
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          padding: '14px 30px', fontSize: 14, fontFamily: SANS, fontWeight: 600,
          color: OP_COLORS.text,
        }}>
          <span>9:41</span>
          <span style={{ fontFamily: MONO, opacity: 0.8 }}>●●●●</span>
        </div>

        {/* App header */}
        <div style={{
          padding: '10px 22px 12px',
          borderBottom: `1px solid ${OP_COLORS.border}`,
        }}>
          <div style={{ fontSize: 12, color: OP_COLORS.textMute, fontFamily: MONO, letterSpacing: '0.1em' }}>
            PARTE DIARIO · mié 15/04
          </div>
          <div style={{ fontSize: 20, fontWeight: 700, color: OP_COLORS.text, marginTop: 2 }}>
            Av. San Martín 1250
          </div>
          <div style={{
            display: 'inline-block', marginTop: 8,
            fontSize: 11, fontWeight: 600,
            padding: '3px 9px', borderRadius: 999,
            background: `${OP_COLORS.amber}22`, color: OP_COLORS.amber,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>BORRADOR</div>
        </div>

        {/* Form fields — fill in over time */}
        <div style={{ padding: '14px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Field
            label="Descripción del trabajo"
            value={buildText(localTime, [
              { t: 1.6, chars: 'Avance de armado de losas en sector norte. ' },
              { t: 2.3, chars: 'Se completó el hormigonado de la columna C4.' },
            ])}
            localTime={localTime}
            showMic={localTime < 2.5}
          />
          <div style={{ display: 'flex', gap: 10 }}>
            <Field small label="Inicio" value={localTime > 2.6 ? '07:30' : ''} />
            <Field small label="Fin" value={localTime > 2.8 ? '16:30' : ''} />
          </div>

          {/* Asistencia */}
          <div style={{ marginTop: 4 }}>
            <div style={{
              fontSize: 10, fontWeight: 600, color: OP_COLORS.textMute,
              letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 8,
            }}>ASISTENCIA</div>
            {['M. Ruiz', 'J. Gómez', 'A. López', 'D. Ponce'].map((n, i) => {
              const checkAt = 3.0 + i * 0.15;
              const checked = localTime > checkAt;
              const flashT = clamp((localTime - checkAt) / 0.3, 0, 1);
              return (
                <div key={n} style={{
                  display: 'flex', alignItems: 'center',
                  padding: '10px 12px', marginBottom: 6,
                  border: `1px solid ${checked ? OP_COLORS.green : OP_COLORS.border}`,
                  background: checked ? `${OP_COLORS.green}14` : OP_COLORS.surface,
                  borderRadius: 10,
                  transition: 'background 0.2s',
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 6,
                    border: `2px solid ${checked ? OP_COLORS.green : OP_COLORS.border2}`,
                    background: checked ? OP_COLORS.green : 'transparent',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    marginRight: 10,
                    transform: checked ? `scale(${1 + (1 - flashT) * 0.3})` : 'scale(1)',
                  }}>
                    {checked && <span style={{ color: '#fff', fontSize: 14, fontWeight: 700 }}>✓</span>}
                  </div>
                  <span style={{ color: OP_COLORS.text, fontFamily: SANS, fontSize: 14, fontWeight: 500 }}>{n}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Enviar button — glows at end */}
        <div style={{
          position: 'absolute', left: 22, right: 22, bottom: 28,
        }}>
          <div style={{
            padding: '14px',
            background: localTime > 3.9 ? OP_COLORS.green : OP_COLORS.surface2,
            color: '#fff',
            borderRadius: 12,
            textAlign: 'center',
            fontFamily: SANS, fontWeight: 700, fontSize: 15,
            boxShadow: localTime > 3.9 ? `0 0 0 6px ${OP_COLORS.green}33` : 'none',
            transition: 'all 0.3s',
          }}>
            Enviar a gerencia
          </div>
        </div>
      </div>
    </div>
  );
}

// Builds typed text: chars appear progressively
function buildText(localTime, chunks) {
  let out = '';
  for (const c of chunks) {
    if (localTime < c.t) break;
    const elapsed = localTime - c.t;
    const charsToShow = Math.floor(elapsed * 55);
    out += c.chars.slice(0, charsToShow);
  }
  return out;
}

function Field({ label, value, small, localTime, showMic }) {
  return (
    <div>
      <div style={{
        fontSize: 10, fontWeight: 600, color: OP_COLORS.textMute,
        letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 6,
      }}>{label}</div>
      <div style={{
        position: 'relative',
        padding: small ? '10px 12px' : '12px 14px',
        background: OP_COLORS.surface,
        border: `1px solid ${OP_COLORS.border}`,
        borderRadius: 10,
        color: OP_COLORS.text, fontFamily: SANS,
        fontSize: small ? 15 : 14,
        minHeight: small ? 'auto' : 60,
        fontWeight: small ? 600 : 400,
        lineHeight: 1.45,
      }}>
        {value || <span style={{ color: OP_COLORS.textMute, opacity: 0.5 }}>—</span>}
        {showMic && (
          <div style={{
            position: 'absolute', right: 10, top: 10,
            width: 28, height: 28, borderRadius: '50%',
            background: OP_COLORS.red,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: `0 0 0 ${3 + Math.sin(Date.now() / 150) * 3}px ${OP_COLORS.red}55`,
          }}>
            <span style={{ color: '#fff', fontSize: 13 }}>🎙</span>
          </div>
        )}
      </div>
    </div>
  );
}

// Voice wave indicator on the left
function VoiceIndicator({ localTime }) {
  const active = localTime > 1.3 && localTime < 2.6;
  if (!active) return null;
  const t = localTime - 1.3;
  return (
    <div style={{
      position: 'absolute',
      right: 620, top: 280,
      display: 'flex', alignItems: 'center', gap: 14,
      fontFamily: MONO, fontSize: 12, color: OP_COLORS.greenLight,
      letterSpacing: '0.1em', textTransform: 'uppercase',
      pointerEvents: 'none',
    }}>
      <div style={{ display: 'flex', gap: 3, alignItems: 'center' }}>
        {Array.from({ length: 7 }).map((_, i) => {
          const h = 10 + Math.abs(Math.sin((t + i * 0.2) * 6)) * 26;
          return (
            <div key={i} style={{
              width: 3, height: h,
              background: OP_COLORS.greenLight,
              borderRadius: 2,
            }} />
          );
        })}
      </div>
      <span>● grabando</span>
    </div>
  );
}

Object.assign(window, { SceneParteDiario });
