// mockups/paquete-flow.jsx — Pantallas del Acto 4 · Paquete USCIS.
//
// Exports on window:
//   HubFiveButtons       (escena 12)
//   FormaI130            (escena 13)
//   EvidenciaDrop        (escena 14)
//   OrganizarDrag        (escena 15)
//   CoverLetterEditor    (escena 16)
//   PrintOutputs         (escena 17)

const HUB_BUTTONS = [
  { key: 'formas',    label: 'Formas prellenadas', short: 'Formas',     icon: '📄', color: '#8b5cf6', sub: '4 formas auto-llenadas' },
  { key: 'evidencia', label: 'Evidencia',          short: 'Evidencia',  icon: '📎', color: '#FF9500', sub: '0/6 documentos' },
  { key: 'organizar', label: 'Organizar paquete',  short: 'Organizar',  icon: '📦', color: '#34C759', sub: '7 items en orden' },
  { key: 'cover',     label: 'Cover Letter',       short: 'Cover',      icon: '📝', color: '#007AFF', sub: 'Editable' },
  { key: 'imprimir',  label: 'Imprimir',           short: 'Imprimir',   icon: '🖨️', color: '#1d1d1f', sub: 'Sobre USCIS-ready' },
];

function PaqueteShell({ children }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const moduleName = (i18n.modules && i18n.modules.migracion) || 'Migración';
  const crumbs = lang === 'en'
    ? ['Cases', 'CARLA', 'Package', 'USCIS documents']
    : ['Casos',  'CARLA', 'Paquete', 'Documentos USCIS'];
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#f5f5f7',
    }}>
      <AppHeader
        moduleName={moduleName}
        moduleAccent="#FF9500"
        moduleIcon="🌎"
        breadcrumbs={crumbs}
      />
      {children}
    </div>
  );
}

// ── Hub 5 botones ─────────────────────────────────────────────────────
function HubFiveButtons({ activeButton = null, clickedButton = null }) {
  // Pull translated labels + subs from i18n.paquete.hub. The HUB_BUTTONS
  // constant still holds the styling (color, icon, key) — labels are overlaid
  // from i18n so the toggle ES/EN swaps them live.
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const hub = (i18n.paquete && i18n.paquete.hub) || {};
  const buttons = HUB_BUTTONS.map(b => {
    switch (b.key) {
      case 'formas':    return { ...b, label: hub.formas_label    || b.label, sub: hub.formas_sub    || b.sub };
      case 'evidencia': return { ...b, label: hub.evidencia_label || b.label, sub: hub.evidencia_sub || b.sub };
      case 'organizar': return { ...b, label: hub.organizar_label || b.label, sub: hub.organizar_sub || b.sub };
      case 'cover':     return { ...b, label: hub.cover_label     || b.label, sub: hub.cover_sub     || b.sub };
      case 'imprimir':  return { ...b, label: hub.imprimir_label  || b.label, sub: hub.imprimir_sub  || b.sub };
      default:          return b;
    }
  });
  return (
    <PaqueteShell>
      <div style={{ position: 'absolute', left: 22, right: 280, top: 70 }}>
        <div style={{
          fontSize: 11, fontFamily: 'ui-monospace, monospace',
          color: '#9a3412', letterSpacing: 0.12,
          textTransform: 'uppercase', fontWeight: 600,
          marginBottom: 4,
        }}>📦 Paquete · CARLA A. VERA RODRÍGUEZ · I-130 + I-130A + I-485 + I-864</div>
        <div style={{
          fontSize: 22, fontWeight: 600, color: '#1d1d1f',
          letterSpacing: -0.025, marginBottom: 4,
        }}>Documentos del paquete USCIS</div>
        <div style={{
          fontSize: 13, color: '#6e6e73',
          letterSpacing: -0.005, lineHeight: 1.45,
          marginBottom: 18,
        }}>
          Flujo en 5 pasos: revisar formas → cargar evidencia → organizar el sobre → generar cover letter → imprimir el paquete.
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(5, 1fr)',
          gap: 12,
          marginBottom: 22,
        }}>
          {buttons.map((b, i) => {
            const isHover = activeButton === b.key;
            const isClicked = clickedButton === b.key;
            return (
              <div key={b.key} style={{
                padding: '20px 18px 18px',
                background: '#fff',
                border: `1.5px solid ${isHover || isClicked ? b.color : '#e8e8ed'}`,
                borderRadius: 14,
                cursor: 'pointer',
                transform: isClicked ? 'scale(0.97)' : (isHover ? 'translateY(-2px)' : 'none'),
                boxShadow: isHover
                  ? `0 12px 28px ${b.color}33`
                  : '0 1px 3px rgba(0,0,0,0.04)',
                transition: 'all 200ms',
              }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  background: `linear-gradient(135deg, ${b.color}, ${b.color}cc)`,
                  color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 22,
                  marginBottom: 12,
                  boxShadow: `0 4px 12px ${b.color}55`,
                }}>{b.icon}</div>
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 6,
                  marginBottom: 4,
                }}>
                  <div style={{
                    fontFamily: 'ui-monospace, monospace',
                    fontSize: 10,
                    color: '#a1a1a6',
                    fontWeight: 700,
                  }}>0{i + 1}</div>
                </div>
                <div style={{
                  fontSize: 13.5, fontWeight: 600,
                  color: '#1d1d1f', letterSpacing: -0.005,
                  marginBottom: 4, lineHeight: 1.2,
                }}>{b.label}</div>
                <div style={{
                  fontSize: 11, color: '#6e6e73',
                  letterSpacing: -0.005,
                }}>{b.sub}</div>
              </div>
            );
          })}
        </div>

        {/* Status row */}
        <div style={{
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 12,
          padding: '14px 18px',
          display: 'flex',
          alignItems: 'center',
          gap: 14,
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            fontSize: 12, color: '#6e6e73',
          }}>
            <span style={{ fontSize: 14 }}>📬</span>
            <span><strong style={{ color: '#1d1d1f' }}>USCIS Lockbox:</strong> Chicago IL · P.O. Box 805887</span>
          </div>
          <div style={{ flex: 1 }} />
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '4px 10px',
            background: '#dcfce7',
            border: '1px solid #86efac',
            borderRadius: 999,
            fontSize: 11, fontWeight: 600,
            color: '#15803d',
          }}>
            <span>✓</span> Listo para empezar
          </div>
        </div>
      </div>
    </PaqueteShell>
  );
}

// ── I-130 PDF auto-fill ───────────────────────────────────────────────
const I130_FIELDS = [
  { x: 0.08, y: 0.16, w: 0.28, label: 'Family Name (Last)',  value: 'SMITH' },
  { x: 0.38, y: 0.16, w: 0.28, label: 'Given Name (First)',  value: 'TOMÁS' },
  { x: 0.68, y: 0.16, w: 0.24, label: 'Middle Name',         value: '—' },
  { x: 0.08, y: 0.24, w: 0.28, label: 'Date of Birth',       value: '05/12/1985' },
  { x: 0.38, y: 0.24, w: 0.28, label: 'Country of Birth',    value: 'United States' },
  { x: 0.68, y: 0.24, w: 0.24, label: 'A-Number',            value: 'N/A' },
  { x: 0.08, y: 0.32, w: 0.40, label: 'Current Mailing Address', value: '8810 Commodity Cir' },
  { x: 0.50, y: 0.32, w: 0.20, label: 'City',                value: 'Orlando' },
  { x: 0.72, y: 0.32, w: 0.10, label: 'State',               value: 'FL' },
  { x: 0.84, y: 0.32, w: 0.10, label: 'ZIP',                 value: '32819' },
  { x: 0.08, y: 0.40, w: 0.40, label: 'Email',               value: 'tomas.smith@gmail.com' },
  { x: 0.50, y: 0.40, w: 0.30, label: 'Daytime Phone',       value: '(407) 555-0142' },
  { x: 0.08, y: 0.48, w: 0.40, label: 'Beneficiary · Family Name', value: 'VERA RODRÍGUEZ' },
  { x: 0.50, y: 0.48, w: 0.30, label: 'Beneficiary · Given Name',  value: 'CARLA A.' },
  { x: 0.08, y: 0.56, w: 0.28, label: 'Beneficiary · DOB',  value: '03/22/1988' },
  { x: 0.38, y: 0.56, w: 0.28, label: 'Country of Birth',   value: 'Venezuela' },
  { x: 0.08, y: 0.64, w: 0.40, label: 'Relationship',       value: 'Spouse (Wife)' },
  { x: 0.50, y: 0.64, w: 0.40, label: 'Date of Marriage',   value: '11/22/2019' },
];

function FormaI130({ fillProgress = 0, syncedCount = 0 }) {
  const lang = useTimeline().lang || 'es';
  const FORM_W = 660;
  const FORM_H = 460;

  return (
    <PaqueteShell>
      <div style={{ position: 'absolute', left: 22, right: 280, top: 70 }}>
        {/* Banner */}
        <div style={{
          padding: '10px 14px',
          background: 'linear-gradient(90deg, #f5f3ff, #fff)',
          border: '1px solid #ddd6fe',
          borderRadius: 10,
          marginBottom: 14,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          fontSize: 12,
        }}>
          <span style={{ fontSize: 14 }}>📄</span>
          <span style={{ color: '#5b21b6', letterSpacing: -0.005 }}>
            {lang === 'en'
              ? <><strong>Step 1 — Pre-filled USCIS forms.</strong> Sophia filled the fields with data inherited from Taxes + Intake. Mark <strong>Sync ✓</strong> on review. Wet signature required </>
              : <><strong>Paso 1 — Formas USCIS prellenadas.</strong> Sophia rellenó los campos con datos heredados de Taxes + Intake. Marca <strong>Sync ✓</strong> al revisar. Firma a tinta requerida </>
            }al imprimir.
          </span>
        </div>

        {/* Toolbar */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          marginBottom: 12,
        }}>
          <div style={{
            background: '#fff', border: '1px solid #e8e8ed',
            padding: '4px 10px', borderRadius: 8,
            fontSize: 11, fontFamily: 'ui-monospace, monospace',
            color: '#1d1d1f', display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ color: '#8b5cf6', fontWeight: 700 }}>I-130</span>
            <span style={{ color: '#a1a1a6' }}>·</span>
            <span style={{ color: '#6e6e73' }}>Petition for Alien Relative</span>
          </div>
          <div style={{
            background: '#fff', border: '1px solid #e8e8ed',
            padding: '4px 8px', borderRadius: 8,
            fontSize: 11, fontFamily: 'ui-monospace, monospace',
            color: '#6e6e73',
          }}>Zoom 140%</div>
          <div style={{
            background: '#fff', border: '1px solid #e8e8ed',
            padding: '4px 8px', borderRadius: 8,
            fontSize: 11, color: '#1d1d1f',
          }}>Llenar N/A</div>
          <div style={{ flex: 1 }} />
          <div style={{
            background: syncedCount >= I130_FIELDS.length ? '#dcfce7' : '#fef3c7',
            border: syncedCount >= I130_FIELDS.length ? '1px solid #86efac' : '1px solid #fcd34d',
            padding: '4px 10px',
            borderRadius: 999,
            fontSize: 11, fontWeight: 600,
            color: syncedCount >= I130_FIELDS.length ? '#15803d' : '#92400e',
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            ✓ Sync {syncedCount} / {I130_FIELDS.length}
          </div>
        </div>

        {/* Form preview frame */}
        <div style={{
          position: 'relative',
          width: '100%',
          height: 480,
          background: '#fff',
          borderRadius: 10,
          border: '1px solid #e8e8ed',
          boxShadow: '0 8px 28px rgba(0,0,0,0.08)',
          overflow: 'hidden',
        }}>
          {/* Page header — USCIS official */}
          <div style={{
            padding: '14px 28px 10px',
            borderBottom: '2px solid #1d1d1f',
            display: 'flex',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
          }}>
            <div>
              <div style={{
                fontSize: 9.5, fontFamily: 'ui-monospace, monospace',
                color: '#1d1d1f', letterSpacing: 0.08,
                textTransform: 'uppercase', fontWeight: 700,
              }}>U.S. Department of Homeland Security</div>
              <div style={{
                fontSize: 9, color: '#6e6e73', fontFamily: 'ui-monospace, monospace',
                letterSpacing: 0.04, marginBottom: 4,
              }}>U.S. Citizenship and Immigration Services</div>
              <div style={{
                fontSize: 16, fontWeight: 700, color: '#1d1d1f',
                letterSpacing: -0.02, marginTop: 2,
              }}>I-130 · Petition for Alien Relative</div>
            </div>
            <div style={{
              fontSize: 9, color: '#a1a1a6', fontFamily: 'ui-monospace, monospace',
              textAlign: 'right',
            }}>
              <div>OMB No. 1615-0012</div>
              <div>Expires 03/31/2027</div>
            </div>
          </div>

          {/* Form body — sections + fields */}
          <div style={{
            position: 'relative',
            padding: '14px 28px',
          }}>
            {/* Part labels */}
            <div style={{
              fontSize: 11, fontWeight: 700, color: '#1d1d1f',
              letterSpacing: -0.005, marginBottom: 8,
              padding: '4px 8px',
              background: '#e5e7eb',
              display: 'inline-block',
            }}>Part 1. Information About You (Petitioner)</div>

            {/* Fields */}
            <div style={{
              position: 'relative',
              width: '100%',
              height: 360,
            }}>
              {I130_FIELDS.map((f, i) => {
                const fieldStart = (i / I130_FIELDS.length) * 0.85;
                const fieldEnd = fieldStart + 0.18;
                const localP = clamp((fillProgress - fieldStart) / (fieldEnd - fieldStart), 0, 1);
                const showLen = Math.floor(f.value.length * localP);
                const visibleText = f.value.slice(0, showLen);
                const isComplete = localP >= 1;
                return (
                  <div key={i} style={{
                    position: 'absolute',
                    left: `${f.x * 100}%`,
                    top: `${(f.y - 0.08) * 100 * 1.4}%`,
                    width: `${f.w * 100}%`,
                    height: 28,
                  }}>
                    <div style={{
                      fontSize: 7,
                      color: '#6e6e73',
                      fontFamily: 'ui-monospace, monospace',
                      letterSpacing: 0.05,
                      marginBottom: 1,
                      textTransform: 'uppercase',
                    }}>{f.label}</div>
                    <div style={{
                      border: '1px solid #1d1d1f',
                      borderRadius: 0,
                      padding: '2px 4px',
                      fontSize: 9.5,
                      fontFamily: 'ui-monospace, monospace',
                      color: isComplete ? '#1d1d1f' : '#007AFF',
                      background: localP > 0 ? '#fff' : '#fafafa',
                      minHeight: 16,
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                    }}>
                      {visibleText}
                      {localP > 0 && localP < 1 && (
                        <span style={{
                          display: 'inline-block', width: 1, height: 10,
                          background: '#007AFF',
                          marginLeft: 1,
                          verticalAlign: 'middle',
                          animation: 'sol-caret 0.6s steps(1) infinite',
                        }} />
                      )}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Footer note */}
            <div style={{
              position: 'absolute',
              bottom: 8, left: 28, right: 28,
              fontSize: 8.5,
              fontFamily: 'ui-monospace, monospace',
              color: '#a1a1a6',
              display: 'flex',
              justifyContent: 'space-between',
            }}>
              <span>Form I-130 · Page 1 of 12</span>
              <span>Edition 04/01/2024</span>
            </div>
          </div>
        </div>
      </div>
    </PaqueteShell>
  );
}

// ── Evidencia drop zone ───────────────────────────────────────────────
const EVIDENCE_DOCS = [
  { id: 'passport_carla', name: 'passport_carla.pdf',        tag: 'ID',         heritage: false },
  { id: 'birth_carla',    name: 'birth_cert_carla.pdf',      tag: 'Vital',      heritage: false },
  { id: 'marriage',       name: 'marriage_cert.pdf',         tag: 'Bona fide',  heritage: false },
  { id: 'passport_tomas', name: 'passport_tomas.pdf',        tag: 'Sponsor',    heritage: false },
  { id: 'wedding',        name: 'wedding_photos.jpg',        tag: 'Bona fide',  heritage: false },
  { id: 'lease',          name: 'joint_lease.pdf',           tag: 'Cohab',      heritage: false },
  { id: 'tax_inherit',    name: 'tax_return_2025.pdf',       tag: 'I-864',      heritage: true },
];

// EvidenciaDrop — redesigned to match the real product UI (per JP feedback May 17):
//   • 5-tab navigation at top (Formas / Evidencia ACTIVE / Organizar / Cover / Imprimir)
//   • Sophia auto-clasifica banner with shimmer + sparkles
//   • Big neutral drop zone that shows folder icon + "Arrastra docs aquí" when empty;
//     the empty state fades out as docs arrive
//   • Right sidebar: CASO + PROGRESO (count-up + pulse at complete) + Sophia tips + +1 HEREDADO
function EvidenciaDrop({ docsProgress = [] }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const p = i18n.paquete || {};
  const total = EVIDENCE_DOCS.length;
  const settledCount = docsProgress.filter(p => p >= 1).length;
  const isComplete = settledCount === total;
  const heredadoSettled = (docsProgress[6] || 0) >= 1;
  const hasAnyDoc = docsProgress.some(p => p >= 0.25);
  const pct = (settledCount / total) * 100;

  const hub = p.hub || {};
  const TABS = [
    { color: '#8b5cf6', icon: '📄', label: hub.formas_label    || 'Formas prellenadas' },
    { color: '#FF9500', icon: '🔗', label: hub.evidencia_label || 'Evidencia',          active: true },
    { color: '#34C759', icon: '📦', label: hub.organizar_label || 'Organizar paquete' },
    { color: '#007AFF', icon: '📝', label: hub.cover_label     || 'Cover letter' },
    { color: '#1d1d1f', icon: '🖨', label: hub.imprimir_label  || 'Imprimir' },
  ];

  return (
    <PaqueteShell>
      {/* 5-tab navigation under AppHeader */}
      <div style={{
        position: 'absolute', left: 22, right: 22, top: 60,
        display: 'flex', gap: 10,
      }}>
        {TABS.map((tab, i) => (
          <div key={i} style={{
            flex: 1, height: 42, borderRadius: 22,
            background: tab.active ? tab.color : '#fff',
            border: tab.active ? 'none' : '1px solid #e8e8ed',
            color: tab.active ? '#fff' : tab.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            fontSize: 13, fontWeight: 600, letterSpacing: -0.005,
            boxShadow: tab.active ? `0 6px 18px ${tab.color}55` : '0 1px 3px rgba(0,0,0,0.04)',
          }}>
            <span style={{ fontSize: 14 }}>{tab.icon}</span>
            <span>{tab.label}</span>
          </div>
        ))}
      </div>

      {/* Sub-text */}
      <div style={{
        position: 'absolute', left: 22, right: 22, top: 110,
        fontSize: 12, color: '#86868b',
        letterSpacing: -0.005, fontStyle: 'italic',
      }}>
        {lang === 'en' ? 'The recommended step is highlighted in the breadcrumb above. You can jump between steps in any order — Sophia will alert you if something isn\u2019t ready.' : 'El paso recomendado se resalta en el breadcrumb arriba. Puedes saltar entre pasos en cualquier orden — Sophia te avisa si algo no está listo.'}
      </div>

      {/* Main layout: left (banner + drop + actions) | right sidebar 280w */}
      <div style={{
        position: 'absolute', left: 22, right: 22, top: 142, bottom: 16,
        display: 'flex', gap: 16,
      }}>
        {/* LEFT column */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
          {/* Sophia auto-clasifica banner — shimmer + sparkles (reuses sol-cross-fill-zoom CSS) */}
          <div className="sol-cross-fill-zoom" style={{
            position: 'relative',
            padding: '12px 16px',
            background: 'linear-gradient(90deg, #faf5ff, #fff)',
            border: '1.5px solid #ddd6fe',
            borderRadius: 12,
            display: 'flex',
            alignItems: 'flex-start',
            gap: 12,
            fontSize: 13,
            overflow: 'hidden',
            isolation: 'isolate',
            flexShrink: 0,
          }}>
            <span className="sol-cross-fill-shimmer" />
            <span className="sol-cross-fill-sparkle" style={{ left: '18%', bottom: 4, animationDelay: '0s' }}>✨</span>
            <span className="sol-cross-fill-sparkle" style={{ left: '42%', bottom: 6, animationDelay: '0.5s' }}>⚡</span>
            <span className="sol-cross-fill-sparkle" style={{ left: '68%', bottom: 4, animationDelay: '1.0s' }}>✨</span>

            <div style={{
              width: 30, height: 30, flexShrink: 0,
              borderRadius: '50%',
              background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
              boxShadow: '0 0 14px rgba(139, 92, 246, 0.45)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontWeight: 700, fontSize: 14,
              position: 'relative', zIndex: 3,
            }}>S</div>
            <span style={{ color: '#1d1d1f', letterSpacing: -0.005, lineHeight: 1.45, position: 'relative', zIndex: 3 }}>
              <strong style={{ color: '#7c3aed' }}>Sophia auto-clasifica</strong> los documentos que subas.
              Docs de otros módulos (pasaporte, 1040, W-2) se <strong>heredan automáticamente</strong> sin re-subir.
              Los docs fiscales requieren consentimiento §7216 — ya lo capturé al abrir el caso.
            </span>
          </div>

          {/* Drop zone */}
          <div style={{
            flex: 1,
            position: 'relative',
            background: hasAnyDoc ? 'rgba(255, 149, 0, 0.03)' : '#fafafa',
            border: hasAnyDoc ? '2px dashed #FF9500' : '2px dashed #c7c7cf',
            borderRadius: 14,
            padding: 18,
            overflow: 'hidden',
            transition: 'background 320ms, border-color 320ms',
          }}>
            {/* Empty state — fades out as docs arrive */}
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              gap: 12,
              color: '#1d1d1f',
              opacity: hasAnyDoc ? 0 : 1,
              transform: hasAnyDoc ? 'scale(0.94)' : 'scale(1)',
              transition: 'opacity 320ms, transform 320ms',
              pointerEvents: 'none',
            }}>
              <FolderIconBig />
              <div style={{ fontSize: 17, fontWeight: 600, color: '#1d1d1f', letterSpacing: -0.01 }}>{p.evidencia_drop_hint || 'Arrastra documentos aquí o haz click para subir'}</div>
              <div style={{ fontSize: 12, color: '#86868b', fontFamily: 'ui-monospace, monospace' }}>PDF · JPG · PNG · HEIC — máx 10 MB cada uno</div>
              <div style={{ marginTop: 18, fontSize: 12, color: '#a1a1a6', fontStyle: 'italic', display: 'flex', alignItems: 'center', gap: 8 }}>
                <FolderIconSmall />
                {lang === 'en' ? 'No documents in this case yet.' : 'Aún no hay documentos en este caso.'}
              </div>
            </div>

            {/* Falling docs */}
            {EVIDENCE_DOCS.map((d, i) => (
              <EvidenceDoc key={d.id} doc={d} order={i} progress={docsProgress[i] || 0} />
            ))}
          </div>

          {/* Bottom action row */}
          <div style={{ display: 'flex', gap: 10, flexShrink: 0 }}>
            <button style={{
              flex: 1, height: 42, borderRadius: 8,
              background: isComplete ? '#34C759' : '#86efac',
              border: 0, color: '#fff', fontSize: 13.5, fontWeight: 600,
              cursor: 'pointer',
              opacity: isComplete ? 1 : 0.78,
              transition: 'all 220ms',
              boxShadow: isComplete ? '0 6px 18px rgba(52, 199, 89, 0.32)' : 'none',
            }}>{p.evidencia_btn_continuar || 'Continuar a Organizar paquete →'}</button>
            <button style={{
              padding: '0 18px', height: 42, borderRadius: 8,
              background: '#fff', border: '1px solid #e8e8ed',
              color: '#1d1d1f', fontSize: 13.5, fontWeight: 500,
              cursor: 'pointer',
            }}>{p.evidencia_btn_cerrar || '× Cerrar'}</button>
          </div>
        </div>

        {/* RIGHT sidebar */}
        <div style={{ width: 280, display: 'flex', flexDirection: 'column', gap: 12, flexShrink: 0 }}>
          {/* CASO card */}
          <div style={{
            background: '#fff', border: '1px solid #e8e8ed',
            borderRadius: 12, padding: 14,
          }}>
            <div style={{
              fontSize: 10, fontFamily: 'ui-monospace, monospace',
              color: '#86868b', letterSpacing: 0.1,
              textTransform: 'uppercase', fontWeight: 600,
              marginBottom: 8,
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span>📋</span> {p.evidencia_sidebar_caso || 'CASO'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5, fontSize: 11.5 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ color: '#86868b' }}>Beneficiario</span>
                <strong style={{ color: '#1d1d1f', textAlign: 'right', fontSize: 11 }}>CARLA A. VERA RODRÍGUEZ</strong>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ color: '#86868b' }}>Peticionario</span>
                <strong style={{ color: '#1d1d1f' }}>TOMÁS SMITH</strong>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ color: '#86868b' }}>Tipo</span>
                <strong style={{ color: '#1d1d1f', fontFamily: 'ui-monospace, monospace', fontSize: 10.5 }}>I-130 + I-130A + I-485 + I-864</strong>
              </div>
            </div>
          </div>

          {/* PROGRESO card with animated count + complete pulse */}
          <div className={isComplete ? 'sol-progress-card-complete' : ''} style={{
            background: '#fff', border: '1px solid #e8e8ed',
            borderRadius: 12, padding: 14,
            transition: 'all 300ms',
          }}>
            <div style={{
              fontSize: 10, fontFamily: 'ui-monospace, monospace',
              color: '#86868b', letterSpacing: 0.1,
              textTransform: 'uppercase', fontWeight: 600,
              marginBottom: 6,
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span>📈</span> {p.evidencia_sidebar_progreso || 'PROGRESO'}
            </div>
            <div style={{
              fontWeight: 700,
              fontVariantNumeric: 'tabular-nums',
              letterSpacing: -0.025,
              lineHeight: 1,
              display: 'flex', alignItems: 'baseline', gap: 4,
              color: isComplete ? '#34C759' : '#FF9500',
            }}>
              <span key={settledCount} className="sol-progress-digit" style={{ fontSize: 36, display: 'inline-block' }}>{settledCount}</span>
              <span style={{ fontSize: 18, color: '#a1a1a6', fontWeight: 400 }}>/ {total}</span>
            </div>
            <div style={{
              fontSize: 11.5, color: '#6e6e73', marginBottom: 10, marginTop: 4,
            }}>{lang === 'en' ? 'documents uploaded' : 'documentos cargados'}</div>
            <div style={{
              height: 6, background: '#f0f0f3', borderRadius: 3, overflow: 'hidden',
            }}>
              <div style={{
                width: `${pct}%`,
                height: '100%',
                background: isComplete
                  ? '#34C759'
                  : 'linear-gradient(90deg, #FF9500, #fb923c)',
                transition: 'width 380ms cubic-bezier(.2,.7,.2,1)',
                boxShadow: isComplete ? '0 0 14px rgba(52, 199, 89, 0.6)' : 'none',
              }} />
            </div>
          </div>

          {/* Sophia tips card */}
          <div style={{
            background: 'linear-gradient(180deg, #f5f3ff, #fff)',
            border: '1px solid #ddd6fe',
            borderRadius: 12,
            padding: 14,
            position: 'relative',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8,
              marginBottom: 8,
            }}>
              <div className="sol-callout-avatar-pulse" style={{
                width: 26, height: 26,
                borderRadius: '50%',
                background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
                color: '#fff', fontSize: 12, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 0 12px rgba(139, 92, 246, 0.5)',
                position: 'relative',
              }}>S</div>
              <span style={{
                fontSize: 11, fontFamily: 'ui-monospace, monospace',
                color: '#7c3aed', letterSpacing: 0.08,
                textTransform: 'uppercase', fontWeight: 600,
              }}>{p.evidencia_sidebar_sophia || 'Sophia · tips para evidencia'}</span>
            </div>
            <div style={{
              padding: '10px 12px',
              background: '#fff',
              border: '1px solid #ede9fe',
              borderRadius: 8,
              fontSize: 11.5, color: '#1d1d1f',
              letterSpacing: -0.005, lineHeight: 1.45,
            }}>
              📑 Para <strong>Birth cert peticionario</strong>, USCIS acepta: (a) US passport, (b) certificate of citizenship, (c) naturalization cert, (d) consular report of birth abroad. <em style={{ color: '#86868b' }}>Consulta cuál aplica al caso.</em>
            </div>
            <div style={{
              fontSize: 10, color: '#a78bfa',
              fontStyle: 'italic', marginTop: 8,
            }}>{lang === 'en' ? 'Operational information — not legal advice.' : 'Información operacional — no constituye asesoría legal.'}</div>
          </div>

          {/* +1 HEREDADO with bouncy pop + sparkle burst */}
          {heredadoSettled && (
            <div style={{
              position: 'relative',
              background: '#dcfce7',
              border: '1.5px solid #86efac',
              borderRadius: 12,
              padding: 12,
              animation: 'sol-heredado-pop 520ms cubic-bezier(.34,1.56,.64,1)',
              boxShadow: '0 4px 14px rgba(52, 199, 89, 0.22)',
            }}>
              {/* Mini sparkle burst */}
              <span style={{
                position: 'absolute', top: -8, right: -4,
                fontSize: 16,
                animation: 'sol-mini-sparkle 720ms ease-out',
                pointerEvents: 'none',
              }}>✨</span>
              <span style={{
                position: 'absolute', top: -4, right: 24,
                fontSize: 13,
                animation: 'sol-mini-sparkle 820ms ease-out 100ms',
                pointerEvents: 'none',
              }}>⭐</span>
              <span style={{
                position: 'absolute', bottom: -4, left: 14,
                fontSize: 13,
                animation: 'sol-mini-sparkle 760ms ease-out 200ms',
                pointerEvents: 'none',
              }}>✨</span>

              <div style={{
                fontSize: 10.5, fontFamily: 'ui-monospace, monospace',
                color: '#15803d', letterSpacing: 0.1,
                textTransform: 'uppercase', fontWeight: 700,
                marginBottom: 4,
              }}>+1 Heredado</div>
              <div style={{
                fontSize: 11.5, color: '#14532d', letterSpacing: -0.005,
              }}>
                <strong>tax_return_2025.pdf</strong> desde Taxes
              </div>
            </div>
          )}
        </div>
      </div>
    </PaqueteShell>
  );
}

// Big folder icon for empty drop zone (matches macOS Finder folder style)
function FolderIconBig() {
  return (
    <svg width="64" height="50" viewBox="0 0 64 50" fill="none" aria-hidden="true">
      <path d="M2 8c0-2.2 1.8-4 4-4h14l5 5h33c2.2 0 4 1.8 4 4v33c0 2.2-1.8 4-4 4H6c-2.2 0-4-1.8-4-4V8z" fill="#d2d2d7"/>
      <path d="M2 16h60v26c0 2.2-1.8 4-4 4H6c-2.2 0-4-1.8-4-4V16z" fill="#e8e8ed" stroke="#c7c7cf" strokeWidth="1"/>
    </svg>
  );
}

function FolderIconSmall() {
  return (
    <svg width="22" height="18" viewBox="0 0 22 18" fill="none" aria-hidden="true">
      <path d="M1 3c0-1 .8-1.5 1.5-1.5h5l2 2h11c.8 0 1.5.7 1.5 1.5v11c0 .8-.7 1.5-1.5 1.5h-18C1.6 17.5 1 16.8 1 16V3z" fill="#d2d2d7"/>
      <path d="M1 6h20v10c0 .8-.7 1.5-1.5 1.5h-17C1.6 17.5 1 16.8 1 16V6z" fill="#e8e8ed" stroke="#c7c7cf" strokeWidth="0.6"/>
    </svg>
  );
}

function EvidenceDoc({ doc, order, progress }) {
  const p = clamp(progress, 0, 1);
  if (p <= 0) return null;
  const e = Easing.easeOutCubic(p);
  // Grid 3 cols × 3 rows inside the redesigned drop zone (wider now)
  // Drop zone inner width ≈ 700px, height ≈ 380px → docs 200×112, gap 18
  const col = order % 3;
  const row = Math.floor(order / 3);
  const tgtX = 14 + col * (200 + 18);   // 200 doc + 18 gap
  const tgtY = 14 + row * (112 + 18);
  const srcX = 600 + order * 18;
  const srcY = -100 - order * 8;
  const x = srcX + (tgtX - srcX) * e;
  const y = srcY + (tgtY - srcY) * e;
  const rot = (1 - e) * 16 + ((order % 2) * 8 - 4) * e;
  const scale = 0.7 + 0.3 * e;
  const opacity = Math.min(1, p * 2);

  const ext = doc.name.split('.').pop().toUpperCase();
  const icon = ext === 'JPG' || ext === 'PNG' ? '🖼️' : '📄';
  const settled = p >= 1;
  const heritage = doc.heritage && settled;

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: 200, height: 102,
      background: heritage ? '#dcfce7' : '#fff',
      borderRadius: 10,
      boxShadow: `0 ${4 + 12 * e}px ${14 + 14 * e}px rgba(0, 0, 0, ${0.08 + 0.05 * e})`,
      transform: `rotate(${rot}deg) scale(${scale})`,
      transformOrigin: 'center',
      opacity,
      border: settled
        ? (heritage ? '1.5px solid #34C759' : '1.5px solid #FF9500')
        : '1px solid #e8e8ed',
      padding: 10,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between',
      zIndex: 2,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 22 }}>{icon}</div>
        {heritage && (
          <div style={{
            fontSize: 8.5,
            background: '#34C759',
            color: '#fff',
            padding: '2px 6px',
            borderRadius: 999,
            fontWeight: 700,
            letterSpacing: 0.04,
          }}>HEREDADO</div>
        )}
      </div>
      <div>
        <div style={{
          fontSize: 10,
          fontFamily: 'ui-monospace, monospace',
          color: '#1d1d1f',
          fontWeight: 500,
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          marginBottom: 3,
        }}>{doc.name}</div>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 4,
          fontSize: 9,
          color: settled ? (heritage ? '#15803d' : '#9a3412') : '#a1a1a6',
          fontWeight: 600,
          letterSpacing: 0.04,
        }}>
          {settled ? (<><span>✓</span> {doc.tag}</>) : (<><span style={{ fontSize: 7 }}>●</span> {ext}</>)}
        </div>
      </div>
    </div>
  );
}

// ── Organizar paquete (drag-reorder) ──────────────────────────────────
const ORG_ITEMS = [
  { icon: '💳', name: 'G-1450 Pago con tarjeta',  tag: 'Pago' },
  { icon: '✅', name: 'Checklist del paquete',    tag: 'Anexo' },
  { icon: '📝', name: 'Cover Letter',             tag: 'Carta' },
  { icon: '📄', name: 'I-130A',                   tag: 'Forma' },
  { icon: '📄', name: 'I-485',                    tag: 'Forma' },
  { icon: '📄', name: 'I-130',                    tag: 'Forma' },
  { icon: '📄', name: 'I-864',                    tag: 'Forma' },
];

function OrganizarDrag({ order = [0,1,2,3,4,5,6], draggingIdx = null, draggingY = 0 }) {
  const lang = useTimeline().lang || 'es';
  return (
    <PaqueteShell>
      <div style={{ position: 'absolute', left: 22, right: 280, top: 70 }}>
        <div style={{
          padding: '10px 14px',
          background: 'linear-gradient(90deg, #f0fdf4, #fff)',
          border: '1px solid #86efac',
          borderRadius: 10,
          marginBottom: 14,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          fontSize: 12,
          color: '#15803d',
        }}>
          <span style={{ fontSize: 14 }}>📦</span>
          <span style={{ letterSpacing: -0.005 }}>
            {lang === 'en'
              ? <><strong>Step 3 — USCIS envelope order · 7 items.</strong> Drag to reorder as your Lockbox prefers.</>
              : <><strong>Paso 3 — Orden del sobre USCIS · 7 items.</strong> Arrastra para reordenar como prefiere tu Lockbox.</>
            }
          </span>
        </div>

        <div style={{ display: 'flex', gap: 16 }}>
          {/* Order list */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {order.map((origIdx, pos) => {
              const item = ORG_ITEMS[origIdx];
              const isDragging = draggingIdx === pos;
              return (
                <div key={origIdx} style={{
                  background: isDragging ? '#fef3c7' : '#fff',
                  border: isDragging ? '1.5px solid #34C759' : '1px solid #e8e8ed',
                  borderRadius: 10,
                  padding: '12px 14px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  boxShadow: isDragging
                    ? '0 12px 32px rgba(52, 199, 89, 0.25)'
                    : '0 1px 3px rgba(0,0,0,0.03)',
                  transform: isDragging ? `translateY(${draggingY}px) scale(1.02)` : 'none',
                  transition: isDragging ? 'none' : 'transform 280ms cubic-bezier(0.2, 0.8, 0.4, 1)',
                  zIndex: isDragging ? 10 : 1,
                  position: 'relative',
                }}>
                  <div style={{
                    cursor: 'grab',
                    color: '#a1a1a6',
                    fontSize: 18,
                    letterSpacing: -0.2,
                  }}>⋮⋮</div>
                  <div style={{
                    width: 28, height: 28,
                    background: '#f5f5f7',
                    borderRadius: 6,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 8, fontWeight: 700,
                    color: '#6e6e73',
                    fontFamily: 'ui-monospace, monospace',
                  }}>{String(pos + 1).padStart(2, '0')}</div>
                  <div style={{ fontSize: 18 }}>{item.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{
                      fontSize: 13, fontWeight: 500,
                      color: '#1d1d1f', letterSpacing: -0.005,
                    }}>{item.name}</div>
                  </div>
                  <div style={{
                    fontSize: 10, color: '#6e6e73',
                    fontFamily: 'ui-monospace, monospace',
                    padding: '3px 8px',
                    background: '#f5f5f7',
                    borderRadius: 999,
                  }}>{item.tag}</div>
                </div>
              );
            })}
          </div>

          {/* Right column */}
          <div style={{
            width: 240,
            display: 'flex',
            flexDirection: 'column',
            gap: 10,
          }}>
            <div style={{
              background: '#fff', border: '1px solid #e8e8ed',
              borderRadius: 10, padding: 14,
            }}>
              <div style={{
                fontSize: 10, fontFamily: 'ui-monospace, monospace',
                color: '#6e6e73', letterSpacing: 0.1,
                textTransform: 'uppercase', fontWeight: 600,
                marginBottom: 6,
              }}>{lang === 'en' ? 'Summary' : 'Resumen'}</div>
              <div style={{ fontSize: 11, color: '#1d1d1f', marginBottom: 4 }}>
                <strong>Lockbox:</strong> Chicago AOS
              </div>
              <div style={{ fontSize: 11, color: '#1d1d1f', marginBottom: 4 }}>
                <strong>Fees totales:</strong> <span style={{ fontFamily: 'ui-monospace, monospace' }}>$2,705</span>
              </div>
              <div style={{ fontSize: 11, color: '#1d1d1f' }}>
                <strong>Documentos:</strong> 7 / 7
              </div>
            </div>

            <div style={{
              background: '#dcfce7',
              border: '1px solid #86efac',
              borderRadius: 10, padding: 12,
            }}>
              <div style={{
                fontSize: 11, fontWeight: 600,
                color: '#15803d',
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <span>✓</span> Listo para imprimir
              </div>
            </div>
          </div>
        </div>
      </div>
    </PaqueteShell>
  );
}

// ── Cover Letter editor ───────────────────────────────────────────────
const COVER_PARAGRAPHS = [
  'EasyPro Plus LLC',
  '8810 Commodity Cir, Orlando, FL 32819',
  '',
  'Case ref: ac632039',
  'Date: May 16, 2026',
  '',
  'To: USCIS Chicago Lockbox',
  '     P.O. Box 805887',
  '     Chicago, IL 60680-4120',
  '',
  'Re: Petition for Alien Relative + Adjustment of Status',
  '    Petitioner: TOMÁS SMITH (U.S. Citizen)',
  '    Beneficiary: CARLA A. VERA RODRÍGUEZ',
  '',
  'Dear USCIS Officer:',
  '',
  'Enclosed in this package, please find a concurrent filing of forms I-130, I-130A, I-485, and I-864 along with the optional I-765 (work permit) and I-131 (advance parole). Filing fees of $2,705 are paid by credit card via G-1450, included.',
  '',
  'Sincerely,',
  'Test Usuario · EasyPro Plus LLC',
];

function CoverLetterEditor({ typedChars = 0 }) {
  const lang = useTimeline().lang || 'es';
  const fullText = COVER_PARAGRAPHS.join('\n');
  const visibleText = fullText.slice(0, typedChars);

  return (
    <PaqueteShell>
      <div style={{ position: 'absolute', left: 22, right: 280, top: 70 }}>
        <div style={{
          padding: '10px 14px',
          background: 'linear-gradient(90deg, #eff6ff, #fff)',
          border: '1px solid #93c5fd',
          borderRadius: 10,
          marginBottom: 14,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          fontSize: 12,
          color: '#1e40af',
        }}>
          <span style={{ fontSize: 14 }}>📝</span>
          <span style={{ letterSpacing: -0.005 }}>
            {lang === 'en'
              ? <><strong>Step 4 — Editable cover letter.</strong> Auto-generated with the package order. The preview updates in real time.</>
              : <><strong>Paso 4 — Cover Letter editable.</strong> Generada automáticamente con el orden del paquete. El preview se actualiza en tiempo real.</>
            }
          </span>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 12,
          height: 520,
        }}>
          {/* Editor left */}
          <div style={{
            background: '#fff',
            border: '1px solid #e8e8ed',
            borderRadius: 10,
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
          }}>
            <div style={{
              padding: '8px 14px',
              borderBottom: '1px solid #f0f0f3',
              fontSize: 10,
              fontFamily: 'ui-monospace, monospace',
              color: '#6e6e73',
              letterSpacing: 0.1,
              textTransform: 'uppercase',
              fontWeight: 600,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}>
              <span>Editor · Cover Letter</span>
              <span style={{ color: '#007AFF' }}>{typedChars} / {fullText.length}</span>
            </div>
            <div style={{
              flex: 1,
              padding: '14px 16px',
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontSize: 10,
              lineHeight: 1.5,
              color: '#1d1d1f',
              whiteSpace: 'pre',
              overflow: 'hidden',
              letterSpacing: -0.005,
            }}>
              {visibleText}
              {typedChars < fullText.length && (
                <span style={{
                  display: 'inline-block',
                  width: 5, height: 10,
                  background: '#007AFF',
                  marginLeft: 1,
                  verticalAlign: 'middle',
                  animation: 'sol-caret 0.6s steps(1) infinite',
                }} />
              )}
            </div>
          </div>

          {/* Preview right */}
          <div style={{
            background: '#fff',
            border: '1px solid #e8e8ed',
            borderRadius: 10,
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
          }}>
            <div style={{
              padding: '8px 14px',
              borderBottom: '1px solid #f0f0f3',
              fontSize: 10,
              fontFamily: 'ui-monospace, monospace',
              color: '#6e6e73',
              letterSpacing: 0.1,
              textTransform: 'uppercase',
              fontWeight: 600,
            }}>Preview · Lo que verá USCIS</div>
            <div style={{
              flex: 1,
              padding: '20px 28px',
              fontFamily: '"Times New Roman", Georgia, serif',
              fontSize: 11.5,
              lineHeight: 1.7,
              color: '#1d1d1f',
              whiteSpace: 'pre-wrap',
              overflow: 'hidden',
              background: '#fafafa',
            }}>{visibleText}</div>
          </div>
        </div>
      </div>
    </PaqueteShell>
  );
}

// ── Print outputs — "Impresora 4D" (rewritten Fase 3 per JP feedback) ─
// Central printer spits 4 outputs in sequence: USCIS envelope, postal labels,
// email confirmation, WhatsApp with real USPS tracking number.
function PrintOutputs({ progress = 0 }) {
  const p = clamp(progress, 0, 1);
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const pq = i18n.paquete || {};

  // Phase orchestration (each output: paper flies → content reveals)
  const phases = {
    printerOn:   clamp(p / 0.10, 0, 1),
    paper1Fly:   clamp((p - 0.08) / 0.16, 0, 1),  // → envelope
    envelopeIn:  clamp((p - 0.18) / 0.18, 0, 1),
    paper2Fly:   clamp((p - 0.25) / 0.16, 0, 1),  // → labels
    labelsIn:    clamp((p - 0.34) / 0.18, 0, 1),
    paper3Fly:   clamp((p - 0.48) / 0.16, 0, 1),  // → email
    emailIn:     clamp((p - 0.56) / 0.18, 0, 1),
    paper4Fly:   clamp((p - 0.62) / 0.16, 0, 1),  // → whatsapp
    whatsappIn:  clamp((p - 0.72) / 0.18, 0, 1),
    summary:     clamp((p - 0.82) / 0.18, 0, 1),
  };

  // Stage: full-width inside PaqueteShell. Origin of all coords below.
  // Stage size ~ 1236 × 540. Printer in center, 4 outputs in 4 corners.
  const printerCx = 618;
  const printerCy = 286;
  // Output anchor points (center of each output card)
  const dest = {
    envelope: { x: 220,  y: 130 },
    labels:   { x: 1010, y: 130 },
    email:    { x: 330,  y: 450 },
    whatsapp: { x: 990,  y: 450 },
  };

  return (
    <PaqueteShell>
      {/* Title bar */}
      <div style={{ position: 'absolute', left: 22, right: 22, top: 60 }}>
        <div style={{
          fontSize: 11, fontFamily: 'ui-monospace, monospace',
          color: '#9a3412', letterSpacing: 0.14,
          textTransform: 'uppercase', fontWeight: 700,
          marginBottom: 4,
        }}>{pq.print_eyebrow || '🖨 Paso 5 — 1 click → todo'}</div>
        <div style={{
          fontSize: 22, fontWeight: 600, color: '#1d1d1f',
          letterSpacing: -0.025, marginBottom: 0,
        }}>{pq.print_title || 'De la captura al sobre. Sin re-trabajo.'}</div>
      </div>

      {/* Stage */}
      <div style={{
        position: 'absolute', left: 22, right: 22, top: 110, bottom: 14,
        background: 'linear-gradient(180deg, #fafafa, #f5f5f7)',
        border: '1px solid #e8e8ed',
        borderRadius: 14,
        overflow: 'hidden',
      }}>
        {/* Subtle radial highlight behind printer */}
        <div style={{
          position: 'absolute',
          left: printerCx - 280, top: printerCy - 200,
          width: 560, height: 400,
          background: 'radial-gradient(circle, rgba(255, 149, 0, 0.10) 0%, transparent 60%)',
          pointerEvents: 'none',
          opacity: phases.printerOn,
          transition: 'opacity 300ms',
        }} />

        {/* CENTER: Printer */}
        <div style={{
          position: 'absolute',
          left: printerCx - 100, top: printerCy - 90,
          width: 200, height: 180,
          opacity: phases.printerOn,
          transform: `scale(${0.85 + 0.15 * phases.printerOn})`,
          transformOrigin: 'center',
          transition: 'transform 320ms',
        }}>
          <PrinterIcon active={phases.printerOn >= 1} />
          {/* Working indicator "Imprimiendo…" */}
          {p < 0.85 && (
            <div style={{
              position: 'absolute',
              left: '50%', bottom: -22,
              transform: 'translateX(-50%)',
              fontSize: 10.5, fontFamily: 'ui-monospace, monospace',
              color: '#FF9500', letterSpacing: 0.06,
              fontWeight: 600, textTransform: 'uppercase',
              opacity: phases.printerOn,
              whiteSpace: 'nowrap',
            }}>
              <span style={{
                display: 'inline-block', width: 6, height: 6,
                borderRadius: '50%', background: '#FF9500',
                marginRight: 6, verticalAlign: 'middle',
                animation: 'sol-printer-blink 0.6s ease-in-out infinite',
              }} />
              {pq.print_status || 'Imprimiendo · 4 outputs'}
            </div>
          )}
          {p >= 0.85 && (
            <div style={{
              position: 'absolute',
              left: '50%', bottom: -22,
              transform: 'translateX(-50%)',
              fontSize: 10.5, fontFamily: 'ui-monospace, monospace',
              color: '#15803d', letterSpacing: 0.06,
              fontWeight: 700, textTransform: 'uppercase',
              animation: 'sol-fade-up 320ms ease-out',
              whiteSpace: 'nowrap',
            }}>{pq.print_done || '✓ Listo · 4 / 4'}</div>
          )}
        </div>

        {/* Flying papers (4) — each shoots from printer top-slot to its destination */}
        <FlyingPaper progress={phases.paper1Fly} fromX={printerCx} fromY={printerCy - 60} toX={dest.envelope.x} toY={dest.envelope.y} arc={-80} />
        <FlyingPaper progress={phases.paper2Fly} fromX={printerCx} fromY={printerCy - 60} toX={dest.labels.x} toY={dest.labels.y} arc={-80} />
        <FlyingPaper progress={phases.paper3Fly} fromX={printerCx} fromY={printerCy + 30} toX={dest.email.x} toY={dest.email.y} arc={60} kind="email" />
        <FlyingPaper progress={phases.paper4Fly} fromX={printerCx} fromY={printerCy + 30} toX={dest.whatsapp.x} toY={dest.whatsapp.y} arc={60} kind="whatsapp" />

        {/* OUTPUT 1: USCIS Envelope — top left */}
        <OutputCard
          opacity={phases.envelopeIn}
          x={40} y={28} width={360} height={196}
          accent="#FF9500"
          badge={pq.print_envelope_badge || '📦 SOBRE USCIS'}
          rotate={-2}
        >
          <div style={{ fontSize: 10, fontFamily: 'ui-monospace, monospace', color: '#6e6e73', letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 600, marginBottom: 2 }}>{pq.print_from || 'De:'}</div>
          <div style={{ fontSize: 11, color: '#1d1d1f', marginBottom: 10 }}>EasyPro Plus LLC · Orlando, FL</div>
          <div style={{
            padding: '6px 10px',
            background: '#fef3c7',
            border: '1.5px solid #FF9500',
            borderRadius: 6,
            fontSize: 10, fontWeight: 700,
            color: '#9a3412', letterSpacing: 0.04,
            fontFamily: 'ui-monospace, monospace',
            marginBottom: 10,
            display: 'inline-block',
          }}>I-130 + I-130A + I-485 + I-864</div>
          <div style={{ fontSize: 10, fontFamily: 'ui-monospace, monospace', color: '#6e6e73', letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 600, marginBottom: 2 }}>{pq.print_to || 'Para:'}</div>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#1d1d1f' }}>USCIS Chicago Lockbox</div>
          <div style={{ fontSize: 10.5, color: '#1d1d1f', fontFamily: 'ui-monospace, monospace' }}>P.O. Box 805887 · Chicago, IL 60680-4120</div>
        </OutputCard>

        {/* OUTPUT 2: 2 Postal labels — top right */}
        <div style={{
          position: 'absolute',
          left: 836, top: 18,
          width: 380, height: 220,
          opacity: phases.labelsIn,
          transform: `translateY(${(1 - phases.labelsIn) * 14}px)`,
          transition: 'all 280ms',
        }}>
          <Label
            opacity={phases.labelsIn}
            x={0} y={0}
            rotate={3}
            title={pq.print_label_uscis_title || 'USCIS Chicago Lockbox'}
            lines={['P.O. Box 805887', 'Chicago, IL 60680-4120']}
            accent="#FF9500"
            badge="USCIS"
          />
          <Label
            opacity={phases.labelsIn}
            x={50} y={104}
            rotate={-2}
            title={pq.print_label_client_title || 'TOMÁS SMITH · COPIA'}
            lines={['8810 Commodity Cir', 'Orlando, FL 32819']}
            accent="#34C759"
            badge={pq.print_labels_client || 'CLIENTE'}
          />
        </div>

        {/* OUTPUT 3: Email — bottom left */}
        <OutputCard
          opacity={phases.emailIn}
          x={40} y={392} width={478} height={108}
          accent="#007AFF"
          badge={pq.print_email_badge || '✉ EMAIL CLIENTE'}
          rotate={1.5}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 8,
              background: '#eff6ff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 18, flexShrink: 0,
            }}>✉</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#1d1d1f', letterSpacing: -0.005, marginBottom: 2 }}>tomas.smith.fl@gmail.com</div>
              <div style={{ fontSize: 10.5, color: '#6e6e73', fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{pq.print_email_subject || '"Tu paquete USCIS salió hoy · tracking USPS adjunto"'}</div>
            </div>
            <div style={{
              width: 22, height: 22, borderRadius: '50%',
              background: '#34C759', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700, flexShrink: 0,
            }}>✓</div>
          </div>
        </OutputCard>

        {/* OUTPUT 4: WhatsApp with USPS tracking — bottom right */}
        <OutputCard
          opacity={phases.whatsappIn}
          x={742} y={392} width={478} height={108}
          accent="#25d366"
          badge={pq.print_wa_badge || '💬 WHATSAPP · TRACKING'}
          rotate={-1.5}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 8,
              background: '#f0fdf4',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 18, flexShrink: 0,
            }}>💬</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, color: '#1d1d1f', letterSpacing: -0.005, marginBottom: 2 }}>{pq.print_wa_line || 'USPS Priority · entrega 22 may'}</div>
              <div style={{
                fontSize: 11.5, color: '#15803d',
                fontFamily: 'ui-monospace, monospace',
                fontWeight: 600, letterSpacing: 0.02,
              }}>9405 5036 9930 0123 4567 89</div>
            </div>
            <div style={{
              fontSize: 11, color: '#15803d', fontWeight: 600,
              flexShrink: 0, whiteSpace: 'nowrap',
            }}>✓✓</div>
          </div>
        </OutputCard>

        {/* Summary line — appears at the very end */}
        {phases.summary > 0 && (
          <div style={{
            position: 'absolute',
            left: '50%', bottom: 22,
            transform: `translateX(-50%) translateY(${(1 - phases.summary) * 10}px)`,
            opacity: phases.summary,
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 16px',
            background: 'rgba(10, 8, 24, 0.92)',
            border: '1px solid rgba(167, 139, 250, 0.4)',
            borderRadius: 999,
            boxShadow: '0 14px 38px rgba(139, 92, 246, 0.35)',
            fontSize: 13, fontWeight: 600, color: '#fff',
            letterSpacing: -0.005,
            transition: 'all 320ms',
          }}>
            <span style={{ fontSize: 16 }}>⚡</span>
            <span>{lang === 'en'
              ? <>1 click <span style={{ color: '#a78bfa' }}>→</span> 4 outputs <span style={{ color: '#a78bfa' }}>→</span> 0 errors</>
              : <>1 click <span style={{ color: '#a78bfa' }}>→</span> 4 outputs <span style={{ color: '#a78bfa' }}>→</span> 0 errores</>
            }</span>
          </div>
        )}
      </div>
    </PaqueteShell>
  );
}

// Simple printer SVG icon — apple-iconish, blocky
function PrinterIcon({ active = true }) {
  return (
    <svg width="200" height="180" viewBox="0 0 200 180" fill="none" aria-hidden="true" style={{ display: 'block' }}>
      {/* Drop shadow under printer */}
      <ellipse cx="100" cy="172" rx="78" ry="6" fill="rgba(0,0,0,0.12)" />
      {/* Top paper tray (showing sheet sticking up) */}
      <rect x="46" y="6" width="108" height="32" rx="3" fill="#fff" stroke="#86868b" strokeWidth="1.5"/>
      <line x1="54" y1="14" x2="146" y2="14" stroke="#d2d2d7" strokeWidth="1"/>
      <line x1="54" y1="20" x2="138" y2="20" stroke="#d2d2d7" strokeWidth="1"/>
      <line x1="54" y1="26" x2="142" y2="26" stroke="#d2d2d7" strokeWidth="1"/>
      {/* Main body */}
      <rect x="14" y="38" width="172" height="102" rx="10" fill="#3a3a3c" stroke="#1d1d1f" strokeWidth="1.5"/>
      {/* Screen */}
      <rect x="26" y="50" width="46" height="24" rx="3" fill={active ? '#34C759' : '#1c1c1e'} stroke="#1d1d1f" strokeWidth="0.5"/>
      {active && (
        <>
          <rect x="30" y="56" width="38" height="2" rx="1" fill="rgba(255,255,255,0.55)"/>
          <rect x="30" y="62" width="30" height="2" rx="1" fill="rgba(255,255,255,0.35)"/>
          <rect x="30" y="68" width="34" height="2" rx="1" fill="rgba(255,255,255,0.45)"/>
        </>
      )}
      {/* Buttons row */}
      <circle cx="92" cy="62" r="4" fill="#86868b"/>
      <circle cx="108" cy="62" r="4" fill="#86868b"/>
      <circle cx="124" cy="62" r="4" fill={active ? '#FF9500' : '#86868b'}/>
      <circle cx="140" cy="62" r="4" fill="#86868b"/>
      <circle cx="156" cy="62" r="4" fill={active ? '#34C759' : '#86868b'}/>
      {/* Output slot (where papers come out) */}
      <rect x="34" y="98" width="132" height="8" rx="2" fill="#0a0a0a"/>
      <rect x="40" y="106" width="120" height="3" fill="#1d1d1f"/>
      {/* Output paper edge — peeking out */}
      <rect x="46" y="108" width="108" height="22" fill="#fff" stroke="#86868b" strokeWidth="0.8"/>
      {/* Feet */}
      <rect x="24" y="140" width="22" height="10" rx="2" fill="#1d1d1f"/>
      <rect x="154" y="140" width="22" height="10" rx="2" fill="#1d1d1f"/>
    </svg>
  );
}

// A small sheet of paper or message bubble flying along an arc.
function FlyingPaper({ progress, fromX, fromY, toX, toY, arc = -40, kind = 'paper' }) {
  if (progress <= 0 || progress >= 1) return null;
  const e = Easing.easeInOutQuad(progress);
  const x = fromX + (toX - fromX) * e;
  // Arc lift: pure sin wave (peaks at progress=0.5)
  const y = fromY + (toY - fromY) * e + Math.sin(e * Math.PI) * arc;
  const rot = (1 - e) * 28 * Math.sign(toX - fromX) + Math.sin(e * Math.PI * 2) * 10;
  const opacity = Math.min(1, progress * 4) * Math.min(1, (1 - progress) * 4);
  const scale = 0.6 + 0.4 * Math.sin(e * Math.PI);

  if (kind === 'email') {
    return (
      <div style={{
        position: 'absolute',
        left: x - 14, top: y - 10,
        width: 28, height: 20,
        background: '#fff',
        border: '1.5px solid #007AFF',
        borderRadius: 3,
        transform: `rotate(${rot}deg) scale(${scale})`,
        opacity,
        zIndex: 5,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11,
        color: '#007AFF',
        boxShadow: '0 4px 10px rgba(0, 122, 255, 0.25)',
      }}>✉</div>
    );
  }
  if (kind === 'whatsapp') {
    return (
      <div style={{
        position: 'absolute',
        left: x - 14, top: y - 10,
        width: 28, height: 20,
        background: '#25d366',
        borderRadius: 4,
        transform: `rotate(${rot}deg) scale(${scale})`,
        opacity,
        zIndex: 5,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11,
        color: '#fff',
        boxShadow: '0 4px 10px rgba(37, 211, 102, 0.32)',
      }}>💬</div>
    );
  }
  // Default: paper sheet
  return (
    <div style={{
      position: 'absolute',
      left: x - 11, top: y - 14,
      width: 22, height: 28,
      background: '#fff',
      border: '1px solid #c7c7cf',
      borderRadius: 2,
      transform: `rotate(${rot}deg) scale(${scale})`,
      opacity,
      zIndex: 5,
      boxShadow: '0 4px 12px rgba(0, 0, 0, 0.18)',
    }}>
      <div style={{ height: 2, background: '#e8e8ed', margin: '4px 3px' }} />
      <div style={{ height: 1.5, background: '#e8e8ed', margin: '0 3px 2px' }} />
      <div style={{ height: 1.5, background: '#e8e8ed', margin: '0 3px 2px' }} />
      <div style={{ height: 1.5, background: '#e8e8ed', margin: '0 3px 2px' }} />
    </div>
  );
}

// Generic output card with badge — used for envelope, email, whatsapp
function OutputCard({ x, y, width, height, opacity, rotate = 0, accent, badge, children }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width, height,
      background: '#fff',
      border: `1.5px solid ${accent}`,
      borderRadius: 10,
      padding: '12px 14px',
      opacity,
      transform: `rotate(${rotate}deg) translateY(${(1 - opacity) * 18}px) scale(${0.88 + 0.12 * opacity})`,
      boxShadow: `0 12px 32px ${accent}33`,
      transition: 'opacity 280ms, transform 280ms',
    }}>
      <div style={{
        position: 'absolute',
        top: -10, left: 12,
        padding: '3px 8px',
        background: accent,
        color: '#fff',
        borderRadius: 4,
        fontSize: 9, fontWeight: 700,
        letterSpacing: 0.08,
        fontFamily: 'ui-monospace, monospace',
        boxShadow: `0 4px 10px ${accent}55`,
      }}>{badge}</div>
      {children}
    </div>
  );
}

function Label({ x, y, opacity, rotate, title, lines, accent, badge }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const postalLabel = (i18n.paquete && i18n.paquete.postal_label) || 'ETIQUETA POSTAL';
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: 280, padding: '14px 16px',
      background: '#fffef9',
      border: `1.5px solid ${accent}`,
      borderRadius: 6,
      transform: `rotate(${rotate}deg) translateY(${(1 - opacity) * 20}px) scale(${0.8 + 0.2 * opacity})`,
      opacity,
      boxShadow: `0 12px 32px ${accent}33`,
      transition: 'all 280ms',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        alignItems: 'center', marginBottom: 6,
      }}>
        <div style={{
          fontSize: 9.5, fontFamily: 'ui-monospace, monospace',
          color: '#6e6e73', letterSpacing: 0.12,
          textTransform: 'uppercase', fontWeight: 600,
        }}>{postalLabel}</div>
        <div style={{
          fontSize: 9, padding: '2px 6px',
          background: accent, color: '#fff',
          borderRadius: 3, fontWeight: 700,
          letterSpacing: 0.06,
        }}>{badge}</div>
      </div>
      <div style={{
        fontSize: 12, fontWeight: 600,
        color: '#1d1d1f', letterSpacing: -0.005,
        marginBottom: 4,
      }}>{title}</div>
      {lines.map((l, i) => (
        <div key={i} style={{
          fontSize: 10, color: '#1d1d1f',
          fontFamily: 'ui-monospace, monospace',
        }}>{l}</div>
      ))}
    </div>
  );
}

Object.assign(window, {
  HubFiveButtons, FormaI130, EvidenciaDrop, OrganizarDrag,
  CoverLetterEditor, PrintOutputs,
  HUB_BUTTONS, EVIDENCE_DOCS, ORG_ITEMS, COVER_PARAGRAPHS, I130_FIELDS,
});
