// scenes/act2-taxes.jsx — Act 2: Cómo funciona el módulo Taxes (~38s)
//
// MERGE: case creation + intake doc-drop + send to client + intake signature
//
// Sub-timeline (act-local · Act 2 starts at global 10.25):
//  0.0-23.0   CasoSub      Case creation flow (4 modals) → contract sent + WhatsApp + sign (phone central, engine)
// 23.0-30.5   IntakeSub    Office returns → intake doc-drop (W-2, 1099, ID, 1095-A) → Sophia fills → detect 1099-K
// 30.5-34.0   RevisarSub   "Paso 5 de 6: Revisar y Firmar" page → click "Enviar al cliente para firmar remoto"
// 34.0-38.0   PostIntakeSub Background faded (phone takes over with intake firma, engine)

// Cinema-style value callouts — spanglish, explicativo, sin overlapping
// 2026-05-17 v2: "Caso + Contrato + WhatsApp" duration extended 3.5—9s so it
// stays visible during the whole phone moment 1 (contrato delivery + sign +
// confirmation). Post-moment-1 callouts shifted +5s to match new sub-scene
// schedule (intake doc-drop now starts at act-local 32 instead of 27).
const ACT2_CALLOUTS = [
  { appearAt: 3.0,  duration: 3.2,  icon: '✨', tKey: 'extraccion_ai' },
  { appearAt: 8.2,  duration: 3.4,  icon: '🎯', tKey: 'prefill_auto' },
  { appearAt: 20.5, duration: 12.5, icon: '⚡', tKey: 'caso_contrato_whatsapp' },
  { appearAt: 33.0, duration: 4.0,  icon: '📋', tKey: 'cero_recaptura' },
  { appearAt: 37.5, duration: 3.5,  icon: '🔍', tKey: 'deteccion_proactiva' },
  { appearAt: 41.5, duration: 5.0,  icon: '📱', tKey: 'esign_act' },
];

function Act2Taxes() {
  const { localTime, duration } = useSprite();
  const { time } = useTimeline();
  const actStart = time - localTime;

  return (
    <>
      {/* Sub A — Case creation (0-32.5) — stays as backdrop during phone moment 1 */}
      {localTime < 32.5 && <CasoSub localTime={localTime} />}

      {/* Sub B — Intake doc-drop (32-41) — 9s, was 8s (+1s for Sophia detection breathing) */}
      {localTime >= 32 && localTime < 41 && <IntakeSub localTime={localTime - 32} />}

      {/* Sub C — Revisar y Firmar (40.5-46.5) — 6s, was 5s (+1s shift, +1s extension) */}
      {localTime >= 40.5 && localTime < 46.5 && <RevisarSub localTime={localTime - 40.5} />}

      {/* Sub D — Post-intake (46+), background only, phone is engine-controlled */}
      {localTime >= 46 && <PostIntakeSub localTime={localTime - 46} />}

      {/* Value callouts — cinema-style benefit narration */}
      <CalloutsTrack localTime={localTime} callouts={ACT2_CALLOUTS} />

      {/* Cursor track for the entire act (act-local times via LocalCursorTrack) */}
      <LocalCursorTrack actStart={actStart} track={[
        { t: 0.0,   x: 640,  y: 680 },
        { t: 2.0,   x: 640,  y: 680 },
        { t: 2.35,  x: 1175, y: 360 },
        { t: 2.55,  x: 1175, y: 360, click: true },
        { t: 2.8,   x: 1175, y: 360 },
        { t: 4.8,   x: 1175, y: 360 },
        { t: 5.05,  x: 786,  y: 545 },
        { t: 5.4,   x: 786,  y: 545, click: true },
        { t: 5.6,   x: 786,  y: 545 },
        { t: 12.5,  x: 786,  y: 545 },
        { t: 12.85, x: 786,  y: 605 },
        { t: 13.05, x: 786,  y: 605, click: true },
        { t: 13.3,  x: 786,  y: 605 },
        { t: 14.6,  x: 786,  y: 605 },
        { t: 14.9,  x: 492,  y: 295 },
        { t: 15.1,  x: 492,  y: 295, click: true },
        { t: 15.35, x: 492,  y: 295 },
        { t: 19.3,  x: 492,  y: 295 },
        { t: 19.7,  x: 800,  y: 555 },
        { t: 20.0,  x: 800,  y: 555, click: true },
        { t: 20.25, x: 800,  y: 555 },
        { t: 21.0,  x: 1320, y: 720 },
        { t: 27.5,  x: 1320, y: 720 },
        { t: 28.5,  x: 640,  y: 600 },
        { t: 34.0,  x: 640,  y: 600 },
        { t: 34.2,  x: 1180, y: 165, click: true },
        { t: 34.7,  x: 1180, y: 165 },
        { t: 36.5,  x: 1180, y: 165 },
        { t: 37.2,  x: 850,  y: 590 },
        { t: 37.7,  x: 850,  y: 590, click: true },
        { t: 37.95, x: 850,  y: 590 },
        { t: 38.5,  x: 1320, y: 720 },
      ]} />
    </>
  );
}

// ═════════════════════════════════════════════════════════════════════
// SUB A — Case creation (0-23.5)
// ═════════════════════════════════════════════════════════════════════
function CasoSub({ localTime }) {
  // ── Stage flags — each modal +1s hold for slower pacing ──
  const showModal1 = localTime >= 2.5 && localTime < 8.3;
  const showModal2 = localTime >= 7.9 && localTime < 13.2;
  const showModal3 = localTime >= 13.2 && localTime < 16.7;
  const showModal4 = localTime >= 16.3 && localTime < 20.3;
  const showToast = localTime >= 20.3;

  // Injected TOMÁS case (animates in after modal 4 closes)
  const injectedProgress = clamp((localTime - 20.5) / 0.55, 0, 1);
  const injectedCase = injectedProgress > 0 ? { progress: injectedProgress } : null;

  // ── Modal 1 ──
  const modal1Progress = clamp((localTime - 2.5) / 0.3, 0, 1) *
                         (localTime < 8.0 ? 1 : Math.max(0, 1 - (localTime - 8.0) / 0.3));
  const licenseFly = clamp((localTime - 2.9) / 1.9, 0, 1);
  const analyzing = localTime >= 5.5 && localTime < 6.8;
  const analyzerHover = localTime >= 4.95 && localTime < 5.35;
  const analyzerPressed = localTime >= 5.35 && localTime < 5.55;

  // ── Modal 2 ──
  const modal2Progress = clamp((localTime - 7.9) / 0.4, 0, 1) *
                         (localTime < 12.9 ? 1 : Math.max(0, 1 - (localTime - 12.9) / 0.3));
  const fills = {
    nombre:     clamp((localTime - 8.4) / 0.45, 0, 1),
    direccion:  clamp((localTime - 8.7) / 0.5, 0, 1),
    ciudad:     clamp((localTime - 9.0) / 0.4, 0, 1),
    estado:     clamp((localTime - 9.05) / 0.3, 0, 1),
    zip:        clamp((localTime - 9.1) / 0.35, 0, 1),
    dob:        clamp((localTime - 9.4) / 0.4, 0, 1),
    email:      clamp((localTime - 9.9) / 0.7, 0, 1),
    telefono:   clamp((localTime - 10.4) / 0.55, 0, 1),
    ssn:        clamp((localTime - 10.9) / 0.4, 0, 1),
  };
  const crearHover = localTime >= 12.55 && localTime < 12.95;
  const crearPressed = localTime >= 12.95 && localTime < 13.15;

  // ── Modal 3 ──
  const modal3Progress = clamp((localTime - 13.2) / 0.4, 0, 1) *
                         (localTime < 16.4 ? 1 : Math.max(0, 1 - (localTime - 16.4) / 0.3));
  const taxesHover = localTime >= 14.8 && localTime < 15.3;
  const taxesSelected = localTime >= 15.05;
  const taxesPressed = localTime >= 15.05 && localTime < 15.25;

  // ── Modal 4 ──
  const modal4Progress = clamp((localTime - 16.3) / 0.4, 0, 1) *
                         (localTime < 20.0 ? 1 : Math.max(0, 1 - (localTime - 20.0) / 0.3));
  const continuarHover = localTime >= 19.55 && localTime < 19.95;
  const continuarPressed = localTime >= 19.95 && localTime < 20.15;

  // ── Dashboard +Nuevo cliente button hover/click ──
  const newClientHover = localTime >= 2.35 && localTime < 2.6;
  const newClientPressed = localTime >= 2.55 && localTime < 2.75;

  // ── Fade out at end (last 0.5s before intake takes over) ──
  // CasoSub now fades 31.5—32.5 (was 26.5—27.5) since intake shifted +5s
  const subFadeOut = localTime > 31.5 ? Math.max(0, 1 - (localTime - 31.5) / 1.0) : 1;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      opacity: subFadeOut,
      transition: 'opacity 200ms',
    }}>
      {/* Dashboard always visible behind */}
      <DashboardHome
        greetingProgress={clamp(localTime / 0.6, 0, 1)}
        newClientHover={newClientHover}
        newClientPressed={newClientPressed}
        injectedCase={injectedCase}
      />

      {/* Success toast */}
      {showToast && <CasoCreadoToast localTime={localTime} appearAt={16.3} />}

      {/* Modal backdrop */}
      {(showModal1 || showModal2 || showModal3 || showModal4) && (
        <ModalBackdrop progress={Math.min(1, Math.max(modal1Progress, modal2Progress, modal3Progress, modal4Progress))} />
      )}

      {showModal1 && (
        <NuevoClienteModal
          progress={modal1Progress}
          licenseFly={licenseFly}
          analyzing={analyzing}
          btnHover={analyzerHover}
          btnPressed={analyzerPressed}
        />
      )}
      {showModal2 && (
        <ConfirmaDatosModal
          progress={modal2Progress}
          fills={fills}
          btnHover={crearHover}
          btnPressed={crearPressed}
        />
      )}
      {showModal3 && (
        <NuevoCasoModal
          progress={modal3Progress}
          hoveredKey={taxesHover ? 'taxes' : null}
          selectedKey={taxesSelected ? 'taxes' : null}
          cardPressed={taxesPressed}
        />
      )}
      {showModal4 && (
        <CasoTaxesModal
          progress={modal4Progress}
          year="2026"
          declType="original"
          origin="cero"
          conjunta={false}
          btnHover={continuarHover}
          btnPressed={continuarPressed}
        />
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════
// SUB B — Intake doc-drop (now 9s, was 8s)
// ═════════════════════════════════════════════════════════════════════
function IntakeSub({ localTime }) {
  // Fade in 0-0.5
  const inOpacity = Math.min(1, localTime / 0.5);
  // Fade out at end (last 1s — extended so Sophia detection card lingers)
  const outOpacity = localTime > 8.0 ? Math.max(0, 1 - (localTime - 8.0) / 1.0) : 1;

  // Docs schedule (start later — case creation already happened)
  const docSchedule = [
    { id: 'w2',    flyStart: 0.6, flyDur: 0.5 },
    { id: '1099',  flyStart: 1.2, flyDur: 0.5 },
    { id: 'id',    flyStart: 1.8, flyDur: 0.5 },
    { id: '1095a', flyStart: 2.4, flyDur: 0.5 },
  ];

  const docs = TAXES_DOCS.map(d => {
    const sched = docSchedule.find(s => s.id === d.id);
    const fly = clamp((localTime - sched.flyStart) / sched.flyDur, 0, 1);
    const settled = fly >= 1;
    return { ...d, fly, settled };
  });

  // Field fills:
  // s1.* fields are ALREADY filled from case creation → fill = 1 from start
  // Other fields fill from docs (3.5-5.5)
  const fieldFills = {
    's1.name':    1,
    's1.ssn':     1,
    's1.marital': 1,
    's1.addr':    1,
    's2.employer': clamp((localTime - 3.5) / 0.35, 0, 1),
    's2.gross':    clamp((localTime - 3.7) / 0.32, 0, 1),
    's2.fed':      clamp((localTime - 3.9) / 0.32, 0, 1),
    's3.payer':    clamp((localTime - 4.15) / 0.32, 0, 1),
    's3.nec':      clamp((localTime - 4.35) / 0.32, 0, 1),
    's4.mkt':      clamp((localTime - 4.6) / 0.30, 0, 1),
    's4.aptc':     clamp((localTime - 4.80) / 0.32, 0, 1),
  };

  // Doc checkboxes
  const docChecks = {
    w2:     localTime >= 5.4,
    '1099': localTime >= 5.55,
    id:     localTime >= 5.7,
    '1095a':localTime >= 5.85,
  };

  // Case status phase
  let caseStatus = 'received';
  if (localTime >= 2.9 && localTime < 3.5) caseStatus = 'analyzing';
  else if (localTime >= 3.5 && localTime < 6.0) caseStatus = 'extracting';
  else if (localTime >= 6.0) caseStatus = 'ready';

  // 1099-K detection card 6.0+
  const showDetection = localTime >= 6.0;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      opacity: Math.min(inOpacity, outOpacity),
    }}>
      <TaxesIntake
        docs={docs}
        fieldFills={fieldFills}
        docChecks={docChecks}
        caseStatus={caseStatus}
        showDetection={showDetection}
      />
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════
// SUB C — Revisar y Firmar (now 0-6, was 0-4) — gives reader 1s more to read
// ═════════════════════════════════════════════════════════════════════
function RevisarSub({ localTime }) {
  const inOpacity = Math.min(1, localTime / 0.4);
  const outOpacity = localTime > 4.5 ? Math.max(0, 1 - (localTime - 4.5) / 0.8) : 1;

  // Button click shifted +1s — gives the reader time to take in the "Paso 5 de 6" page
  const btnHover = localTime >= 3.7 && localTime < 4.15;
  const btnPressed = localTime >= 4.15 && localTime < 4.35;

  return (
    <RevisarFirmarPage
      progress={Math.min(inOpacity, outOpacity)}
      btnHover={btnHover}
      btnPressed={btnPressed}
    />
  );
}

// ═════════════════════════════════════════════════════════════════════
// SUB D — Post-intake (phone takes over)
// ═════════════════════════════════════════════════════════════════════
function PostIntakeSub({ localTime }) {
  // Just a faded dashboard / status — the phone (engine-controlled) is the focus
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: '#fafafa',
      opacity: 0.95,
    }}>
      <AppHeader moduleName="Taxes" moduleAccent="#007AFF" moduleIcon="🧮" />
      <div style={{
        position: 'absolute',
        top: '40%', left: '50%',
        transform: 'translate(-50%, -50%)',
        textAlign: 'center',
        color: '#a1a1a6',
        fontSize: 13,
        letterSpacing: -0.005,
      }}>
        <div style={{
          fontFamily: 'ui-monospace, monospace',
          fontSize: 10.5,
          letterSpacing: 0.14,
          textTransform: 'uppercase',
          marginBottom: 6,
          color: '#007AFF',
          fontWeight: 600,
        }}>Esperando firma</div>
        <div>Link enviado · TOMÁS está revisando en su teléfono…</div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════
// HELPER: Toast — Caso creado + contrato enviado
// ═════════════════════════════════════════════════════════════════════
function CasoCreadoToast({ localTime, appearAt }) {
  const t = localTime - appearAt;
  const p = clamp(t / 0.5, 0, 1);
  const e = Easing.easeOutCubic(p);
  return (
    <div style={{
      position: 'absolute',
      top: 76,
      right: 24,
      width: 360,
      background: '#fff',
      border: '1px solid rgba(52, 199, 89, 0.4)',
      borderRadius: 14,
      boxShadow: '0 18px 40px -16px rgba(52, 199, 89, 0.35), 0 8px 16px -8px rgba(0,0,0,0.15)',
      padding: '14px 16px',
      zIndex: 26,
      opacity: e,
      transform: `translateY(${(1 - e) * -12}px)`,
      willChange: 'transform, opacity',
    }}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        marginBottom: 8,
      }}>
        <div style={{
          width: 28, height: 28,
          borderRadius: '50%',
          background: '#34C759',
          color: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 14,
          fontWeight: 700,
          flexShrink: 0,
          boxShadow: '0 2px 8px rgba(52, 199, 89, 0.4)',
        }}>✓</div>
        <div style={{ flex: 1 }}>
          <div style={{
            fontSize: 13,
            fontWeight: 600,
            color: '#1d1d1f',
            letterSpacing: -0.005,
          }}>Caso Taxes 2026 creado</div>
          <div style={{
            fontSize: 10.5,
            color: '#6e6e73',
            fontFamily: 'ui-monospace, monospace',
            letterSpacing: 0.02,
            marginTop: 1,
          }}>TOMÁS SMITH · TAX_2026_001</div>
        </div>
      </div>
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        gap: 4,
        fontSize: 11,
        color: '#52525b',
        letterSpacing: -0.005,
        paddingLeft: 38,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ color: '#007AFF' }}>✉</span>
          Contrato enviado por <b style={{ color: '#1d1d1f', fontWeight: 600 }}>email</b>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ color: '#25D366' }}>●</span>
          <b style={{ color: '#1d1d1f', fontWeight: 600 }}>WhatsApp</b> al cliente notificado
        </div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════
// HELPER: New TOMÁS row — pushes existing rows down
// ═════════════════════════════════════════════════════════════════════
function NewCaseRow({ localTime, appearAt }) {
  const t = localTime - appearAt;
  const p = clamp(t / 0.5, 0, 1);
  const e = Easing.easeOutCubic(p);

  // First row in casos table position: top 437 (sidebar 196 + header 54 + padding 18 + hero 145 + gap 14 + stats 110 + gap 14 + casos title 46 + table header 36)
  return (
    <>
      {/* Spacer that pushes existing rows down */}
      <div style={{
        position: 'absolute',
        top: 437,
        left: 224,
        right: 28,
        height: 46 * e,
        zIndex: 3,
        background: '#fff',
        borderBottom: '1px solid #f5f5f7',
      }} />
      {/* TOMÁS new row inserts at top */}
      <div style={{
        position: 'absolute',
        top: 437,
        left: 224,
        right: 28,
        height: 46,
        background: 'rgba(52, 199, 89, 0.08)',
        border: '1.5px solid rgba(52, 199, 89, 0.4)',
        borderRadius: 8,
        padding: '0 18px',
        display: 'grid',
        gridTemplateColumns: '2fr 1fr 1.4fr 1fr 1fr 70px',
        gap: 12,
        alignItems: 'center',
        fontSize: 12.5,
        letterSpacing: -0.005,
        zIndex: 4,
        opacity: e,
        transform: `translateX(${(1 - e) * -16}px)`,
        boxShadow: `0 0 ${(1 - Math.abs(p - 0.5) * 2) * 24}px rgba(52, 199, 89, ${(1 - Math.abs(p - 0.5) * 2) * 0.5})`,
        willChange: 'transform, opacity, box-shadow',
      }}>
        <span style={{
          fontWeight: 600,
          color: '#1d1d1f',
          display: 'inline-flex',
          alignItems: 'center',
          gap: 6,
        }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#34C759' }} />
          TOMÁS SMITH
        </span>
        <span style={{ color: '#a1a1a6' }}>—</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          Amelia
          <span style={{
            fontSize: 8.5,
            color: '#FF9500',
            background: '#fff5e6',
            border: '1px solid #ffd9a3',
            padding: '1px 5px',
            borderRadius: 3,
            fontWeight: 600,
            letterSpacing: 0.04,
          }}>OWNER</span>
        </span>
        <span style={{ color: '#6e6e73', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>2026-05-16</span>
        <span style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 4,
          padding: '3px 9px',
          borderRadius: 999,
          fontSize: 10.5,
          color: '#7c3aed',
          background: 'rgba(139, 92, 246, 0.10)',
          border: '1px solid rgba(139, 92, 246, 0.30)',
          fontWeight: 500,
          alignSelf: 'center',
          justifySelf: 'start',
        }}>● Contrato enviado</span>
        <a style={{
          color: '#007AFF',
          fontSize: 12,
          textAlign: 'right',
          fontWeight: 500,
        }}>Ver</a>
      </div>
    </>
  );
}

Object.assign(window, { Act2Taxes, CasoCreadoToast, NewCaseRow });
