// mockups/case-creation.jsx — Los 4 modales del flujo de creación de caso
//
// Modal 1: NuevoClienteModal       — drop ID, Sophia analiza
// Modal 2: ConfirmaDatosModal      — Sophia extrajo, usuario revisa
// Modal 3: NuevoCasoModal          — 6 tarjetas de módulos
// Modal 4: CasoTaxesModal          — año fiscal + tipo declaración + origen
//
// Wrapper: <CaseCreationModal step ... />
//
// Exports on window: CaseCreationModal, ModalChrome, ModalBackdrop

// ── Shared backdrop ─────────────────────────────────────────────────
function ModalBackdrop({ progress = 1 }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: `rgba(0,0,0,${0.35 * progress})`,
      backdropFilter: `blur(${4 * progress}px)`,
      WebkitBackdropFilter: `blur(${4 * progress}px)`,
      zIndex: 20,
      pointerEvents: 'none',
    }} />
  );
}

// ── Shared modal chrome ─────────────────────────────────────────────
function ModalChrome({ width = 520, progress = 1, children }) {
  const e = Easing.easeOutCubic(progress);
  return (
    <div style={{
      position: 'absolute',
      top: '50%', left: '50%',
      transform: `translate(-50%, -50%) scale(${0.92 + 0.08 * e})`,
      width,
      background: '#fff',
      borderRadius: 18,
      boxShadow: '0 30px 80px rgba(0,0,0,0.30), 0 12px 32px rgba(0,0,0,0.18)',
      opacity: e,
      zIndex: 22,
      overflow: 'hidden',
      maxHeight: '90%',
      display: 'flex',
      flexDirection: 'column',
    }}>
      {children}
    </div>
  );
}

function ModalHeader({ title, subtitle, accent = '#8b5cf6' }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'flex-start',
      gap: 14,
      padding: '20px 24px 0',
    }}>
      <div style={{
        width: 38, height: 38,
        borderRadius: '50%',
        background: 'radial-gradient(circle at 35% 30%, #c4b5fd 0%, #8b5cf6 60%, #5b21b6 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
        boxShadow: '0 4px 10px rgba(139, 92, 246, 0.3)',
      }}>
        <Sparkle size={18} color="#fff" />
      </div>
      <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
        <div style={{
          fontSize: 18,
          fontWeight: 600,
          color: '#1d1d1f',
          letterSpacing: -0.02,
          lineHeight: 1.2,
          marginBottom: 6,
        }}>{title}</div>
        {subtitle && (
          <div style={{
            fontSize: 12.5,
            color: accent,
            letterSpacing: -0.005,
            lineHeight: 1.4,
          }}><b style={{ fontWeight: 600 }}>"</b> {subtitle}</div>
        )}
      </div>
      <button style={{
        width: 30, height: 30,
        background: '#fff',
        border: '1px solid #e8e8ed',
        borderRadius: '50%',
        color: '#6e6e73',
        fontSize: 14,
        lineHeight: 1,
        flexShrink: 0,
        cursor: 'pointer',
      }}>×</button>
    </div>
  );
}

// ── Modal 1: Nuevo cliente (drop ID) ─────────────────────────────────
function NuevoClienteModal({
  progress = 1,
  licenseFly = 0,        // 0..1 fly-in of license card
  analyzing = false,     // true → analyze button shows spinner
  btnHover = false,
  btnPressed = false,
}) {
  const lang = useTimeline().lang || 'es';
  const cc = ((window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {}).case_create || {};
  // License card visuals: floats over dropzone when 0 < licenseFly < 0.95
  const e = Easing.easeOutCubic(licenseFly);
  // Source: above dropzone (off-screen top). Target: center of dropzone.
  const srcX = 250, srcY = -180;
  const tgtX = 0, tgtY = 0;
  const x = srcX + (tgtX - srcX) * e;
  const y = srcY + (tgtY - srcY) * e;
  const rot = (1 - e) * 14;
  const scale = 0.6 + 0.4 * e;

  const docInDropzone = licenseFly >= 0.95;
  const dropActive = licenseFly > 0 && licenseFly < 0.95;

  return (
    <ModalChrome width={500} progress={progress}>
      <ModalHeader
        title={cc.m1_title || 'Nuevo cliente'}
        subtitle={cc.m1_subtitle || 'Suelta capturas, fotos de licencia o papeles con datos. Sophia los lee.'}
      />
      <div style={{ padding: '18px 24px 22px' }}>
        {/* Dropzone */}
        <div style={{
          position: 'relative',
          background: dropActive ? 'rgba(139, 92, 246, 0.12)' : 'rgba(139, 92, 246, 0.06)',
          border: `2px dashed ${dropActive ? '#8b5cf6' : '#c4b5fd'}`,
          borderRadius: 12,
          padding: '34px 16px',
          textAlign: 'center',
          transition: 'background 200ms, border-color 200ms',
          minHeight: 150,
          marginBottom: 8,
          overflow: 'hidden',
        }}>
          {/* Floating license doc during fly-in */}
          {licenseFly > 0 && licenseFly < 0.97 && (
            <div style={{
              position: 'absolute',
              left: `calc(50% + ${x}px)`,
              top: `calc(50% + ${y}px)`,
              transform: `translate(-50%, -50%) rotate(${rot}deg) scale(${scale})`,
              width: 140,
              height: 88,
              borderRadius: 8,
              background: 'linear-gradient(135deg, #fef3c7 0%, #fde68a 100%)',
              border: '2px solid #f59e0b',
              boxShadow: `0 ${8 + 14 * e}px ${16 + 24 * e}px rgba(0,0,0,${0.15 + 0.10 * e})`,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 4,
              zIndex: 5,
              pointerEvents: 'none',
              willChange: 'transform',
            }}>
              <div style={{
                fontSize: 8.5,
                fontWeight: 700,
                color: '#7c2d12',
                letterSpacing: 0.1,
              }}>FLORIDA</div>
              <div style={{
                fontSize: 9.5,
                fontWeight: 700,
                color: '#7c2d12',
                letterSpacing: 0.05,
              }}>DRIVER LICENSE</div>
              <div style={{
                fontSize: 9,
                color: '#92400e',
                fontFamily: 'ui-monospace, monospace',
                marginTop: 2,
              }}>SMITH, TOMÁS</div>
              <div style={{
                fontSize: 7.5,
                color: '#a16207',
                fontFamily: 'ui-monospace, monospace',
              }}>S530-456-78-218-0</div>
            </div>
          )}

          {!docInDropzone && (
            <>
              <div style={{ marginBottom: 8 }}>
                <Sparkle size={28} color="#8b5cf6" />
              </div>
              <div style={{
                fontSize: 14,
                fontWeight: 600,
                color: '#1d1d1f',
                letterSpacing: -0.01,
                marginBottom: 4,
              }}>{cc.m1_dropzone || 'Arrastra archivos aquí o haz clic para seleccionar'}</div>
              <div style={{
                fontSize: 11,
                color: '#6e6e73',
              }}>{cc.m1_dropzone_sub || 'Imágenes o PDF · varios permitidos'}</div>
            </>
          )}

          {/* Settled state: doc tile */}
          {docInDropzone && (
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              padding: '8px 12px',
              background: '#fff',
              borderRadius: 8,
              border: '1px solid #e8e8ed',
              animation: 'sol-tile-in 280ms ease-out',
              maxWidth: 280,
              margin: '0 auto',
            }}>
              <div style={{
                width: 32, height: 22,
                borderRadius: 4,
                background: 'linear-gradient(135deg, #fef3c7 0%, #fde68a 100%)',
                border: '1px solid #f59e0b',
                flexShrink: 0,
              }} />
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{
                  fontSize: 11.5,
                  fontWeight: 500,
                  color: '#1d1d1f',
                  fontFamily: 'ui-monospace, monospace',
                }}>licencia_fl_tomas.jpg</div>
                <div style={{
                  fontSize: 9.5,
                  color: '#6e6e73',
                }}>284 KB · imagen</div>
              </div>
              <span style={{
                width: 18, height: 18,
                borderRadius: '50%',
                background: '#34C759',
                color: '#fff',
                fontSize: 11,
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}>✓</span>
            </div>
          )}
        </div>

        {/* Crear sin captura */}
        <div style={{
          textAlign: 'center',
          marginBottom: 14,
        }}>
          <a style={{
            color: '#8b5cf6',
            fontSize: 12,
            letterSpacing: -0.005,
            cursor: 'pointer',
          }}>{cc.m1_skip || 'Crear sin captura'}</a>
        </div>

        <div style={{
          height: 1,
          background: '#f0f0f3',
          margin: '0 -24px 14px',
        }} />

        {/* Action buttons */}
        <div style={{
          display: 'flex',
          gap: 10,
          justifyContent: 'space-between',
        }}>
          <button style={{
            padding: '10px 22px',
            borderRadius: 999,
            border: '1px solid #e8e8ed',
            background: '#fff',
            color: '#1d1d1f',
            fontSize: 13,
            fontWeight: 500,
            cursor: 'pointer',
            letterSpacing: -0.005,
          }}>{cc.m1_cancel || 'Cancelar'}</button>

          <button style={{
            padding: '10px 22px',
            borderRadius: 999,
            border: '1px solid #e8e8ed',
            background: analyzing
              ? 'linear-gradient(180deg, #8b5cf6, #6d28d9)'
              : (btnPressed
                  ? '#f0f0f3'
                  : (btnHover ? '#fafafa' : '#fff')),
            color: analyzing ? '#fff' : (docInDropzone ? '#1d1d1f' : '#a1a1a6'),
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: -0.005,
            display: 'inline-flex',
            alignItems: 'center',
            gap: 8,
            cursor: 'pointer',
            transition: 'background 160ms, transform 100ms',
            transform: btnPressed ? 'scale(0.97)' : 'none',
            boxShadow: analyzing
              ? '0 4px 14px rgba(139, 92, 246, 0.35)'
              : 'none',
          }}>
            {analyzing && (
              <span style={{
                width: 12, height: 12,
                borderRadius: '50%',
                border: '2px solid rgba(255,255,255,0.4)',
                borderTopColor: '#fff',
                animation: 'sol-spin 800ms linear infinite',
                display: 'inline-block',
              }} />
            )}
            {analyzing ? (cc.m1_analyzing || 'Analizando…') : (cc.m1_analyze || 'Analizar con Sophia →')}
          </button>
        </div>
      </div>
    </ModalChrome>
  );
}

// ── Modal 2: Confirma los datos ──────────────────────────────────────
const CONFIRM_FIELDS = {
  nombre: 'TOMÁS SMITH',
  email: 'tomas.smith.fl@gmail.com',
  telefono: '4077445775',
  direccion: '8810 COMMODITY CIR',
  ciudad: 'ORLANDO',
  estado: 'FL',
  zip: '32819',
  dob: '04/12/1987',
  ssn: '4218',
};

function ConfirmaDatosModal({
  progress = 1,
  fills = {},             // map of field key → 0..1
  btnHover = false,
  btnPressed = false,
}) {
  const lang = useTimeline().lang || 'es';
  const cc = ((window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {}).case_create || {};
  const fillOf = k => Math.min(1, Math.max(0, fills[k] || 0));
  const canCreate = fillOf('email') > 0.5; // enable button once core fields are filled

  return (
    <ModalChrome width={520} progress={progress}>
      <ModalHeader
        title={cc.m2_title || 'Confirma los datos'}
        subtitle={cc.m2_subtitle || 'Revisa y corrige si algo está mal.'}
      />
      <div style={{
        padding: '14px 24px 18px',
        overflow: 'auto',
        maxHeight: 540,
      }}>
        {/* Green banner: doc identified */}
        <div style={{
          background: 'rgba(52, 199, 89, 0.10)',
          border: '1px solid rgba(52, 199, 89, 0.30)',
          borderRadius: 10,
          padding: '8px 12px',
          fontSize: 12,
          color: '#0a7a3e',
          letterSpacing: -0.005,
          marginBottom: 14,
          lineHeight: 1.4,
        }}>
          {cc.m2_detected || '✓ Licencia de conducir de Florida detectada'}
        </div>

        {/* Form fields */}
        <FieldGroup>
          <Field label={cc.m2_field_name || "NOMBRE Y APELLIDO"} value={CONFIRM_FIELDS.nombre} fillP={fillOf('nombre')} />
        </FieldGroup>

        <FieldGroup cols="1fr 1fr">
          <Field label={cc.m2_field_email || "EMAIL"} labelTag={cc.m2_field_tag_review || "REVISAR"} value={CONFIRM_FIELDS.email} fillP={fillOf('email')} />
          <Field label={cc.m2_field_phone || "TELÉFONO"} labelTag={cc.m2_field_tag_review || "REVISAR"} value={CONFIRM_FIELDS.telefono} fillP={fillOf('telefono')} />
        </FieldGroup>

        <FieldGroup>
          <Field label={cc.m2_field_address || "DIRECCIÓN"} value={CONFIRM_FIELDS.direccion} fillP={fillOf('direccion')} />
        </FieldGroup>

        <FieldGroup cols="2fr 1fr 1fr">
          <Field label={cc.m2_field_city || "CIUDAD"} value={CONFIRM_FIELDS.ciudad} fillP={fillOf('ciudad')} />
          <Field label={cc.m2_field_state || "ESTADO"} value={CONFIRM_FIELDS.estado} fillP={fillOf('estado')} />
          <Field label={cc.m2_field_zip || "ZIP"} value={CONFIRM_FIELDS.zip} fillP={fillOf('zip')} />
        </FieldGroup>

        <FieldGroup>
          <Field label={cc.m2_field_dob || "FECHA DE NACIMIENTO"} value={CONFIRM_FIELDS.dob} fillP={fillOf('dob')} />
        </FieldGroup>

        <FieldGroup>
          <Field label={cc.m2_field_ssn || "SSN ÚLTIMOS 4 (OPCIONAL)"} value={'••••'} fillP={fillOf('ssn')} mono />
        </FieldGroup>
      </div>

      {/* Footer actions */}
      <div style={{
        display: 'flex',
        gap: 10,
        justifyContent: 'space-between',
        padding: '14px 24px 20px',
        borderTop: '1px solid #f0f0f3',
        background: '#fff',
        flexShrink: 0,
      }}>
        <button style={{
          padding: '10px 20px',
          borderRadius: 999,
          border: '1px solid #e8e8ed',
          background: '#fff',
          color: '#1d1d1f',
          fontSize: 13,
          fontWeight: 500,
          letterSpacing: -0.005,
        }}>{cc.m2_back || '← Atrás'}</button>

        <button style={{
          padding: '10px 22px',
          borderRadius: 999,
          border: 0,
          background: canCreate
            ? (btnPressed
                ? '#0061d4'
                : (btnHover ? '#2289ff' : '#007AFF'))
            : '#e8e8ed',
          color: canCreate ? '#fff' : '#a1a1a6',
          fontSize: 13,
          fontWeight: 500,
          letterSpacing: -0.005,
          boxShadow: canCreate ? '0 4px 14px rgba(0, 122, 255, 0.28)' : 'none',
          transform: btnPressed ? 'scale(0.97)' : 'none',
          transition: 'transform 100ms, background 160ms',
        }}>{cc.m2_create || 'Crear cliente →'}</button>
      </div>
    </ModalChrome>
  );
}

function FieldGroup({ cols = '1fr', children }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: cols,
      gap: 10,
      marginBottom: 12,
    }}>{children}</div>
  );
}

function Field({ label, labelTag, value, fillP, mono = false }) {
  const visibleLen = Math.floor(value.length * fillP);
  const visible = value.slice(0, visibleLen);
  const isFilling = fillP > 0 && fillP < 1;
  const isFilled = fillP >= 1;

  return (
    <div>
      <div style={{
        fontSize: 9.5,
        fontWeight: 600,
        color: '#a1a1a6',
        letterSpacing: 0.12,
        marginBottom: 5,
        display: 'flex',
        alignItems: 'center',
        gap: 6,
      }}>
        {label}
        {labelTag && (
          <span style={{
            color: '#dc2626',
            fontSize: 8.5,
            fontWeight: 700,
            letterSpacing: 0.05,
          }}>({labelTag})</span>
        )}
      </div>
      <div style={{
        padding: '9px 12px',
        border: `1px solid ${isFilling ? '#007AFF' : (isFilled ? '#34C759' : '#e2e2e7')}`,
        borderRadius: 8,
        background: isFilling ? 'rgba(0,122,255,0.04)' : (isFilled ? 'rgba(52,199,89,0.06)' : '#fff'),
        fontSize: 12.5,
        color: '#1d1d1f',
        fontFamily: mono ? 'ui-monospace, monospace' : 'inherit',
        letterSpacing: mono ? 0.04 : -0.005,
        height: 36,
        boxSizing: 'border-box',
        display: 'flex',
        alignItems: 'center',
        transition: 'border-color 240ms, background 240ms',
      }}>
        {visible}
        {isFilling && (
          <span style={{
            display: 'inline-block',
            width: 1, height: 12,
            background: '#007AFF',
            marginLeft: 2,
            animation: 'sol-caret 0.6s steps(1) infinite',
          }} />
        )}
      </div>
    </div>
  );
}

// ── Modal 3: Nuevo caso para [cliente] ───────────────────────────────
const MODULE_CARDS = [
  { key: 'taxes',     name: 'Taxes',         descKey: 'mod_taxes_desc',     color: '#007AFF', bg: '#dbeafe', icon: '$', locked: false },
  { key: 'migracion', name: 'Migración',     descKey: 'mod_migracion_desc', color: '#FF9500', bg: '#ffedd5', icon: '🌐', locked: false },
  { key: 'insurance', name: 'Insurance',     descKey: 'mod_insurance_desc', color: '#34C759', bg: '#dcfce7', icon: '🛡', price: '$41.30/mes', discount: '-30%', locked: true },
  { key: 'credit',    name: 'Credit Repair', descKey: 'mod_credit_desc',    color: '#a855f7', bg: '#f3e8ff', icon: '📊', price: '$41.30/mes', discount: '-30%', locked: true },
  { key: 'business',  name: 'Business',     descKey: 'mod_business_desc', color: '#3b82f6', bg: '#dbeafe', icon: '🏢', price: '$49.00/mes', locked: true },
  { key: 'legal',     name: 'Legal',        descKey: 'mod_legal_desc',    color: '#ef4444', bg: '#fee2e2', icon: '⚖️', price: '$99.00/mes', locked: false },
];

function NuevoCasoModal({
  progress = 1,
  hoveredKey = null,    // which card cursor is hovering
  selectedKey = null,   // which card has been clicked
  cardPressed = false,  // card being clicked
}) {
  const lang = useTimeline().lang || 'es';
  const cc = ((window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {}).case_create || {};
  return (
    <ModalChrome width={560} progress={progress}>
      <ModalHeader
        title={(cc.m3_title_pre || 'Nuevo caso para ') + 'TOMÁS SMITH'}
        subtitle={cc.m3_subtitle || '¿Para qué módulo abrimos el caso? Sus datos se prellenan automáticamente.'}
      />
      <div style={{
        padding: '14px 24px 14px',
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: 10,
      }}>
        {MODULE_CARDS.map(m => {
          const isHover = hoveredKey === m.key && !m.locked;
          const isSelected = selectedKey === m.key;
          const isPressed = cardPressed && isSelected;
          return (
            <div
              key={m.key}
              data-module={m.key}
              style={{
                position: 'relative',
                background: '#fff',
                border: `1.5px solid ${isSelected ? m.color : (isHover ? '#c7c7cf' : '#e8e8ed')}`,
                borderRadius: 12,
                padding: '14px 14px 12px',
                opacity: m.locked ? 0.68 : 1,
                cursor: m.locked ? 'not-allowed' : 'pointer',
                boxShadow: isSelected
                  ? `0 6px 18px ${m.color}33, 0 0 0 3px ${m.color}11`
                  : (isHover ? '0 4px 12px rgba(0,0,0,0.06)' : 'none'),
                transform: isPressed ? 'scale(0.985)' : (isHover ? 'translateY(-1px)' : 'none'),
                transition: 'transform 140ms, box-shadow 200ms, border-color 200ms',
              }}>
              {/* Icon tile */}
              <div style={{
                width: 38, height: 38,
                borderRadius: 9,
                background: m.bg,
                color: m.color,
                fontSize: 18,
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 8,
              }}>{m.icon}</div>

              {/* Lock badge */}
              {m.locked && (
                <div style={{
                  position: 'absolute',
                  top: 10, right: 10,
                  width: 18, height: 18,
                  borderRadius: '50%',
                  background: '#f5f5f7',
                  color: '#6e6e73',
                  fontSize: 11,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>🔒</div>
              )}

              <div style={{
                fontSize: 14.5,
                fontWeight: 600,
                color: m.color,
                letterSpacing: -0.01,
                marginBottom: 4,
              }}>{m.name}</div>
              <div style={{
                fontSize: 11,
                color: '#6e6e73',
                lineHeight: 1.4,
                marginBottom: m.price ? 10 : 0,
                letterSpacing: -0.005,
              }}>{cc[m.descKey] || m.desc}</div>
              {m.price && (
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                  fontSize: 11,
                }}>
                  <span style={{
                    color: '#FF9500',
                    fontWeight: 600,
                    fontFamily: 'ui-monospace, monospace',
                  }}>{m.price}</span>
                  {m.discount && (
                    <span style={{
                      background: '#dcfce7',
                      color: '#16a34a',
                      padding: '1px 6px',
                      borderRadius: 4,
                      fontWeight: 600,
                      fontSize: 9.5,
                    }}>{m.discount}</span>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div style={{
        display: 'flex',
        justifyContent: 'flex-end',
        padding: '4px 24px 18px',
      }}>
        <button style={{
          padding: '9px 20px',
          borderRadius: 999,
          border: '1px solid #e8e8ed',
          background: '#fff',
          color: '#1d1d1f',
          fontSize: 13,
          fontWeight: 500,
          letterSpacing: -0.005,
        }}>{cc.m3_cancel || 'Cancelar'}</button>
      </div>
    </ModalChrome>
  );
}

// ── Modal 4: Caso Taxes (año + tipo + origen) ────────────────────────
function CasoTaxesModal({
  progress = 1,
  year = '2026',
  declType = 'original',   // 'original' | '1040x' | '4868'
  origin = 'cero',          // 'cero' | 'copiar'
  conjunta = false,
  btnHover = false,
  btnPressed = false,
}) {
  const lang = useTimeline().lang || 'es';
  const cc = ((window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {}).case_create || {};
  return (
    <ModalChrome width={510} progress={progress}>
      <ModalHeader
        title={(cc.m4_title_pre || 'Caso Taxes para ') + 'TOMÁS SMITH'}
        subtitle={cc.m4_subtitle || '¿Qué año y tipo de declaración?'}
      />
      <div style={{ padding: '14px 24px 14px', overflow: 'auto', maxHeight: 540 }}>
        {/* Año fiscal */}
        <div style={{ marginBottom: 14 }}>
          <div style={{
            fontSize: 9.5,
            fontWeight: 600,
            color: '#a1a1a6',
            letterSpacing: 0.12,
            marginBottom: 6,
          }}>{cc.m4_section_year || 'AÑO FISCAL'}</div>
          <div style={{
            padding: '10px 14px',
            border: '1px solid #e2e2e7',
            borderRadius: 8,
            background: '#fff',
            fontSize: 13,
            color: '#1d1d1f',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <span style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: 0.04 }}>{year}</span>
            <span style={{ color: '#a1a1a6', fontSize: 10 }}>▼</span>
          </div>
        </div>

        {/* Tipo de declaración */}
        <div style={{ marginBottom: 14 }}>
          <div style={{
            fontSize: 9.5,
            fontWeight: 600,
            color: '#a1a1a6',
            letterSpacing: 0.12,
            marginBottom: 8,
          }}>{cc.m4_section_type || 'TIPO DE DECLARACIÓN'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
            <RadioCard
              selected={declType === 'original'}
              title={cc.m4_type_original || "Original"}
              desc={cc.m4_type_original_desc || "Declaración del año por primera vez (Form 1040)."} />
            <RadioCard
              selected={declType === '1040x'}
              title={cc.m4_type_amend || "Enmienda 1040X"}
              desc={cc.m4_type_amend_desc || "Corregir una declaración ya presentada."} />
            <RadioCard
              selected={declType === '4868'}
              title={cc.m4_type_extension || "Extensión 4868"}
              desc={cc.m4_type_extension_desc || "Pedir 6 meses extra (vence Oct 15)."} />
          </div>
        </div>

        {/* Checkbox declaración conjunta */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '8px 0',
          marginBottom: 10,
          fontSize: 12,
          color: '#1d1d1f',
        }}>
          <span style={{
            width: 14, height: 14,
            border: `1.5px solid ${conjunta ? '#007AFF' : '#c7c7cf'}`,
            background: conjunta ? '#007AFF' : '#fff',
            color: '#fff',
            borderRadius: 3,
            fontSize: 10,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontWeight: 700,
          }}>{conjunta ? '✓' : ''}</span>
          <span>¿Declaración conjunta? (después pediremos info del cónyuge)</span>
        </div>

        {/* Origen de los datos */}
        <div>
          <div style={{
            fontSize: 9.5,
            fontWeight: 600,
            color: '#a1a1a6',
            letterSpacing: 0.12,
            marginBottom: 8,
          }}>{cc.m4_section_origin || 'ORIGEN DE LOS DATOS'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
            <RadioCard
              selected={origin === 'cero'}
              title={cc.m4_origin_blank || "Crear desde cero"}
              desc={cc.m4_origin_blank_desc || "Captura toda la información manualmente."} />
            <RadioCard
              selected={origin === 'copiar'}
              accentColor="#34C759"
              title={<span>{cc.m4_origin_copy || 'Copiar del caso Taxes anterior'} <span style={{
                marginLeft: 8,
                padding: '2px 7px',
                background: '#dcfce7',
                color: '#16a34a',
                borderRadius: 4,
                fontSize: 9,
                fontWeight: 700,
                letterSpacing: 0.06,
              }}>{(cc.m4_origin_copy_badge || 'Recomendado').toUpperCase()}</span></span>}
              desc={lang === 'en' ? 'No previous Taxes case for this client.' : 'No hay caso Taxes anterior de este cliente.'} />
          </div>
        </div>
      </div>

      <div style={{
        display: 'flex',
        gap: 10,
        justifyContent: 'space-between',
        padding: '12px 24px 18px',
        borderTop: '1px solid #f0f0f3',
        flexShrink: 0,
      }}>
        <button style={{
          padding: '10px 20px',
          borderRadius: 999,
          border: '1px solid #e8e8ed',
          background: '#fff',
          color: '#1d1d1f',
          fontSize: 13,
          fontWeight: 500,
        }}>{cc.m4_back || '← Atrás'}</button>

        <button style={{
          padding: '10px 24px',
          borderRadius: 999,
          border: 0,
          background: btnPressed ? '#0061d4' : (btnHover ? '#2289ff' : '#007AFF'),
          color: '#fff',
          fontSize: 13,
          fontWeight: 500,
          letterSpacing: -0.005,
          boxShadow: '0 4px 14px rgba(0, 122, 255, 0.28)',
          transform: btnPressed ? 'scale(0.97)' : 'none',
          transition: 'transform 100ms, background 160ms',
        }}>{cc.m4_start || 'Continuar →'}</button>
      </div>
    </ModalChrome>
  );
}

function RadioCard({ selected, accentColor = '#007AFF', title, desc }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'flex-start',
      gap: 10,
      padding: '9px 12px',
      border: `1.5px solid ${selected ? accentColor : '#e2e2e7'}`,
      borderRadius: 8,
      background: selected ? `${accentColor}0d` : '#fff',
      transition: 'border-color 200ms, background 200ms',
    }}>
      <span style={{
        width: 16, height: 16,
        borderRadius: '50%',
        border: `1.5px solid ${selected ? accentColor : '#c7c7cf'}`,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 1,
        flexShrink: 0,
      }}>
        {selected && (
          <span style={{
            width: 8, height: 8,
            borderRadius: '50%',
            background: accentColor,
          }} />
        )}
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 12.5,
          fontWeight: 600,
          color: '#1d1d1f',
          letterSpacing: -0.005,
          marginBottom: 2,
        }}>{title}</div>
        <div style={{
          fontSize: 11,
          color: '#6e6e73',
          letterSpacing: -0.005,
        }}>{desc}</div>
      </div>
    </div>
  );
}

// ── Wrapper: drives which modal is visible ──────────────────────────
function CaseCreationModal({ step = 0, ...props }) {
  return (
    <>
      <ModalBackdrop progress={step > 0 ? 1 : 0} />
      {step === 1 && <NuevoClienteModal {...props} />}
      {step === 2 && <ConfirmaDatosModal {...props} />}
      {step === 3 && <NuevoCasoModal {...props} />}
      {step === 4 && <CasoTaxesModal {...props} />}
    </>
  );
}

// Animations
if (typeof document !== 'undefined' && !document.getElementById('sol-modal-anim')) {
  const s = document.createElement('style');
  s.id = 'sol-modal-anim';
  s.textContent = `
    @keyframes sol-spin {
      from { transform: rotate(0deg); }
      to   { transform: rotate(360deg); }
    }
    @keyframes sol-caret {
      50% { opacity: 0; }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, {
  CaseCreationModal,
  ModalBackdrop, ModalChrome, ModalHeader,
  NuevoClienteModal, ConfirmaDatosModal, NuevoCasoModal, CasoTaxesModal,
});
